Reputation: 4223
I've noticed that a variable sent in an AJAX call (jQuery) as a type:boolean was interpreted as a type:string on the server side (PHP). Here is an extract of my code, to illustrate that:
Ajax call:
$.ajax({
url : 'model/script.php',
type : 'POST',
data : ref,
success : function (data){
...
}
});
If I test the ref
variable type in my JS script:
var ref_type = jQuery.type(ref);
alert(ref_type);
// Result : boolean
If I test the $_POST['ref']
type in my PHP script:
if(isset($_POST['ref'])){
echo gettype($_POST['ref']);
}
// Result : string
Is there a way to send / recept a boolean variable? Or do I have to cast the variable in the PHP script? I might have missed something...
Upvotes: 0
Views: 88
Reputation: 146410
A regular post request body (technically speaking, a x-www-form-urlencoded
message) is nothing but text. Even numbers are text. Everything is text, because in the end this is what the browser sends and the server receives:
Name=John%20Smith&Age=35&Subscribed=true
Just pick a convention for true/false and make an explicit conversion in your server-side code:
switch ($_POST['ref']) {
case 'yeah':
$ref = true;
break;
case 'nope':
$ref = false;
break;
default:
$ref = null;
}
If you pick a value set that PHP will recognise correctly when casting from string to boolean the code can get simpler:
$ref = (bool)$_POST['ref'];
Or you can just let PHP do all the hard work:
$ref = filter_input(INPUT_POST, 'ref', FILTER_VALIDATE_BOOLEAN);
Alternatively, you can use plain text to transmit a serialised complex data structure that supports complex data types and has encoder/decoder both in client and server platforms. A typical choice is JSON.
Upvotes: 1
Reputation: 339
You need to cast the variable in your PHP code because the data is converted into (one) string and gets sent as it.
Upvotes: 0