I'm trying to get some data from javascript to php. It's a table where the number of rows is variable. So, I'm trying to get all the data with a loop in javascript then sending them to php. There, I will use another loop to save each row with another loop. So, there is the code:
JAVASCRIPT
//---- this is the important section ---- //
var data = new FormData();
var table = [];
for (var i = 1; i <= document.getElementById('nblines').value; i++) {
var date = document.getElementById('date' + i).innerHTML;
if (document.getElementById('l' + i).checked == true) { var type = 1;} else { var type = 2;}
var paiement = document.getElementById('a' + i).innerHTML;
var tps = document.getElementById('b' + i).innerHTML;
var tvq = document.getElementById('c' + i).innerHTML;
var total = document.getElementById('d' + i).innerHTML;
var interet = document.getElementById('e' + i).innerHTML;
var principal = document.getElementById('f' + i).innerHTML;
var balance = document.getElementById('g' + i).innerHTML;
var line = [i,date,type,type,paiement,tps,tvq,total,interet,principal,total];
table.push(line);
};
console.log(table);
data.append('amortTable', table);
------------------------------------------------
| |
| ---- this is the NOT important section ---- |
| |
------------------------------------------------
var token = document.getElementById("csrf_token").content;
var request = new XMLHttpRequest();
request.onreadystatechange = function notify()
{
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
setTimeout(loadPage(page),500);
$.niftyNoty({
type: 'success',
container : 'floating',
html : 'Votre calcul s\'est enregistré avec succès!',
timer : 5000
});
} else {
}
} else {
// still not ready
}
}
request.open( "POST", "savecalcul", true);
request.setRequestHeader("X-CSRF-TOKEN", token);
request.send(data);
PHP
foreach ($request->input('amortTable') as $i) {
$line = new Amortissement;
$line -> calcul() -> associate($calcul->id);
$line -> number = $i[0];
$line -> date = $i[1];
$line -> type = $i[2];
$line -> paiement = $i[3];
$line -> tps = $i[4];
$line -> tvq = $i[5];
$line -> total = $i[6];
$line -> interet = $i[7];
$line -> principal = $i[8];
$line -> total = $i[9];
$line -> save();
}
I am getting this error local.ERROR: exception 'ErrorException' with message 'Invalid argument supplied for foreach()' in ... the line is :
foreach ($request->input('amortTable') as $i) {
So, am I on the right way and if yes, what am I doing wrong. If I am not on the right way, what should I do?