Correctly POSTing boolean values in jQuery
When I’m building Javascript/jQuery based webapps, my go-to method of performing AJAX requests is via jQuery .post() using JSON.
My code normally looks something like this…
var postUrl = '/someurl.php';
var postData = {'id': 123, 'data': 'xyz', 'bool': true}; // etc
var jqXhr = $.post(postUrl, postData, function(data){
// Do something with the result here...
}, 'json');
This generally works fine and is quick and easy, however you run into trouble with boolean values… they end up getting posted as the strings ‘true’ and ‘false’. Of course you can hack around this in the back-end but it’s far from ideal.
Below is a better way I have devised that behaves properly when it comes to data types other than strings…
var postUrl = '/someurl.php';
var postData = {'id': 123, 'data': 'xyz', 'bool': true}; // etc
var jqXhr = $.ajax({
type: "POST",
url: postUrl,
data: JSON.stringify(postData),
contentType: "application/json; charset=utf-8",
success: function(data){
// Do something with the result here...
},
dataType: 'json'
});
So go back to using .ajax() rather than the short hand .post(), and use JSON.stringify() for the stuff you want to send back.
In the back end you have to add an extra step to retrieve your data. In php you must decode the result of file_get_contents(‘php://input’). Because I was altering existing code I put the resulting array into the variable $_POST at the top of my script as seen below…
$_POST = json_decode(file_get_contents('php://input'), true);