tags:

views:

88

answers:

4

Hi guys,

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?

A: 

Is there any error returned from firebug?

I'd start by changing:

$.getJSON("http://localhost/jsontest/a.json?callback=?", function(data) {

to:

$.getJSON("http://localhost/jsontest/a.json", 'callback=?', function(data) {
Fotis
No errors returned from Firefox - I tried it with ...a.json?callback=? - still never worked.It works now - the alert(data.done) did the trick.Thanks guys :-)
icecreamsoop
So when you said "the alert is not displayed", you meant, "the alert happens but it just contains the word 'done'"?
Pointy
A: 

The alert is at the wrong place. It should be the callback parameter. http://api.jquery.com/jQuery.getJSON/

airmanx86
?? It **is** in the callback function.
Pointy
+1  A: 

Try this:

$.getJSON("http://localhost/jsontest/a.json", { }, function(data) {
    alert(data.done);
});
Matthew Abbott
That is not necessary. If jQuery sees that the second parameter is a function, it assumes that the call looks like the call in the original question.
Pointy
+1 - The ` { },` portion is not needed, the callback can be the second param, but the `alert(data.done)` (instead of the string `"done"`) is correct.
Nick Craver
Well yes, but he says the alert is not displayed. @Nick you're the acknowledged master of spotting "forgot to put code in a 'ready' handler" problems!!
Pointy
A: 

I'm betting on this: you forgot to put that setup code in a <script> block after your "click" element, or in a "ready" handler:

$(function() {
  $('#click').click(function() { /* ... same stuff as you have ... */ });
});
Pointy