0

The aim is to get the value from the Ajax success and use it in another function;

I have attached the code below:

Code:

 let neededvalue;
$(function(callback){

 $.ajax({
 type:'GET',
 url: 'getfile.php',

 data:{
   'file':file,

   },
 success: function(data){
 neededvalue = data.split(",");    // 24,23,100,106

 console.log(neededvalue[0])      //23
 console.log(neededvalue[1])      //24
 console.log(neededvalue[2])      //100
 console.log(neededvalue[3])      //106

 $('#img01').selectAreas({
   onChanged: debugQtyAreas,
   maxAreas:1,
   areas: [
              {
                x: neededvalue[0],
                y: neededvalue[1],
                width: neededvalue[2],
                height: neededvalue[3],
              }
            ],

     parent: $('#myModal'),

 });
     callback(neededvalue);

 }

})
})

In the above code, when I checked the values of neededvalue that i received from ajax Get, it prints the correct values in the log. I added those values to the side of the variables in the code above. The problem that I face is when I try to use the values of neededvalue[0],neededvalue[1],neededvalue[2],neededvalue[3] and use them inside the function selectareas. I could not place the values from 'neededvalue' to variables x, y , width and height.

I tried to run the code with direct values to variables inside selectareas i.e., x=23, y=24, width =100 and height=106 and I was able to make the box over the image.

But I dont know why I can not use the values of "neededvalue" and assign it to the variables of selectareas x,y,width and height.

Can someone help me to fix this issue and help me assign the values from ajax success function to SelectAreas function

Joskaa
  • 151
  • 1
  • 2
  • 9
  • This is a very popular question that comes from a misunderstanding of asynchronous programming. Please see the duplicate question to understand why you cannot just return or assign a variable inside an async callback in this way. – elclanrs Nov 30 '20 at 02:17
  • @elclanrs please dont close this question, I tries with the Callback but still I dont get the result, Can you please help – Joskaa Nov 30 '20 at 02:32

1 Answers1

0

I hope code below help for you.

 $.ajax({
 type:'GET',
 url: 'getfile.php',

 data:{
   'file':file,

   },
 success: function(data){
   var neededvalue = data.split(",");    // 24,23,100,106

//you run check value exists
$.each(neededvalue, function(i,v){
    console.log(v);
})

//you create array object
var newobj = {};
    newobj.x = neededvalue[0];
    newobj.y = neededvalue[1];
    newobj.width= neededvalue[2];
    newobj.height = neededvalue[3];

var newarr = [];
   newarr.push(newobj);
 $('#img01').selectAreas({
   onChanged: debugQtyAreas,
   maxAreas:1,
   areas: newarr,
   parent: $('#myModal'),

 });
 }
})
Apple Yellow
  • 307
  • 1
  • 2
  • 7