Here is my code that does not work:
var sessionListJSON = GatherSessionsFromPage();
$.post('ajax.php', {
_ExportMissingAddressesToXLS : 1,
sessions : sessionListJSON // ARRAY
}, function(data) {
});
here is my php
attempt to catch it:
else if (array_key_exists('_ExportMissingAddressesToXLS', $_POST)) { // {{{
$sessions = $_POST['sessions'];
ExportMissingParentAddressesToXLS($sessions);
} // }}}
How do I properly send this array through this jQuery
.post
and then retrieve it in PHP? Also, would this be a case of serialization? If so, how do you do this for JS/jQuery?
jQuery automatically serializes arrays for you in $.post()
. In PHP, $_POST['sessions']
will be an array if sessionListJSON
was an array. You can access it with ordinary array indexing, foreach
, etc.
If sessionListJSON
is really a JSON string, you need to decode it in PHP:
$session = json_decode($_POST['sessions']);
My suggestion when working when any complex data structure being passed between javascript and PHP would be to use JSON serialization/deserialization and not rely on $_POST
behavior at all.
This may look like this in javascript/jQuery.
var json = JSON.stringify({
_ExportMissingAddressesToXLS : 1,
sessions : sessionListJSON // ARRAY
});
$.ajax({
type: 'POST',
url: 'ajax.php',
contentType: 'application/json',
dataType: 'json', // if you expect JSON in return
data: json, // your JSON string here
success: // your success handler
error: // your error handler
});
On the PHP-side, since you are not dealing with form-encoded data, you would need to read PHP's raw input. Luckily this is very simple and converting the POST data into a PHP object/array is very trivial. It is as simple as this:
$json = file_get_contents('php://input');
$variable = json_decode($json);
Note that with default json_decode()
behavior you would actually get an object that you could work with like
if($variable->_ExportMissingAddressesToXLS === 1) {
$sessions = $variable->sessions;
ExportMissingParentAddressesToXLS($sessions);
}