Reputation: 708
What I am trying to do is:
First Ajax is uploading csv file and gets all the products list. Then on success it goes through loop and calls another ajax which uploads these products.
Problem:
When it goes through loop it freezes browser and waits till every product will be uploaded and then it prints out the ID's.
What I need:
To get rid of freezing browser and when it could print every ID after every product has been uploaded.
Code:
var data = new FormData();
data.append('file', jQuery('#item_data')[0].files[0]);
data.append('action', 'csv_upload');
jQuery.ajax({
url: ajaxurl,
data: data,
timeout: 3000,
cache: false,
contentType: false,
processData: false,
type: 'POST',
dataType: 'json',
success: function (data) {
jQuery( ".wrap .all" ).html(data.information.length);
jQuery.each(data.information, function (i, elem) {
add_item(elem, i);
});
jQuery( "#results" ).append( "<p style='color:green;'>The end!</p>" );
}
});
function add_item(elem, i){
var data = new FormData();
data.append('action', 'product_upload');
data.append('file_cont', JSON.stringify(elem));
jQuery.ajax({
async: false,
url: ajaxurl,
data: data,
type: 'POST',
processData: false,
contentType: false,
dataType: 'json',
success: function (response) {
jQuery( "#results" ).append( "<span>"+ data.message +"</span>" );
}
});
jQuery( ".wrap .count" ).html(i+1);
}
Upvotes: 0
Views: 44
Reputation: 1481
var data = new FormData();
data.append('file', jQuery('#item_data')[0].files[0]);
data.append('action', 'csv_upload');
jQuery.ajax({
url: ajaxurl,
data: data,
timeout: 3000,
cache: false,
contentType: false,
processData: false,
type: 'POST',
dataType: 'json',
success: function(data) {
jQuery(".wrap .all").html(data.information.length);
add_item(data.information, data.information[0], 0);
}
});
function add_item(info, elem, i ) {
var
data = new FormData();
data.append('action', 'product_upload');
data.append('file_cont', JSON.stringify(elem));
jQuery.ajax({
url: ajaxurl,
data: data,
type: 'POST',
processData: false,
contentType: false,
dataType: 'json',
success: function(response) {
if (info.length >= i + 1) {
jQuery("#results").append("<span>" + data.message + "</span>");
add_item(info, info[i + 1], i + 1);
jQuery(".wrap .count").html(i + 1);
}
}
});
if(info.length == i){
jQuery( "#results" ).append( "<p style='color:green;'>The End!</p>" );
}
}
you can do it recursively, since setting async: false
will wait for the request to finish before the next instruction is executed.
UPDATE: removed async: false
, and added with "The End" message correction.
Upvotes: 2