0

can u please help me. I want to create search using ajax function and django view. There are input and submit button. When I clicked on submit button, jQuery takes value of input and create ajax request. Its good. But in the view, when i want to print serch_by value in console, there is an output:

None qwer asdf zxvc <- value of input

I think it is a problem. But maybe no. Help me, please.

HTML:

<form id="searchform" {% csrf_token %}
  <input name="q" type="text" id="search">
  <button type="submit" id="searchsubmit"></button>
</form>

JS:

function initSearchForm(){
    $('#searchsubmit').on('click', function(e){
        e.preventDefault();
        q = $('#search').val();
        updateContentBySearch(q);
  });
}
function updateContentBySearch(q) {
    var data = {};
    data['search_by'] = q
    data["csrfmiddlewaretoken"] = $('#searchform [name="csrfmiddlewaretoken"]').val();
    $.ajax({
        url: "/search_products/",
        type: 'GET',
        data: data,
        success:
            $('.product_content').load(url, function() { ...
            }),
        });

    }

View:

def search_products(request):
     data = request.GET
     search_by = data.get('search_by')
     print(search_by) # The console is displayed first 'None' and at 
                      # the next line value of search_by
if search_by:
    q = Q()
    for tag in search_by.split():
        q |= Q(brand__brand_name__iexact=tag) | Q(model__iexact=tag)
    products = Product.objects.filter(q)

return render(request, 'main/product_content.html', {'products': product})

1 Answers1

0
  $.ajax({
        url: '/search-products/',
        data: {
          'search_by': q
        },
        dataType: 'json',
        success: function (data) {
            // do your thing
        }
      });
Samuel Omole
  • 185
  • 1
  • 7