Home > OS >  AJAX .done() returns before actual response is successful
AJAX .done() returns before actual response is successful

Time:04-14

I have the following code that waits for an AJAX request to be completed/successful and then it will redirect to a different url.

Here's what my AJAX request looks like

 function UploadFile(contoller, File, RecordID, AuxID) {
    console.log("initialize uploading file: "   RecordID);
    const formData = new FormData();
    formData.append('RecordID', RecordID);
    formData.append('AuxID', AuxID);
    formData.append('File', File);

    return $.ajax({
        type: "POST",
        url: contoller,
        processData: false,
        contentType: false,
        cache: false,
        enctype: 'multipart/form-data',
        data: formData,
        dataType: 'json'
    })
}

I have another function that calls the AJAX request and redirects to a different url if the response is successful (ie: file has been uploaded to server successfully)

    UploadFile(controller,
               file,
               ID
              ).done(
                    // redirects to different url
              ).fail(
                    console.log("file failed to upload")
              );


            

However, I notice that .done() is always executed before the file has finished uploading to the server.

If I use the following code with "success" then it works well. The callback function after the success parameter is only called after the uploading process has been completed.

 $.ajax({
                    type: "POST",
                    url: controller,
                    processData: false,
                    contentType: false,
                    cache: false,
                    enctype: 'multipart/form-data',
                    data: formData,
                    success: () => {
                           // redirects to url
                        })
                    },
                    error: function (ret) {
                       
                    },
                    dataType: 'json'
                });

I read in other posts/documentation that the new jquery replaces "success" with ".done()" so they are basically the same thing, right? However, I'm not sure why .done() doesn't work for my code.

CodePudding user response:

Both the done and fail need callback functions passed to them.

$.ajax returns a jqXHR object. This object contains the done and fail methods. From this documentation we have:

deferred.done( doneCallbacks [, doneCallbacks ] )

where:

doneCallbacks Type: Function() A function, or array of functions, that are called when the Deferred is resolved.

So an example would look like this:

$.get( "test.php" ).done(function() {
   alert( "$.get succeeded" );
 });
  • Related