1

I try to get an ajax-result via function into a variable. But var output is always undefined. What am I doing wrong? I guess the problem is, that the ajax request takes some time, while the output is done immediately

var data = { 'something': 'anything' };
var output = ajaxed(data);
console.log(output);

function ajaxed(data) {
    $.ajax({
        url: "/script.php",
        type: "POST",
        data: data,
        dataType: "json"
    })
    .done(function( json ) {
        return json.response;
    });
}
user3142695
  • 15,844
  • 47
  • 176
  • 332
  • Very good question and I looked up this answer which uses deferred objects which might work in this case: http://stackoverflow.com/a/14754681/2048391 – jyrkim Feb 22 '15 at 09:57
  • your guess is correct. The "fix" is to ensure that all of your processing on the `json.response` variable is done from code that's invoked from within that `.done` callback. In fact your code should read `return $.ajax(...).then(function(json) { return json.response })` at which point the result of `ajaxed(data)` will not be the data itself, but a _promise_ to return the correct data some time later. You can then attach additional `.then` handlers to that promise. – Alnitak Feb 22 '15 at 10:14

1 Answers1

-1

If you are sending data vía POST, just try to define each variable with an individual name like this:

var output = ajaxed(myData);

$.post( '/script.php', { dataToBeProcessed: myData }, function(data) { 
    return data[0].response;
}, "json");
benjamingranados
  • 438
  • 5
  • 15