I've been trying to decode a Javascript array in PHP for several days now with no luck.
I basically have a PHP while loop that loops through all products in my SQL database and it spits out a checkbox on each row to allow users to select 1 or more product to action via a PHP script.
My HTML & form is:
<div class="error_box"><?php echo $_SESSION['newdata']; ?></div>
<div class="error_box"><?php echo $_SESSION['errordata']; ?></div>
<form>
<input type='submit' value='Bulk update products -->' id='bulk-change-products' onClick='updateProduct()'>
<input type='checkbox' name='products[]' id='serialized' value='$product_no' onclick='serialize()'>
</form>
My Javascript code:
window.serialize = function serialize() {
var values = [].filter.call(document.getElementsByName('products[]'), function(c) {
return c.checked;
}).map(function(c) {
return c.value;
});
console.log(values);
$('#result').html(values);
}
function updateProduct(values){
$.ajax({
url: "https://tech-seo.co.uk/ecommerce/products/bulk_process_products.php",
method: "POST",
data: {array:values},
success: function(res){
}
})
}
Console log shows the data correctly e.g.
(2) ["1", "2"]
0: "1"
1: "2"
length: 2
My php code after posting with AJAX:
session_start();
$getArray = json_decode($_POST['data']);
// checking if data exists
if ($getArray != null ){
$_SESSION['newdata'] = "Success!";
}else{
// either of the values doesn't exist
$_SESSION['errordata'] = ">>>>>> There was an error <<<<<<<";
}
I always get '>>>>>> There was an error <<<<<<<' when I select the products and click the submit button.
Any help is appreciated.
Thanks. Stan.
data: {array:values}your array is in thearraykey notdatakey, eg you would use$_POST['array']onClick='updateProduct()'You're not passing thevaluesargument to the function.json_decode()in PHP, but you never callJSON.stringify()in JavaScript. Where are you expecting the JSON to come from?