qwerty qwerty - 4 months ago 24
Ajax Question

AJAX GET request works only after pressing back and trying again

I have the weirdest bug that I do not understand. I am using Spring Boot with thymeleaf and have an AJAX GET request.

Basically, I am making a REST search service that uses String parameter to query mongoDB. My REST API works fine, I can query anything I want, however the issue starts if I want to use my search REST API via the search box on results page.

When I press "Search" on the search box, my request is being sent, but I am being redirected to "Bad Request 400 - Required String parameter 'searchQuery' is not present". However, when I press back button in browser and type any query, the one that did not previously work is sent instead. Is my AJAX request incorrect, is there something to do with the way Thymeleaf works or other magic?

This is my AJAX request:

var searchQuery = document.getElementById("search_input").value;

function doAjax() {
$.ajax({
url: "/search",
type: 'GET',
data: {
searchQuery: searchQuery
}
}).success(function (data) {
window.location.href = "/search?searchQuery=" + searchQuery;
});

alert("yay2");
}


And this is my HTML:

<form>
<label for="search_input">Search:</label>
<input type="text" id="search_input"></input>
<button onclick="doAjax()">GO</button>
</form>


This is exactly what happens (I may not be explaining myself clearly as I am a beginner): SEE THIS GIF I MADE

Answer

2 things:

  1. You need to put var searchQuery = document.getElementById("search_input").value; inside the doAjax() function. Right now it gets the value only once - on page load.
  2. You need to prevent button default action - submitting the form. E.g. <button onclick="doAjax();" type="button">GO</button> (type="submit" is default if type is not specified and will submit the form, type="button" will not.

        function doAjax() {
            var searchQuery = document.getElementById("search_input").value;
            $.ajax({
                url: "/search",
                type: 'GET',
                data: {
                    searchQuery: searchQuery
                }
            }).success(function (data) {
                    window.location.href = "/search?searchQuery=" + searchQuery;
            });
    
            alert("yay2");
        }
    

HTML:

<form>
   <label for="search_input">Search:</label>
   <input type="text" id="search_input"></input>
   <button onclick="doAjax()" type="button">GO</button>
</form>