Bool Parameter from Jquery Ajax Received as Literal String "False"/"True" in PHP

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.

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;

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
}

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

Condition if return true with ajax and php even it is false

The transmission of boolean and check on it serverside can lead to unexpected due to low typing.

What happens if you init your variable this way ?

$check1= $_POST["checkbox1"] == 'true' ? true : false;

Is there a way to get true/false string values from a Boolean in PHP?

PHP displays boolean values as 1 (true) or empty string (false) when outputted.

If you want to check if it's true or false use == (if implicit conversion is OK) or === (if it's not). For example:

echo $val ? 'true' : 'false'; // implicit conversion
echo $val === true ? 'true' : 'false'; // no conversion

I don't know of any way to make PHP output boolean values natively as true or false.

Check if a variable is a string in JavaScript

You can use typeof operator:

var booleanValue = true; 
var numericalValue = 354;
var stringValue = "This is a String";
var stringObject = new String( "This is a String Object" );
alert(typeof booleanValue) // displays "boolean"
alert(typeof numericalValue) // displays "number"
alert(typeof stringValue) // displays "string"
alert(typeof stringObject) // displays "object"

Example from this webpage. (Example was slightly modified though).

This won't work as expected in the case of strings created with new String(), but this is seldom used and recommended against[1][2]. See the other answers for how to handle these, if you so desire.


  1. The Google JavaScript Style Guide says to never use primitive object wrappers.
  2. Douglas Crockford recommended that primitive object wrappers be deprecated.

Send JSON data via POST (ajax) and receive json response from Controller (MVC)

Create a model

public class Person
{
public string Name { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
}

Controllers Like Below

    public ActionResult PersonTest()
{
return View();
}

[HttpPost]
public ActionResult PersonSubmit(Vh.Web.Models.Person person)
{
System.Threading.Thread.Sleep(2000); /*simulating slow connection*/

/*Do something with object person*/

return Json(new {msg="Successfully added "+person.Name });
}

Javascript

<script type="text/javascript">
function send() {
var person = {
name: $("#id-name").val(),
address:$("#id-address").val(),
phone:$("#id-phone").val()
}

$('#target').html('sending..');

$.ajax({
url: '/test/PersonSubmit',
type: 'post',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
$('#target').html(data.msg);
},
data: JSON.stringify(person)
});
}
</script>


Related Topics



Leave a reply



Submit