jquery ajax call sucess and then

ajax, javascript

Solution

The problem in your code is this:

$.ajax Description: Perform an asynchronous HTTP (Ajax) request

so, the code is read by the browser, and then is executed. By the time your `alert(flag)` is executed your `flag` is unassigned. And after the http request is complete the `success` callback is called BUT it is not executing the code after the `$.ajax()` call by second time.

That's why you must place the code you need to be executed inside the `$.ajax()` callbacks or call the functions you need to call inside them

To fix your code, move the `alert()` inside the `success` callback

function checkUserName() {

var flag=false;

$.ajax({
    type : "get",
    url : "/vclub/verify/checkUserName.do",
    data : {lastName: "jason"},
    success : function(data) {
        if (data) {
            alert("flag now true");
            flag=true;
            alert(flag);
        } 
    }
 });

return flag;
}

One important thing is that the code inside `success` may never be executed, it will be executed only is the request returns a 200 status code. Thats why we have the other callbacks: `error`, `complete`, etc.

EDIT: To answer "what is the diff between Then and Success?" let's see the .then description:

deferred.then() Description: Add handlers to be called when the Deferred object is resolved, rejected, or still in progress

so the main difference is that `success` callback is only called when the http request is finished and received an 200 status code, but the `then` function in this context is used to add callback handlers to the `jqXHR` object, example

$.get( "test.php" ).then(
  function() {
    //ajax complete equivalent callback here
  }, function() {
    //ajax error equivalent callback here
  }
);

Problem

So for JQuery Ajax call we can do something like below ``` function checkUserName() { var flag=false; $.ajax({ type : "get", url : "/vclub/verify/checkUserName.do", data : {lastName: "jason"}, success : function(data) { if (data) { alert("flag now true"); flag=true; } } }); alert(flag); return flag; } ``` And flag never becomes true. I searched the forum and been told to use callback functions. Why can I not use success function (which I believe that success function called after success ajax response??) to assign flag variable? What's the difference between "THEN()" and "Success function"? To me both of them seems about the same. What am I missing? Thank you. Again Thank you for sharing your knowledge. But what is the diff between Then and Success?

Original source

Related problems