0

I created an AJAX function that takes two arguments, sends them to a script in PHP and formats them as I wish, like this :

function createUniqueKey (arg1, arg2) {
  $.post("/ajax/documents.php", {arg_1: arg1, arg_2 : arg2}, function(data){
    console.log(data) //Good result
    return data
  }, "text");
}

When the user clicks a button, it starts the ajax request, the problem is that I can not assign it to a variable, I tested that but without success

$('#btn').click(function() {
  ...
  var uniqueKey = createUniqueKey(arg1, arg2)
  console.log(uniqueKey) //undefined
  ...
});

The console.log present in the function gives me a result but the console.log of the variable returns me undefined

How to sign the result to the variable (uniqueKey)?

Rocstar
  • 1,427
  • 3
  • 23
  • 41

1 Answers1

0

Because this is asynchronous, you have a few options. The basic one is to use a callback:

function createUniqueKey (arg1, arg2, callback) {
  $.post("/ajax/documents.php", {arg_1: arg1, arg_2 : arg2}, function(data){
    console.log(data) //Good result
    callback(data);
  }, "text");
}

$('#btn').click(function() {
  createUniqueKey(arg1, arg2, function(uniqueKey){
      console.log(uniqueKey);
  })      
});

Another option is to figure out how to implement it as a Promise or using Async functions:

function createUniqueKey (arg1, arg2) {
    return new Promise(function(resolve, reject) {
        $.post("/ajax/documents.php", {arg_1: arg1, arg_2 : arg2}, function(data){
            console.log(data) //Good result
            resolve(data);
          }, "text");
    })

}

$('#btn').click(function() {
  createUniqueKey(arg1, arg2).then(function(uniqueKey) {
    console.log(uniqueKey);
  })
});

The .click callback is equivalent to this

$('#btn').click(async function() {
  var uniqueKey = await createUniqueKey(arg1, arg2);
  console.log(uniqueKey);
});
TKoL
  • 13,158
  • 3
  • 39
  • 73
  • Wow I did not think it was so complicated, but there is a lot of other things that happen when you click the button, I have to use ``asynchronous`` ? – Rocstar Jan 15 '19 at 15:38
  • 1
    It's not complicated when you figure out how Promises work and why they're needed. You'd benefit from looking up a Promise tutorial – TKoL Jan 15 '19 at 15:39
  • Thank you but I do not understand where to put ``var = uniqueKey`` – Rocstar Jan 15 '19 at 15:44
  • I tried to use your code but it does not work, when I use callback like this ``var uniqueKey = createUniqueKey(arg1, arg2, function(uniqueKey){ return uniqueKey; }) `` my variable is ``undefined`` – Rocstar Jan 16 '19 at 08:57
  • Because that's not what you do. I didn't put that in my code for a reason: that is incorrect.You have access to the uniqueKey variable *inside the callback*. That's the only place you have access to it. You have to research how Asynchronous javascript works to understand what's going on here. – TKoL Jan 16 '19 at 09:06