Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .getJSON not working

Tags:

json

jquery

ajax

I'm just learning how to utilise ajax/json with jquery and I've hit a brick wall that I just don't understand.

Here is my code - VERY simple code:

$("#click").click(function() {
    $.getJSON("http://localhost/jsontest/a.json", function(data) {
        alert("done"); 
    });

   });

Basically, load a.json and send an alert to the screen saying done.

Here are the contents of a.json:

{ "done": "37" }

That's it.

It doesn't work though... the alert is not displayed.

Any ideas folks?

like image 681
icecreamsoop Avatar asked May 04 '26 09:05

icecreamsoop


1 Answers

I just had an issue where I didn't format the data in the file that it's retrieving right. If the JSON in the file has anything wrong with it, it fails silently. Though you can always add .fail(function) to detect the fail.

I was using: { varname:"my string" }

When I should have been using: { "varname":"mystring" }

For this reason I think it might be better to use get to retrieve the data with $.get() and then use JSON.parse() on it. This way you know whether the get or the parse failed.

like image 179
Grallen Avatar answered May 07 '26 00:05

Grallen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!