1

I'm trying to display a loading image after an AJAX call has been made.

Currently I have the following Javascript code:

window.onload = function(){

var img = document.createElement("IMG");
img.src = "http://i.stack.imgur.com/FhHRx.gif";

function getCategories(){
    $.ajax({
        url: //url here,
        dataType:'jsonp',           
        success: function(data){

            //code here

        },
        statusCode: {
            404: function() {
                alert:('There was a problem with the server');
            }
        }

    }); 
}



$(document).ajaxStart(function(){   
    alert('here');
    var div = document.createElement("div");
    div.id = "id1";
    document.getElementById('id1').appendChild(img);
    document.body.appendChild(div);

}).ajaxStop(function(){
    var element = document.getElementById('id1');
    element.parentNode.removeChild(element);

});

However, I am finding that the code is not even getting to the ajaxStart function as the alert is not appearing... I have tried other methods (eg: How to show loading spinner in jQuery?) to try and get this working but have not been successful as of yet...

Would anyone be able to help with this please?

Thank you.

Community
  • 1
  • 1

2 Answers2

0

You are more than likely getting an error for Unexpected Token, since you are declaring a function incorrectly.

Uncaught SyntaxError: Unexpected token { 

You need to declare a function with either:

function getCategories () { }

Or:

var getCategories = function () { };
Mark Pieszak - Trilon.io
  • 44,537
  • 13
  • 74
  • 89
0

I think I found the solution here ($(document).ajaxstart not firing)

It seems that ajaxStart only works when XMLHttpRequest is used. If you use JSONP, XMLHttpRequest isn't used. Rather, it inserts a <script> tag to achieve this goal.

I simply used the workaround suggested in the above link.

Community
  • 1
  • 1