Reputation: 153
I am trying to get some data sent to a PHP page to update PHP Session variables. I have tried several different examples that I found here but just can't seem to get any to work. The data is never received on the PHP page.
Here is my Javascript/jQuery:
var str, ProductID, sessionValues= [];
ProductID = "1";
str = {"ProductID": ProductID, "State": "UNCHECKED"};
sessionValues.push(str);
ProductID = "2";
str = {"ProductID": ProductID, "State": "CHECKED"};
sessionValues.push(str);
var postObj = {"sessionData": sessionValues};
console.log(postObj);
$.ajax({
type: 'POST',
contentType : 'application/json',
data: {'data': JSON.stringify(postObj)},
url: 'setSession.php'
}).done(function(response){
console.log(response);
}).fail(function(jqXHR, textStatus, errorThrown){
alert('FAILED! ERROR: ' + errorThrown);
});
This is what my data object looks like:
Then on the PHP side all I get is an error that I supplied an invalid argument to foreach. No matter how many times I repeat the sessionValues.push(str)
my browser always reports 528 bytes sent.
<?php
$data = json_decode($_POST['data']);
print_r($data);
foreach ($data->sessionData as $key => $value) {
echo "$key => $value";
}
?>
Upvotes: 0
Views: 2996
Reputation: 508
Since some browsers caches the ajax requests, it doesn't responds as expected. So explicitly disabling the cache for the particular ajax request helped to make it work. Try to modify charlietfl's request as below:
$.ajax({
type: 'POST',
data: {'data': postValue},
cache: false,
url: 'postAjaxHandling.php'
}).done(function(response){
});
Upvotes: 0
Reputation: 171679
You need to remove contentType : 'application/json',
because that is not what you are sending.
When you do send as application/json
properly ... stringifying the whole object , not just parts of it, then $_POST
will be empty and you have to access the data using json_decode(file_get_contents('php://input'))
There is also no need to stringify your other object...jQuery will form encode it for you and you can access it as array
Try
JS
$.ajax({
type: 'POST',
data: {'data': postObj},
url: 'setSession.php'
}).done(function(response){
PHP
<?php
$data = $_POST['data'];
foreach ($data['sessionData'] as $key => $value) {
echo "$key => $value";
}
?>
Upvotes: 1