0

I'm making a lot of $.ajax calls, and I'm trying to create a function, so I don't have to keep typing out the full $.ajax format.

I'd like to create a function similar to this:

function php(task, data=false) {
    if(!data) { data = ""; } else { data = "&"+data; }
    $.ajax({ url: 'actions.php',
        data: '&task='+task+data,
        type: 'post',
        success: function(output) { return output; },
        error: function(xhr, e){ alert(e); }
    });
}

The goal is to return the output, so I can use it somewhere else. For Example:

function doSomething() {
    var test = php("test");
    alert(test);
}

On the actions.php page, there is a task called "test", that's sole purpose is to echo out: "TESTING 123".

If I use $.ajax in "doSomething()" (changing the success potion to simply alert(output) - then I would see an alert box with the words "TESTING 123" (working as intended)

However, when I attempt to create the "php(task, data)" function, and return the output to a variable, my alert box says "UNDEFINED".

MEE
  • 75
  • 8
  • 3
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – CertainPerformance Mar 24 '19 at 00:19
  • I think that is actually what I was looking for, but it didn't show up (probably because of the way I worded my title). I will need to read through it, thanks for the info! – MEE Mar 24 '19 at 00:21
  • Check this link https://stackoverflow.com/questions/5316697/jquery-return-data-after-ajax-call-success – Rohit Mittal Mar 24 '19 at 17:39

0 Answers0