I have a jquery script that collects data from different sites and saves it through ajax and php to a sql database. At the moment the script saves each collection from a site separately. I want to change that, so that the script collects all the data in an array and when it is finished collecting it passes the array on to the php file which will save it in the database.
My problem now is, that I can't send the array after the "each loop" to the ajax statement. If I send the array inside the "each loop" it works (at the moment I save the data in a session on the php file, so that I can see it's structure and can adapt the pdo statement accordingly), but then I have a post request after each "loop". I want to avoid that, so that I have just one POST request with the whole array at the end. But if I use the ajax post request after the "each loop", the array I get is just empty. I thought I made the array global, so that I can use it outside the each statement, but for some reason it doesn't work.
Do you have any idea how to solve the problem? Here is the script:
$('#ScanButton, .ScanButton').click(function() {
var array = ["http://www.xyz.com/bla/bla/summary.html",
"http://www.xyz.com/blu/blu/summary.html",
];
dataArray = [];
$.each(array, function(n, val) {
$.get(val, function(res) { //get the html source of this website
var data = {
}
dataArray.push(data);
// If I use the $.ajax statement here, it works and a correct array is submitted. But then I have a a POST request with each loop.. });
});
//If I use the $.ajax here, the array I get is just empty. Any Idea how to solve this?
data = YAHOO.lang.JSON.stringify(dataArray);
$.ajax({
type: 'post',
cache: false,
url: 'test.php',
data: {myJson: data}
});
return false;
});
Do you have any idea where the problem might be? If you need more information, please let me know. Thank you very much! :)