Question

I have a form where the user types in a search term:

<form class="navbar-form navbar-left" role="search">
   <div class="form-group">
       <input type="text" class="form-control" id="search-val" placeholder="Search">
   </div>
   <button type="submit" class="btn btn-default" id="search-btn">Submit</button>
</form>

I want to get that user input and call a certaing page. For example /index?search_term=foo

I have tried doing it with JQuery with things like:

$('#search-btn').on('click',function(){
    var search_term = $('#search-val').val();
    $.get( "/?search_term="+search_term);
});

On the Python side, I try to access the parameter like this:

s = request.args.get('search_term', '')

But it is not working. The page just refreshes and Python doesn't receive the search_term. I am new to Flask so please bear with me.

Was it helpful?

Solution

You are forgetting to cancel the default action, which is to submit the page:

$('#search-btn').on('click',function(){
    var search_term = $('#search-val').val();
    $.get( "/?search_term="+search_term);
    return false;
});

Without the return false the browser will happily also submit the form itself, which in this case means it'll use GET on the same URL as the page (there is no action attribute). This in turn cancels any pending AJAX requests as well.

Of course, your $.get() call still doesn't do anything on the browser-side, but at least by cancelling the default form action, you get to see a server-side effect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top