SamuraiJack
SamuraiJack

Reputation: 5539

Is there an alternative to async:false in Jquery?

I am getting Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. I have looked into this post but couldnt find anything to suit my need.

alternative to async: false ajax

$(docucment).ready(function(){

var obj=AppendFileList(10); 
 $.each(obj.Table, function (key, value) {
             //some code to do some task                                           
   });

});




function AppendFileList(lotid) {

                $.ajax({
                    type: "POST",
                    url: "XYZ/GetAttachements",
                    data: JSON.stringify({ LotId: lotid, GUID: $('#hidnuniqueid').val() }), // LotId: arr1[1],
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: false,
                    success: function (data, status) {
                        var obj = jQuery.parseJSON(data.d);
                        console.log(obj);
                        return obj;

                    },
                    failure: function (data) {
                        console.log(data);

                    },
                    error: function (data) {
                        console.log(data);
                        console.log(data.Message);
                    }
                });

            }

I do not want to keep ajax() method outside within a separate function as i have shown in my example so that I dont have to write ajax call again and again. Is this possible?

Upvotes: 0

Views: 3296

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337580

All the logic which relies on the result of the AJAX request should go in the success callback. To achieve this, you can pass an anonymous function to your AppendFileList() function. Try this:

$(document).ready(function(){
    AppendFileList(10, function(data) { // data = the JSON retrieved
        $.each(obj.Table, function (key, value) {
            // some code to do some task                                           
        });
    }); 
});

function AppendFileList(lotid, callbackFn) {
    $.ajax({
        type: "POST",
        url: "XYZ/GetAttachements",
        data: { 
            LotId: lotid, 
            GUID: $('#hidnuniqueid').val() 
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data, status) {
            callbackFn(data); // use your callback here, passing it the retrieved data
        },
        error: function (data) {
            console.log(data);
            console.log(data.Message);
        }
    });
}

Note that you don't need to use JSON.stringify to send the data or deserialise the response as jQuery will automatically do this for you and that the $.ajax() method has no failure property in its settings.

Upvotes: 1

Related Questions