JavaUser
JavaUser

Reputation: 26354

jquery - First get request as synchronous and subsequent to be asynchronous

I have a usecase where I want my first get request to the server should happen immediately(synchronous way). Based on this respose, I will show some message . Then I need to poll the same request asynchronously(ajax). I have the solution for asynchronousm part . But the first operation , how can I achive this in jquery. Both are same request. Suggest if any other way to achieve this.

(function poll() {
            setTimeout(function() {
                $.ajax({
                    url: "server script path",
                    type: "GET",
                    success: function(data) {
                        console.log("polling"+data);
                        if(data.is_running === false){
                            console.log("stop polling");
                            $("#overlay").show();
                        }
                    },
                    dataType: "json",
                    complete: poll,
                    timeout: 2000
                })
            }, 50000);
        })();

Thanks,

Upvotes: 1

Views: 66

Answers (2)

mylee
mylee

Reputation: 1333

(function poll(synchronous) {
    setTimeout(function() {
        $.ajax({
            url: "server script path",
            type: "GET",
            success: function(data) {
                console.log("polling"+data);
                if(data.is_running === false){
                    console.log("stop polling");
                    $("#overlay").show();
                }
            },
            dataType: "json",
            complete: poll,
            timeout: 2000,
            async: !synchronous
        })
    }, 50000);
})(true);

Upvotes: 1

stackErr
stackErr

Reputation: 4170

All you need to do is set the async property to false in your first request:

$.ajax({
    url: "your url here",
    type: "GET",
    success: onSuccess,
    dataType: "json",
    async: false,
    complete: poll //this will start your polling
    //Everything else
});

You can read the documentation here about $.ajax and its properties. Setting async to false will make it a synchronous request.

Also if you want to poll the server, you should be using setInterval instead of setTimeout as Eric Guan mentioned in the comments.

EDIT: On second thought, I see that you call poll when the ajax request is completed. This might be better than setInterval depending on your use case.

Upvotes: 0

Related Questions