jQuery.getJSON doesn't trigger callback
Asked Answered
G

4

25

I have a html code:

<button>asd</button>
<script type = "text/javascript">
$('button').click(
    function() {
        $.getJSON('/schedule/test/', function(json) {
            alert('json: ' + json + ' ...');
        });
    }
);
</script>

and corresponding view:

def test(request):
    if request.method == 'GET':
        json = simplejson.dumps('hello world!')
        return HttpResponse(json, mimetype = 'application/json')

The view is executed (tested using print), json variable is initialised but no alert appears. What did I do wrong? I've already seen some docs on this (http://docs.jquery.com/Ajax/jQuery.getJSON#urldatacallback for example) but I didn't find an answer.

EDIT: The problem was, that HttpResponse was not imported... Unfortunately Django gave no error about it. Everything else was correct. regards
chriss

Goar answered 21/2, 2009 at 13:31 Comment(1)
Have you backed up and tried it as plain text just for kicks?Bobette
G
47

It is likely that the json is not properly formed. Sometimes this happens to me when my code, that should be producing json is generating an error. Two options:

  • Use firebug to view the JSON response

  • Setup error handling in your jquery code using the jQuery.ajaxSetup options such as:

      $.ajaxSetup({"error":function(XMLHttpRequest,textStatus, errorThrown) {   
          alert(textStatus);
          alert(errorThrown);
          alert(XMLHttpRequest.responseText);
      }});
    

Using the error handling for debugging is great, since you will know immediately when there is a problem with your response. You can check out the jQuery documentation for jQuery.ajax which has all of the available options for jQuery.ajaxSetup.

EDIT: A third option would be to just open the URL that should be generating the JSON and run the output through JSON Lint to validate it.

Grind answered 21/2, 2009 at 13:52 Comment(3)
Could you point me to, or explain, how to check JSON with FireBug?Goar
Sure. I'm assuming that you have FireBug installed in FF, let me know if you do not. FireBug keeps track of all of your ajax request in the XHR tab. Expand the request there and click on the 'response' tab. You will see the JSON or other response text there. Good luck!Grind
You need to close one more curly bracket in the code you provided.Benge
P
3

Are you sure the JSON is valid? take a look at the response directly or use Firebug

Phlegethon answered 21/2, 2009 at 13:38 Comment(0)
B
1

I ran into this a while back and rewrote a wrapper for jQuery's Ajax which allows you to pass the normal getJSON and an additional error callback per get.

http://www.nurelm.com/themanual/2010/08/09/self-indulgent-code-jquery-getjson-with-error-handling/

Berne answered 24/8, 2010 at 19:27 Comment(0)
S
0

I think you are missing the trailing $ in url pattern.

Shontashoo answered 28/4, 2011 at 18:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.