PlayerWet PlayerWet - 7 days ago 5
Ajax Question

Function result undefined in ajax response

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 !!

Answer

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.

Comments