I need help finding an alternative to synchronous jQuery ajax

十年热恋 提交于 2019-12-01 12:51:49

This is a very common 'problem' that can be solved pretty easily by using callbacks appropriately.

$("#submitButton").click(function (event) {
    event.preventDefault(); //Don't submit the form, we'll submit it manually.

    var case_id;

    // Code to check the required fields are entered
    ....

    // Get the case id number from the server
    $.get('ajax/unique-case-id').done(function(data){
        case_id = data;

        // do something with case_id and other things. MUST happen after the ajax call
        ....

        // if there was a problem uploading the images, stop the form from submitting
        if (problem_occured) {
            alert("something went wrong");
        } else {
            $("#referenceToTheForm").submit();
        }

    });
});

Long story short, keeping the "deal with problems or submit the form" inside of the callback to the $.get call will essentially cause the script to 'pause' until it gets the data back. Then you can use something like spin.js to give the user a good waiting experience until it's done.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!