Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronous wait for $.ajax call

I need a hyperlink to execute an Ajax call, and when that has completed, do the standard action for the hyperlink.

<a href="afterwards.html" target="_blank" onclick="return CallFirst();">Link</a>

The javascript function calls $.ajax(), waits for success or failure, then returns true.

function CallFirst()
{
    $deferred = $.ajax({
                    type: "POST",
                    url: url,
                    data: data
                });

    // **todo** WAIT until the Ajax call has responded.

    // Return true, which makes the <a> tag do it's standard action
    return true;
}

The code must wait for $.ajax to succeed, then return true from CallFirst().

$deferred.when() terminates immediately. How can it be made to wait?


2 Answers

Just set async property to false

$deferred = $.ajax({
                type: "POST",
                url: url,
                data: data,
                async: false
            });

But it is really a better idea to use callbacks.

like image 63
Igor Dymov Avatar answered Feb 03 '26 02:02

Igor Dymov


You could set async to false but better practice to use callback:

.done(function( success) {
    if (success) {
      doSomeThingElseNow();
    }
  });
like image 33
Pete Thorne Avatar answered Feb 03 '26 01:02

Pete Thorne