1

Very good to all, it turns out that I have a problem with jquery ajax. I need you to bring me a return value but the result I get is undefined.

I have read that it is because ajax is not asynchronous, but what catches my attention is that in console it shows me the result correctly.

function saveImageAjax(imagen){

        var tmp;

        $.ajax({
        url: "saveimg.php",
        type: "post",       
        data: {'image': imagen},
        success: function (data) {
                if(data!=undefined){
                tmp = data;
                console.log(tmp);

                }

            }

                    });

            return tmp; 

 }

    var response=saveImageAjax('example.com/image.png');

I've been researching and what I've found on the net is for years... When placing in ajax call async: false; The result of all is correct, but I have read that this form is not correct because it would be detrimental in the user experience. How could I solve this? To see if anyone can explain to me what is happening.

Thanks !!

PlayerWet
  • 419
  • 5
  • 18

1 Answers1

2

you need to use a callback:-

function saveImageAjax(imagen, callback) {

  $.ajax({
    url: "saveimg.php",
    type: "post",
    data: {
      'image': imagen
    },
    success: function(data) {
      if (data != undefined) {
        console.log(data);
        callback(data);
      }
    }
  });

}

saveImageAjax('example.com/image.png', function(data) {
  console.log(data);
});

Then your response variable would be data in the callback function.

BenG
  • 14,826
  • 5
  • 45
  • 60
  • Thank you very much, how could I get the result of the function? I need to store it in a var. – PlayerWet Nov 28 '16 at 19:03
  • 1
    look in the link provided at the top for a more in detail answer. – BenG Nov 28 '16 at 19:07
  • I'm sorry but still reading that answer still continues to give me undefined result. I can not get out the value of the function and save it in a variable, at least I do not know how to achieve it. – PlayerWet Nov 28 '16 at 21:17
  • Thanks BenG !! function callback is the key. – PlayerWet Nov 29 '16 at 02:19