4

I have two functions that make $.getJSON calls - one looks at JSON stored on server, and the other one makes a call to Flickr.

I have this:

$(document).ajaxStart(function(){ 
        alert('requeststart');
        //$('#loading').show(); 
    });

which works when $.getJSON is called with some given path, but it does not raise an alert when $.getJSON makes the call to Flickr. The Flickr call works, and everything loads as it should... it doesn't fire ajaxStart however. (I'm using ajaxStart and ajaxStop to show a loading-gif)

Any ideas?

Here is the function that calls Flickr :

$('#submit').on("click", function (evt) {
    evt.preventDefault();
    var tag = $('input').val();
    if (tag == "") {
        alert("please enter a tag");
    }
    else {
      $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",{tags: tag, tagmode: "any", format: "json" },
      function(data) {
        $.each(data.items, function(i,item){
            var name = names[index];
            $("#" + name).empty();
            $('<img src="' + item.media.m.replace("_m.jpg", ".jpg") + '" />').appendTo("#" + name);
            $('<a href="' + item.link + '"> ' + item.title + '</a>').appendTo("#" + name );
            index ++;
            if (i==5) { 
                index = 0;
                }       
        });
      });
    }
});
sooks
  • 668
  • 1
  • 8
  • 20

2 Answers2

6

jQuery only fires those events (ajaxStart and ajaxStop) if it internally uses the XMLHttpRequest object.

However if you request data from a different domain using a callback parameter (JSONP), jQuery does not use XMLHttpRequest, instead it accomplishes that by inserting a <script> tag.

That's why the events get not fired.


As a workaround you could start your loading animation just before the $.getJSON call, and stop it inside the function(data) {.. block.
stewe
  • 39,054
  • 13
  • 75
  • 73
0

for multiply requests you have too count them individually. I did it like this:

var loader = 0;       
function showloader(cnt){
    loader = loader + cnt;
     if(loader < 1) {
        $('#loading').hide();
      } else {
        $('#loading').show();
      }
}

increase by 1 and call it before $.getJSON and decrease it and fire again when its done. like:

showloader(1);
$.getJSON( 
   [...] 
 }).done(function() { 
   showloader(-1);
   [...]
});