Reputation: 137
What I want to do is send an JavaScript Array to a PHP file.
This is what I got:
var mydata = [];
console.log(document.getElementsByTagName("input")[0].name);
for (var i = 0; i < document.getElementsByTagName('input').length; i++) {
mydata[document.getElementsByTagName("input")[i].name] = document.getElementsByTagName("input")[i].value;
};
for (var i = 0; i < document.getElementsByTagName('select').length; i++) {
mydata[document.getElementsByTagName("select")[i].name] = document.getElementsByTagName("select")[i].value;
};
console.log(mydata);
$.ajax({
method: "POST",
url: "q.php",
data: {'lol': JSON.stringify(mydata)},
contentType: 'application/json',
dataType: 'json'
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
$('#debug').html(msg);
});
So as you can see, I create an array with a loop, at that moment all is fine. The problem is when I try to sent it through POST with JSON. I don't know if this is the best method...
I tried without JSON.stringify();
but the $_POST
still empty
It seems like the post isn't sent, but I can see in the console the XHR post request has been sent.
Upvotes: 4
Views: 280
Reputation: 149
Try to use this code and see the changes.
remove the
contentType: 'application/json',
dataType: 'json'
And change var mydata = []
into var mydata = {}
your ajax should look like this
$.ajax({ method: "POST", url: "q.php", data: {'lol': mydata} }) .done(function( msg ) { alert( "Data Saved: " + msg ); $('#debug').html(msg); });
You dont have to stringify your mydata because you already decleared it as object.
Hope it helps
Upvotes: 3