简体   繁体   中英

How to use the value from ajax function outside the success block

I am very new to Ajax and under major deadline.

I have an ajax function

$.ajax({
    type: "POST",
    url: 'CritAdd.php?',
    data: { currfilterfields : currfilterfields },
    async: false,
    success: function(msg) {
        var javminmaxarray = $.parseJSON(msg);
        alert(msg);
        alert(javminmaxarray);
    }
});

This works perfectly fine and the data gets stored in global variable array "javminmaxarray". Alerts put for testing also show expected values.

However when I use this global array in my function where it needs to be accessed as below, the value shows as empty/undefined.

function closemodal() {
    alert(javminmaxarray[0]);
}

I made asynch option of ajax as false but that didn't work either. Please suggest how to use the value from ajax function outside the success block.

change this..

var javminmaxarray = $.parseJSON(msg);

to

javminmaxarray = $.parseJSON(msg);

declare you javminmaxarray variable outside the $.ajax function .

var javminmaxarray = {};

// .... 

$.ajax({
   //...
   success: function(msg) {
      javminmaxarray = $.parseJSON(msg);
   }
});

and then use your function how ever you want

function closemodal(){
    alert(javminmaxarray[0]);}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM