Reputation: 63
Boolean value sent over Ajax (from client) becomes string on the server side:
var ban_status = null;
ban_status = true;
$.ajax({
type: 'POST',
url: app.baseUrl + "/admin/users/api-ban-user",
data: { "userId": user_id, "banStatus": ban_status },
datatype: "json",
success: function (response) {
if (response.status === true) {
addAlert(response.msg, 'success');
userList();
} else {
addAlert(response.msg, 'error');
}
}
});
In php
$banStatus = $post['banStatus'];
gettype($post['banStatus'])
returns string. How to return the boolean value.
Upvotes: 1
Views: 2440
Reputation: 39260
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;
Upvotes: 1
Reputation: 351
The point is you wanted to send a JSON, but giving the object in "data" does not do what you want. It sends data as form elements (see network inspector)
So you have to use:
data: JSON.stringify({ "userId": user_id, "banStatus": ban_status })
to send a real json-string and decode this server side via
json_decode(file_get_contents("php://input"))
In addition: datatype: "json" is only the format option of the incoming response data to the javascript, not the type of data to be send to the server.
Best, Tim
Upvotes: 0
Reputation: 374
Use 1 instead of true, and 0 instead of false in your ajax call. Or compare with strings in server side. HTTP is a text protocol everything must be stringified. (int, boolean etc.)
Upvotes: 0
Reputation: 347
use php typecating
$banStatus = (boolean)$post['banStatus'];
gettype($post['banStatus'])
Upvotes: 0