-1

I have this code :

data = new FormData($('#form')[0]);
$.ajax({
    type: 'POST',
    url: 'systems/createpostsystem.php',
    data: data,
    cache: false,
    contentType: false,
    processData: false
}).done(function(data) {
    alert(data);
    window.location = "myposts.php";
});

I have used $.ajaxStart() and it didn't do what I want.

Also I tried success:function(){my code} and made my request twice !

Now I want to show a progress image while this AJax complete.

Ahmed Essam
  • 162
  • 1
  • 9

2 Answers2

3

Add your loading image (I'm assuming a gif) before executing your ajax function. On success, remove the image and replace it with whatever you desire (success image, data returned from server, etc).

Example:

var formData = new FormData($('#form')[0]);
var imageContainer = $('#selector');
imageContainer.attr('src', 'path/to/loading.gif');
$.ajax({
    type: 'POST',
    url: 'systems/createpostsystem.php',
    data: formData,
    success: function(data) {
        // Do something
    }
});

putipong
  • 350
  • 1
  • 9
0

You just need to edit the DOM before doing the AJAX request, adding your loader, and then to remove it in the complete callback. I usually use the jQuery callback functions rather than the XHR object callbacks.

Mind that:

  • the success callback (and the done XHR callback) is called only when the request completes successfully
  • the complete (and the always XHR callback) is called always, even if the request fails.

Example:

function addLoader() {
    var img = $('<img />', { 
      id: 'loader',
      src: '/path/to/your/loader.gif'
    });
    img.appendTo($('body'));
}
function removeLoader() {
    $('#loader').remove();
}

addLoader(); // here the we add our loader
data = new FormData($('#form')[0]);
$.ajax({
    type: 'POST',
    url: 'systems/createpostsystem.php',
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    complete: function() {
        removeLoader(); // here we remove it
    },
    success: function(data) {
        alert(data);
        window.location = "myposts.php";
    }
});
Alessandro
  • 1,443
  • 9
  • 18