title: Django AJAX Search simplification/show all on page load
body: <p>I have made a successful AJAX search box, but being fairly new, I was wondering if there was a better way to write this code. I am using <code>Python 3.6</code> and <code>Django 2</code>. Also, I want to display all entries on page load, which currently displays nothing. If I enter text and delete it, then all my entries show, but not on initial load. Thanks!</p>
  
  <p>views.py</p>
  
  <pre><code>    def search_ajax(request):
  
          if request.method == 'POST':
              search_text = request.POST['search_text']
              if ',' in search_text:
                  last,first = search_text.split(",")
                  name_search = PhoneBook.objects.filter(last_name__istartswith=last.strip()
              ).filter(first_name__istartswith=first.strip())
              else:
                  name_search = PhoneBook.objects.filter(last_name__istartswith=search_text.strip())
  
              phone_search = search = PhoneBook.objects.filter(number__icontains=search_text.strip())
              if search_text != "":
                  search = list(chain(name_search, phone_search))[:10]
              else:
                  search = list(chain(name_search, phone_search))
              print(search)
              context={'search':search,}
              html = render_to_string('search_ajax_results.html', context)
              return HttpResponse(html, content_type="application/json")
  </code></pre>
  
  <p>ajax_script.js</p>
  
  <pre><code>    $(function(){
  
          $('#search_ajax_input').keyup(function(){
          $.ajax({
              type:"POST",
              url:"search-ajax/",
              data:{
                  'search_text': $('#search_ajax_input').val(),
                  'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
              },
              success: searchSuccess,
              dataType: 'html'
          });
          });
      });
  
      function searchSuccess(data, textStatus,jqXHR)
      {
          $('#search-ajax-results').html(data);
      };
  </code></pre>