views:

168

answers:

2

I have looked at similar queries here, but I can't seem to apply them to my problem. I am pretty new to jquery, so I may be doing something dumb. I have a simple getJSON test:

 $(document).ready(function() {
  $(".testurl").click(function() {
   // do a json call
   var url="testjson.php";
   var rc=$.getJSON(
    url,
    {parm1: "P1", parm2: "P2", parm3: "P3"},
    function(data){
     alert("callback function inline");
   });
   var x = 1;
  });
 });

that calls a really simple script:

  header("Content-Type: application/json");
  echo "{\"results\": [";
  $arr = array();
  $arr[] = "{\"fld1\": \"result1\", \"fld2\": \"result2\", \"fld3\": \"result3\"}";
  echo implode(", ", $arr);
  echo "]}";

that returns valid JSON (I checked on JSON lint)

The var rc that I use to receive the result of the request has the following values:

getResponseText \"{\"results\": [{\"fld1\": \"result1\", \"fld2\": \"result2\", \"fld3\": \"result3\"}]}\"" 
getReadyState 4
getStatus 200

Why does the callback function not fire?

+1  A: 

If the click handler is attached to an anchor element then maybe the ajax call doesn't have time to execute before redirecting to a different page. Try adding a return false to the click callback:

$(".testurl").click(function() {
    // do a json call
    // ...
    return false;
});
Darin Dimitrov
the anchor element has a href of #, so it stays on the page. I'm only attaching to that element as a really basic test page for trying this JSON stuff.
WaveyDavey
It was that - I added return false, and the callback triggered. How very odd - I'd have thought an anchor link would have let the call complete.Many thanks.
WaveyDavey
A: 

The $.getJSON call is just assigned to a variable, it is not being called.

Ralph Stevens
I assigned it to a variable just to see what the results were. When I remove the assignment, the function still does not trigger.
WaveyDavey