Damian
Damian

Reputation: 1720

ajax return value

I'm having a nightmare trying to do this. I must have tried about 15 different methods so far from different posts I've read but all have failed.

I am just trying to get a return value from an ajax post. Here is my code

var test = compareNew(this.name, "remove");
alert(test);

function compareNew(obj, action) {
  $.ajax({
    url: "AJAX_compare_server.php",
    type: 'post',
    data: {
      compare_id:  obj,
      action:   action
    },
      success: function (result) {
      var myObject = eval("(" + result + ")");
      alert(myObject.html);
      return(result);
    }
  });
}

The alert(myObject.html); correctly shows me the html returned but the alert(test); shows me 'undefined'. I've spent hours on this but can't figure it out. Can you see what I'm missing?

Upvotes: 0

Views: 233

Answers (10)

yosafatade
yosafatade

Reputation: 185

You can not get a return value from an asynchronous call, like an AJAX request. The reason is that the code waiting for the response has already executed by the time the response is received. The solution is to run the necessary code inside the success: callback.

function compareNew(obj, action) {
  $.ajax({
    url: "AJAX_compare_server.php",
    type: 'post',
    data: {
      compare_id:  obj,
      action:   action
    },
      success: function (result) {
        // Run the code here that needs
        //    to access the data returned
        return result;
    }
  });
}

or maybe you can call another function inside the success: callback

function compareNew(obj, action) {
      $.ajax({
        url: "AJAX_compare_server.php",
        type: 'post',
        data: {
          compare_id:  obj,
          action:   action
        },
          success: function (result) {
            callFuction(result)
            return result;
        }
      });
    }

and you can also make it synchronous. You need async:false to make it happen.

function compareNew(obj, action) {
var return_this;
$.ajax({
url: "AJAX_compare_server.php",
type: 'post',
async: false,
data: {
  compare_id:  obj,
  action:   action
},
success: function (result) {
            return_this = result;
    }
  });
return return_this;
}

Upvotes: 0

The Alpha
The Alpha

Reputation: 146269

Actually return won't work in an asynchronous call but if you set async:false then it'll work, in this (synchronous call) case you may try this

function compareNew(obj, action) {
    $.ajax({
        url: "AJAX_compare_server.php",
        type: 'post',
        data: {
            compare_id:  obj,
            action:   action
        },
        success: function(result) { 
            returnresult(result); // will call the function and will alert
        }
    });
}

function returnresult(ret){
    // Do whatever you want to do with the result
    if(ret) alert(ret);
}
compareNew(this.name, "remove");

Also you can use it like

function compareNew(obj, action, callBack) {
    $.ajax({
        //...
        success: function(result) { 
            callBack(result);
        }
    });
}

And call it like

compareNew(this.name, "remove", function(data){
    alert(data);
});

Upvotes: 2

mistersender
mistersender

Reputation: 256

if you've got firefox for testing, you can see how the asynchronous call works by converting your alerts to console.log(); and opening up the console. This will show you the text you are dumping, as well as give you a visual representation (along with the data going and coming) for your ajax post. you can see how the test var executes immediately, and btw, if you want test to at least be defined, try having compareNew return "something"; at the bottom, as if the ajax didn't even exist.

var test = compareNew(this.name, "remove");
console.log(test);

function compareNew(obj, action) {
  $.ajax({
    url: "AJAX_compare_server.php",
    type: 'post',
    data: {
      compare_id:  obj,
      action:   action
    },
      success: function (result) {
      var myObject = eval("(" + result + ")");
      console.log(myObject.html);
      //return(result); //this line isn't gonna do anything.
    }
   return "something";
  });
}

`

Upvotes: 0

VijayS91
VijayS91

Reputation: 1531

Functions only will return value. You should use return out side of ajax .....

Upvotes: 1

Michael Norgren
Michael Norgren

Reputation: 770

Set async to false, then set your return value in your success statement. At the end of your method (outside of your ajax request), return the retVal.

function compareNew(obj, action) {
  var retVal;
  $.ajax({
    url: "AJAX_compare_server.php",
    type: 'post',
    data: {
      compare_id:  obj,
      action:   action
    },
    async: false,
    success: function (result) {
      var myObject = eval("(" + result + ")");
      retVal = myOBject.html;
      alert(myObject.html);
    }
  });
  return retVal;
}

Upvotes: 0

Mr T.
Mr T.

Reputation: 4518

Ajax is asynchronous so the alert(test); is preformed before the result from the ajax call is finished. That's why you get undefined.

Upvotes: 0

Udan
Udan

Reputation: 5609

you are using return as a method

Corect is:

return result;

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55750

You cannot have a return value from Ajax..

It is Asynchronous

Upvotes: 0

Mike Park
Mike Park

Reputation: 10941

Two things to note here.

  1. Your ajax call is asynchronous which means that it's entirely possible that it will return after alert(test) runs.
  2. return (result) is not returning from compareNew. It is returning from the success function that you created

Upvotes: 0

Brian Ball
Brian Ball

Reputation: 12606

ajax calls are asynchronous. Once it is initiated, the javascript continues to execute and your function exits. The return statement in your success handler is a return to that anonymous function, NOT a return statement to your compareNew function. undefined is the result I would expect from your script.

What you should probably do is have the success function call another function you have defined, and that function should perform the work on the value returned from your ajax call.

If you want your method to be synchronous, there is an option you can set (probably one of the ones you've tried already). In your success handler, set a variable that is scoped to your function to the value you want to return, then after the ajax method call, return that value. I would recommend against this though as making an ajax call synchronous prevents any other javascript from executing while the call is waiting to be returned, and that usually ends up being a poor user experience.

Upvotes: 0

Related Questions