Supun Manathunga Supun Manathunga - 1 month ago 11
Javascript Question

Jquery ajax get request not working inside on click function

I am writing a web page which shows restaurants in a specified city.
Back end is a node server which uses yelp API for getting results and forwards it as JSON.

In the javascript file, when I call the ajax get method inside

document.ready()
function, it works fine. Console shows
XHR finished loading
.

But when I run it inside jquery click function like this, it doesn't work.

$(document).ready(function(){

$('#btn').click(function(){

var city = $('#city').val();
var post = $.ajax({
url: "/query?city=" + city,
type: "GET"
});

post.done(function(json){
window.alert('ok');
});

post.fail(function(json){
window.alert('failed');

});
});
});


It alerts 'failed' and console says
XHR failed loading: GET "http://localhost/query?city=colombo".


But in the node server it takes the request and processes. When I directly paste
http://localhost/query?city=colombo
into address bar of the browser or to Postman, it gets the request.

Can you please explain me why it only fails inside jquery click function, but works fine outside it...

Answer Source

I'm not sure but it could be this:

In your HTML button you're missing the type attribute

<button type="button" id="btn" class="btn btn-block col-8">Search</button>