Reputation: 129
I am trying to pass an array from my .js file to a php file. The array looks like the following in js:
theBlock[0 - 79] with the values color, x and y. So for example
theBlock[10].color or
theBlock[79].x
This data is passed with the following script:
$.ajax({
type: 'POST',
url: 'insert.php',
data: $(theBlock).serialize()
}).done(function (data) {
console.log(data);
}).fail(function () {
alert("Failed");
});
And the php is following:
$newData = $_POST;
echo count($newData["theBlock"]) . "\n";
Now when calling the function which activates this, the data should be passed to php which then sends me back the length of the array. Well, it always sends me back "0".
The array is created by the following script:
var theBlock = [];
for (c = 0; c < 80; c++) {
theBlock.push({color: 0});
}
After that the array is changed in the following way:
if (ctx.getImageData(xPixel + minX, yPixel + minY, 1, 1).data[3] == 255 && ctx.getImageData(xPixel + minX, yPixel + minY, 1, 1).data[0] == 000) {
id = (xBlock + (yBlock - 1) * 8) - 1;
theBlock[id] = { color: 1, x: xBlock, y: yBlock };
}
Thanks
Upvotes: 0
Views: 180
Reputation: 4680
Well, you can't use serialize() on a javascript variable. Refer to the API documentation. http://api.jquery.com/serialize/
If you want to encode a JSON array, use JSON.stringify()
and then json_decode() it.
$.ajax({
type: 'POST',
url: 'insert.php',
data: { block: JSON.stringify(theBlock) }
}).done(function (data) {
console.log(data);
}).fail(function () {
alert("Failed");
});
And you don't need to assign $_POST to a variable, just use it directly.
echo count(json_decode($_POST['block'])) . "\n";
Sidenote: If you simply want to know the array length, you don't need PHP to do that. Just do theBlock.length
and you get the length.
Upvotes: 2