0

I have the following snippet of code:

$('input#teamName').live('blur', function() {
  var value = $(this).val();
  if (value) {
    $.getJSON('api/event_company/'+value, function(data) {
      console.log('why does this not want to work?');
    });
  }
});

Basically all it's doing is requesting some data from the server when a form field changes. My problem is that nothing in the callback function every gets called even though I can see using firebug that it has successfully sent a request to the server and received a valid JSON response.

If I change the getJSON parameters to:

$.getJSON('api/event_company/'+value, alert('Blah'));

Then the alert pops up as expected. Any ideas what might be causing this behavior?

1
  • 1
    Not sure about the first one, but the reason the alert('Blah') works is because you're not passing it as a callback. You're calling the alert() and passing its return value, which is undefined. Commented Sep 8, 2010 at 16:08

1 Answer 1

4

If the JSON is invalid, the parsing will fail and the handler won't be called. From getJSON docs:

Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript's object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see http://json.org/.

See if your JSON validates.

Your second example is not correct. It should instead be,

$.getJSON('api/event_company/'+value, function() {
    alert('Blah');
});
Sign up to request clarification or add additional context in comments.

1 Comment

Arg. I forgot that I was outputting some extra data when I was debugging things earlier so I wasn't actually returning valid JSON. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.