ahax
ahax

Reputation: 81

AJAX request to perform search in Flask

I'm trying to make a search feature with AJAX. I mean, I click in the button to the right of an input box, and then it shows the results without reloading the page. See here my HTML to show that input form (frontend) in the current home page.

<li>
    <p><input type="text" size="18" name="query"><br>
    <span id=result>?</span>
    <p><a href="/search" id=search>Go!</a>
</li>

Then I created a javascript file to make that AJAX request to be performed. See:

$(function() {
var submit_form = function(e) {
  $.getJSON('/search', {
    query: $('input[name="query"]').val()
  }, function(data) {
    $('#result').text(data.result);
    $('input[name=query]').focus().select();
  });
  return false;
};
$('a#search').bind('click', submit_form);

My "/search" route is defined as so:

@home_blueprint.route('/search')
def search():
    sql = 'SELECT "publicName", "completeName" FROM "politics" WHERE '
    politicDict = request.args.get('query', 'No results were found', type=text)
    print politicDict # It returns 'No results were found'
    return render_template('home.html')

So, let's suppose I wrote "diogo" in that input form (so its val() should be "diogo"). So, the url request should be something like this:

http://localhost:5000/search?query=diogo

and here it is what I get:

http://localhost:5000/search, and for that reason I get politicDict (python file) to be 'None' instead of 'diogo'

Any help would be much grateful,

Best regards.

Edit: fixed Python formatting issue.

Upvotes: 4

Views: 2568

Answers (1)

Kartikeya Sharma
Kartikeya Sharma

Reputation: 1383

This might be very late but it can help others who are stuck on the similar problems! Some of your mistakes are:

  1. you are not calling preventDefault() which prevents the default behavior.
  2. You are not return a proper JSON data back from your flask method as you should make two different methods, one for rendering your page and other to get the data(API)

Here, I propose my solution:

HTML and Javascript code

<html>
  <li>
    <p><input type="text" size="18" name="query"></p>
    <br>
    <span id=result>?</span>
    <p><a href="/search" id=search>Go!</a></p>
  </li>
  <div id="result">
   Results will appear here!
  </div>
</html>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" crossorigin="anonymous"></script>
<script>
$(document).on("click", "#search", function (e) {
    e.preventDefault();
        var search_term = $('input[name=query]').val().toLowerCase();
    console.log(search_term )
        $.ajax(
            {
                type: "GET",
                url: "{{url_for('search')}}",
                data: { "query": search_term },
                success: function (response) {
                        $("#result").empty(); //remove whatever is there and append whatever is returned
            $("#result").append(response.result) //append whatever you want to append
                }
            }
        )
    });
</script>

flask code

@home_blueprint.route('/home')
def home():
    return render_template('home.html')

@home_blueprint.route('/search')
def search():
    sql = 'SELECT "publicName", "completeName" FROM "politics" WHERE '
    politicDict = request.args.get('query') # get the data
    print politicDict # It returns 'No results were found'
    return {"result":politicDict} #you can return whatever result you get from SQL here but I am just
                       # returning the data you sent.

Upvotes: 1

Related Questions