Boolean Variables Posted Through Ajax Being Treated as Strings in Server Side

boolean variables posted through AJAX being treated as strings in server side

You aren't doing anything wrong per se, it's just that when it gets posted, it looks like this:

operation=add_cart&isClass=true&itemId=1234

PHP can't tell what the data type is because it isn't passed, it's always just a string of POST data, so compare it to "true" to do your checks, like this:

if($_POST['isClass'] === "true")
{
//Code to add class to session cart
}
else
{
//Code to add pack to session cart
}

Send a boolean value in jQuery ajax data

A post is just text, and text will evaluate as true in php. A quick fix would be to send a zero instead of false. You could also put quotes around your true in PHP.

if ($_POST['undo_vote'] == "true") {
Photo::undo_vote($_POST['photo_id']);
} else {
Photo::vote($_POST['photo_id'], $_POST['vote']);
}

Then you can pass in true/false text. If that's what you prefer.

When sending boolean values through Ajax call, PHP gets the value as a string

As mentioned; you can use json_decode in php but since the post data is a string you can send one parameter called json and stringify your object in JavaScript:

var ban_status = null;
ban_status = true;

$.ajax({
type: 'POST',
url: app.baseUrl + "/admin/users/api-ban-user",
data: {json:JSON.stringify({ "userId": user_id, "banStatus": ban_status })},
datatype: "json"
}).then(
function (response) {
if (response.status === true) {
addAlert(response.msg, 'success');
userList();
} else {
addAlert(response.msg, 'error');
}
}
).fail(//use .catch if you have a new enough jQuery
function(err){
console.warn("something went wrong:",err);
}
);

In PHP:

$postedObject = json_decode($post['json']);
$banStatus = $postedObject->banStatus;

Bool parameter from jQuery Ajax received as literal string false/true in PHP

In my experience if you have

dataType: 'json'

and

contentType: 'application/json'

in your jQuery ajax call, and JSON.stringify your data before you send it will arrive at the server as a parse-able javascript object. Or in my case I'm using NodeJS serverside and it arrives as a Javascript object, with correct booleans, not string bools. But if I leave out the content type attribute then things get all goofed up including the bools.

Cannot obtain correct Boolean value when sent in ajax

As you are not sending a JSON data via POST (that could be handle correctly with the json_decode) your string "true" or "false" will always be the boolean true, because PHP will assume that, as a non empty string, your var should be converted to the true boolean value.

So, you should use string comparison instead in your case.

In example:

$value = (bool)"test"; // whatever value, not empty string
var_dump($value);

is the boolean true

$value = (bool)"";
var_dump($value);

is the boolean false

Is it possible to search for a boolean in mongo with an ajax post without server side conversion?

The problem here is how you are sending the data and how you are treating it on the receiving end. What you really want to do is post the "body" of the request as JSON and then make sure your server implementation is parsing that JSON body in a way where you have that data available. The default as you are doing is "form encoded".

Your ajax request should look like this:

jQuery.ajax({
url : "/dev/search/searchMongo",
type : "POST",
data : JSON.stringify({
active : false
}),
success : function(html) {
alert(html)
}
})

Then your application end on the server "parses" the body which allows the JSON to come out as an object. Very simple for JavaScript.

On the other end the "body parser" part of your otherwise normal "RESTful" service should translate the JSON "String" to an actual object. This should be the case for other languages other than JavaScript for your server but you might need to look at the parser implementation.

Ajax passing boolean along with HTML from server to client with HTML data type

Just use JSON to respond:

<?php
if ($result->num_rows > 0) {
$html = '<p>There are some user already </p>';
$result = false;
} else{
$html = '<p>List is empty </p>';
$result = true;
}
$response = ["html"=>$html, "result"=>$result];
header("Content-Type: application/json");
echo json_encode($response);

Then, in your JS:

ajaxcall.done(function(data) {
var result = data.result;
$('#call-result').html(data.html);
});

jQuery will automatically parse a response of type json into a JavaScript object so you can access the elements directly.

Ajax call : sent boolean interpreted as string in php

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.



Related Topics



Leave a reply



Submit