0

I don't Know is below a valid question? or Just my stupidity.

 function IsSlaExists(department) {
     var flag = "";
     $.ajax({
         type: "POST",
         data: "Type=ISSLAEXISTS&Department=" + encodeURI(escape(department)),
         url: "class-accessor.php",
         success: function (data) {
             //flag=data;  
             flag = "YES";
         }
     });
     return flag;
 }

 alert(IsSlaExists('department'));

i'm trying to return the value of flag but function returns blanks even if i set the value of flag maually. what i'm doing wrong?

Mr_Green
  • 40,727
  • 45
  • 159
  • 271
  • Are you sure that the ajax requests did work right? What will happen, if you add a function for failed request? – Reporter May 08 '13 at 13:06
  • Ajax requests are (almost) always asynchronous, so your `return` statement is happening before the POST request has time to complete. – Graham May 08 '13 at 13:06
  • Why didn't you try to alert flag inside of callback function? – Shijin TR May 08 '13 at 13:09
  • @shin it's working in callback function – Muhammad Haseeb Khan May 08 '13 at 13:17
  • What's happening is that the `success` callback is being called when, and only when, the ajax request has finished (and succeeded). You need to understand that you are making an asynchronous request, therefore your `success` callback is being called **after** `return flag;`. – Manuel Pedrera May 08 '13 at 14:06

1 Answers1

0
$.ajax({
       type: "POST",
       data: "Type=ISSLAEXISTS&Department=" + encodeURI(escape(department)),
       url: "class-accessor.php"
}).done(function(r){
      alert("flag");
});

This would give you the alert WHEN the AJAX request was successfull. r would contain the data that the response got you. You can now, for example, call another function inside the done function that process the request.

Since $.ajax returns a promise, you could return just the ajax call and then chain the functions together

function ajaxCall(department) {
    return  $.ajax({
           type: "POST",
           data: "Type=ISSLAEXISTS&Department=" + encodeURI(escape(department)),
           url: "class-accessor.php"
    });
}

ajaxCall("myDept").done(function(response){
   alert(response);
})
DrColossos
  • 12,656
  • 3
  • 46
  • 67
  • please understand my prroblem; i want a function which i could use to return a value. in alternative your solution i can simply use the `ajax success`. i want some way by which i could just return value like `var val= ajaxCall('Dep');` – Muhammad Haseeb Khan May 08 '13 at 13:45