Supun Manathunga Supun Manathunga - 1 year ago 63
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

function, it works fine. Console shows
XHR finished loading

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



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



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
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>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download