2

i have i javascript function does not wait ajax execution quit immediately with no wating execution what is the problem seriously my code below:

i made an alert at the end: precisely to stop it. when the alert show i wait a little bit the result from the server and the return is result not null from the server. when i disable the alert the result is undefined.

function getAllBathyms() {

    var idbar = $("#list_barrages").val();
    var idorg = $("#list_organisations").val();

    if (idbar == "" || idbar == "--" || idbar == "NaN") {
        alert("veuillez séléctionner un barrage SVP:");
    }
    if (idorg == "" || idorg == "--" || idorg == "NaN") {
        alert("veuillez séléctionner un barrage une agence SVP:");

    }

    $.ajax({
        type: 'POST',
        url: '@Url.Content("~/CourbesNiveaux/getAllBathyms")',
        data: { 'idbar': idbar, 'idorg': idorg },
        success: function (data) {
            alert('ok ajax');
            console.log('ok ajax');
            bathyms = data;
        },
        error: function () {
            alert('server problems');
        }
    });
    return bathyms;
}
Vova Lando
  • 558
  • 3
  • 15
ezzaam
  • 61
  • 1
  • 1
  • 7
  • *"i have i javascript function does not wait ajax execution"* That's normal, because Ajax stands for *"**Asynchronous** JavaScript And XML"*. They included the term *asynchronous* for a reason. – Felix Kling Feb 20 '14 at 09:50

3 Answers3

1

Add async:false in ajax

 $.ajax({
        type: 'POST',
        async:false, 
        url: '@Url.Content("~/CourbesNiveaux/getAllBathyms")',
Sarath
  • 608
  • 4
  • 12
0

because ajax is asynchronous. it will not wait for the success event to happen. If you want to do so, put

async:false

in your code

Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
0

Option 1: You can always set your AJAX call to be synchronius, but be ready that the whole page stucks while waiting for response. just add parameter async: false to your set of parameters. note that is a really really big no-no and bad practice!

Option 2: Provide callbacks or put your future code inside success handler

Option 3: You can use defer/promise described here http://blog.mediumequalsmessage.com/promise-deferred-objects-in-javascript-pt1-theory-and-semantics

Vova Lando
  • 558
  • 3
  • 15