简体   繁体   中英

JavaScript jquery.ajax in success after loop nothing working

I need to pass some values to other function in Javascript. I have got the values from another PHP file but I can not pass it to any other Javascript Function. Nothing is working in SUCCESS after FOR LOOP. Need Help?

url1 = 'http://localhost:81/Dashboard/admin/inc/dashboard.php';
$.ajax({
    url: url1,
    type: "POST",
    dataType: "json",
    success: function(data)
    {
        for(var i = 0; i <= 11; i++) 
        {
            Month = data[i].Month;
            Sales = data[i].Sales;
            if (i == 0) global_ij = "[" + Month + "," + Sales + "]";
            else global_ij = global_ij + "," + "[" + Month + "," + Sales + "]";
        }
        alert ("hello"); // this alert is also not working
    }
});

That's because you are performing an asynchronous AJAX operation. In other words, the assignments on variables Month , Sale , global_ij that you are making are only available in that particular success function's scope and NOT outside of it.

One workaround for you is to add async: false to your AJAX call which will force it out of asynchronous behavior, therefore allowing you to make the values assigned to those variables available to all the remaining block of code:

$.ajax({
url: url1,
async: false,
type: "POST",
dataType: "json",
success: function(data)
{
    for(var i = 0; i <= 11; i++) 
    {
        Month = data[i].Month;
        Sales = data[i].Sales;
        if (i == 0) global_ij = "[" + Month + "," + Sales + "]";
        else global_ij = global_ij + "," + "[" + Month + "," + Sales + "]";
    }
}
});

jQuery's AJAX calls return promise objects which enforce methods such as .done() , .fail() , etc.

On the other hand, you could also get a promise from the AJAX call (which you can pass around anywhere in your Javascript code) and when the promise gets resolved invoke it's .done() handler.

var promise = $.ajax({/* settings */});

/* --- */

// promise passed to some other block of code

promise.done(function(){
    //execute the block of code after the promise was resolved
});

Read more about this here .

looks like your php is returning 8 elements and in your success method your loop iterates over 11 items, causing error.

I separated the success function and tried it with the data you posted and replaced the 11 in the loop with data.length. take a look at the following codepen:

http://codepen.io/anon/pen/OyXzGb?editors=011

note that I added

var Month;

var Sales;

to keep those temporary variables inside the scope of the function.

You might need to check Data to see if it is a proper array, to catch errors. before this line:

for(var i = 0; i < data.length ; i++)

final output and something to try out:

var global_ij="";
function processData(data) {
    var Month;
    var Sales;
    for(var i = 0; i < data.length; i++) 
    {
        Month = data[i].Month;
        Sales = data[i].Sales;
        if (i == 0) global_ij = "[" + Month + "," + Sales + "]";
        else global_ij = global_ij + "," + "[" + Month + "," + Sales + "]";
        console.log(global_ij);
    }
    return global_ij;
}

try out this function without the ajax first:

processData([{"Month":"1","Year":"2015","Sales":"19746.81"},
{"Month":"2","Year":"2015","Sales":"17902.26"},{"Month":"3","Year":"2015","Sales":"19223.84"},{"Month":"4","Year":"2015","Sales":"18840.88"},{"Month":"5","Year":"2015","Sales":"19889.97"},{"Month":"6","Year":"2015","Sales":"18509.85"},{"Month":"7","Year":"2015","Sales":"1886.81"},{"Month":"8","Year":"2015","Sales":"1740.34"}]);

you might want to use .done()

Modify your code to declare the gloabla_ij variable outside the loop. somehting like below..

var global_ij='0';
url1 = 'http://localhost:81/Dashboard/admin/inc/dashboard.php';
$.ajax({
    url: url1,
    type: "POST",
    dataType: "json",
    success: function(data)
    {
        for(var i = 0; i <= 11; i++) 
        {
            Month = data[i].Month;
            Sales = data[i].Sales;
            if (i == 0) global_ij = "[" + Month + "," + Sales + "]";
            else global_ij = global_ij + "," + "[" + Month + "," + Sales + "]";
        }
    }
});

If you declare the var at the top of the file, it can be used by any function within the file:

var global_ij; // declare variable in global scope of module/file

$.ajax({
    url: 'http://localhost:81/Dashboard/admin/inc/dashboard.php',
    type: "POST",
    dataType: "json",
    success: function(data) {

        var i, month, sales, len = data.length;

        for(i=0; i<=len; i++) {

            month = data[i].Month;
            sales = data[i].Sales;

            if (i===0) global_ij = "[" + month + "," + sales + "]";
            else global_ij = global_ij + "," + "[" + month + "," + sales + "]";
        }

        doSomething(); // can now call function after loop finished
    }
});

func doSomething() {
    // global_ij is now populated
}

The response from the PHP file is:

[
    {"Month":"1","Year":"2015","Sales":"19746.81"},  // 1
    {"Month":"2","Year":"2015","Sale‌​s":"17902.26"},  // 2
    {"Month":"3","Year":"2015","Sales":"19223.84"},  // 3
    {"Month":"4","Year"‌​:"2015","Sales":"18840.88"},  // 4
    {"Month":"5","Year":"2015","Sales":"19889.97"},  // 5
    {"Mont‌​h":"6","Year":"2015","Sales":"18509.85"},  // 6
    {"Month":"7","Year":"2015","Sales":"1886‌​.81"},   // 7
    {"Month":"8","Year":"2015","Sales":"1740.34"}    // 8
]

Yet you are looping

for(var i = 0; i <= 11; i++) 

So when i >= 8 , data[i].Month will throw an "data[i] is undefined" error.

Simply use the .length property instead:

for(var i = 0; i < data.length; i++) 

Example Fiddle

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