Home > database >  How to return related value from database after click function by ajax in django?
How to return related value from database after click function by ajax in django?

Time:11-24

html

  <div>           
  
 {{ productform.vendorid|as_crispy_field }}<a id="vendor_id_search" class="btn btn-info">search</a></br>
    
    <div style="display:none;" id="show_vendorname">hjkh</div><br>
 </div>
 


 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>




 <script>
$("#vendor_id_search").click(function (event) {
    event.preventDefault();
    var vendor_id = $("#id_vendorid").val();

  $.ajax({
    url: '/ajax/find_vendorname/',
    method: 'GET',
    data: {
      'vendor_id': vendor_id
    },
    dataType: 'json',
    success: function (data) {
        $("#show_vendorname").show(data)
    }
  });

});

views.py

 #vendor_name_find_ajax
 def find_vendorname(request):
     if request.is_ajax():
         vendorid = request.GET.get('vendor_id', None)
         username = CustomUser.objects.filter(first_name=vendorid)
         return username

I want to display the related name from the database table for that vendorid after the user typed the vendorid field and once clicked the button, the related name should be displayed on that particular div. Here, I have made a mistake and don't know to get that value.

CodePudding user response:

$("#show_vendorname").show(data) unhide the div, but don't set in the data.

You need set the data before with $.html()

$("#show_vendorname").html(data).show()

EDIT:

Besides, your view needs to return a HttpResponse:

from django.http import HttpResponse

def find_vendorname(request):
     if request.is_ajax():
         vendorid = request.GET.get('vendor_id', None)
         username = CustomUser.objects.filter(first_name=vendorid)
         return HttpResponse(username)
  • Related