skip to Main Content

How can i repeat an Ajax request as long it return 1; if it return 0 it should break

while(1){
    $.ajax({
    type: "POST",
    url: '/admin/importsql/',
    data: $datas,
    dataType: "json",
    success: function($data) {

    }})
}

2

Answers


  1. You could specify that the AJAX call should be executed synchronously instead of asynchronously. This would afford you the opportunity to set a variable to indicate whether to continue.

    To achieve this, simply add the async parameter to your AJAX call:

    async: false
    

    In your original code this would be something like:

    var continue = true;
    
    while(continue) {
        $.ajax({
        type: "POST",
        url: '/admin/importsql/',
        data: $datas,
        dataType: "json",
        async: false,
        success: function($data) {
            // check the result here
            if (result == 0)
                continue = false;
        }})
    

    I should caution though that it would be sensible to catch AJAX failures and errors too, otherwise this could loop indefinitely.

    Edit following comment by @Nicolas

    It’s important to understand that changing the AJAX call to synchronous will cause the thread to block until the call completes.

    This means that any other JS code in the same thread cannot execute whilst the thread is blocked. This may cause an unacceptable impact on your JS applicationwebsite.

    Login or Signup to reply.
  2. You can’t simply do that because ajax is an asynchronous process ( unless specify otherwise, but then what’s the point of using Ajax). You are simply starting noumerous ajax call without waiting for one to finish. What i suggest is to use recursion and promises to send your call one after the other. :

    function sendAjax($data) {
     return $.ajax({
                type: "POST",
                url: '/admin/importsql/',
                data: $datas,
                dataType: "json"})
            .done((result) => {
                 return result == 1 ? sendAjax($data) : Promise.resolve(result);
            }).toPromise();
    
    }
    

    This method chain promises until one of them recieve 0 as a result. Then you can use it as such :

    sendAjax({some: 'data'}).then((result) => {
        // all promises has resolve and the last one was 0
    })
    

    P.S. Please note that this code is untested.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search