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

Following is a part of an AJAX functionality to add classes and packs to session cart:-
The jquery part
function addClassToCart(itemId)
{
addItemToCart(itemId,true);
}
function addPackToCart(itemId)
{
addItemToCart(itemId,false);
}
function addItemToCart(itemId,isClass)
{
$.post(url+"/ajax/add_cart", { operation: 'add_cart','isClass':isClass, 'itemId': itemId},
function(data)
{
if(data.success)
{
alert("item added to cart");
}
}, "json");
}
The AJAX request processing php part -
//Checking operation and other posted parameters
if($_POST['isClass'])
{
//Code to add class to session cart
}
else
{
//Code to add pack to session cart
}
The strange thing
No matter whether I pass true/false (by calling addClassToCart() and addPackToCart()), always the code to add class to session cart executes.
If I put echo statements there like this:-
if($_POST['isClass'])
{
echo "see if condition ".$_POST['isClass'];
}
else
{
echo "see else condition ".$_POST['isClass'];
}
This is the output:-
addClassToCart() see if condition true
addPackToCart() see if condition false
Putting conditions like this in the jquery code however works fine:-
function addItemToCart(itemId,isClass)
{
if(isClass)
alert("is class");
else
alert("is pack");
}
Finally, if I alter the server side code to this:-
if($_POST['isClass'] === true)
{
echo "see if condition ".$_POST['isClass'];
}
else
{
echo "see else condition ".$_POST['isClass'];
}
These are the outputs -
addClassToCart() see else condition true
addPackToCart() see else condition false
So, why is the boolean variable treated as a string here? Am I doing something wrong in posting parameters?
Thanks,
Sandeepan

Also you can use filter_var function with filter FILTER_VALIDATE_BOOLEAN. According to php documentation it
Returns TRUE for "1", "true", "on" and "yes". Returns FALSE otherwise. If FILTER_NULL_ON_FAILURE is set, FALSE is returned only for "0", "false", "off", "no", and "", and NULL is returned for all non-boolean values.
So receiving of POST parameter will look like:
$isClass = filter_var($_POST['isClass'], FILTER_VALIDATE_BOOLEAN);

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
}

This is a bit of an old question, but I'm surprised nobody has posted this here as solution.
Just use 1 and 0 instead of true and false when you're constructing your ajax requests.
When you do a == comparison, they'll be interpreted as true/false.
JS:
$.ajax({
url: '....',
data: {
foo: 1,
bar: 0
}
});
PHP:
<?php
if ($_GET['foo']) {
//...
} else {
//...
}
echo $_GET['bar'] ? 'bar is true' : 'bar is false';
?>

Send the data from your javascript as stringified JSON.
Make a PHP function to convert the strings 'true' and 'false' to boolean value.
Personally I like #2, which goes with Nick Craver's answer.

Related

Checking boolean variable from JQuery POST in PHP

I am new in PHP.
I have a variable in jquery called editMode set to false. I used $.post() in jquery to pass the variable in a php function. But when I check its value, the value is fine, but if statement does not function the way it's supposed to. Here is my code:
jQuery (just a snippet):
var editMode = false;
$(document).ready(function(){
//some function that handles UI input that triggers editMode=true
$("#form").submit(function(event){
event.preventDefault();
var fName = $("#firstname").val();
var lName = $("#lastname").val();
//... and the rest of post values coming from UI input
$.post('includes/sql/register.php', {
fName: fName,
lName: lName,
//... and the rest of post values coming from UI input
editMode: editMode // this is where I post the value for editMode
},
//jQuery function to handle the result
});
In my register.php:
<?php
if(isset($_POST['submit'])){
$fName = mysqli_escape_string($conn,$_POST['fName']);
$lName = mysqli_escape_string($conn,$_POST['lName']);
//and other post values from UI input
$editMode = $_POST['editMode'];
if($editMode) {
echo $editMode . ": edit"; //fires update query
} else {
echo $editMode . "add"; //fires insert query
}
}
?>
When testing the code, it returns the correct value of $editMode, but does not perform the if statement correctly. What I mean is, if $editMode is true, it echoes: true: edit, which is good. But when it's false, it echoes: false: edit. So it still performs the if clause, even if its value is now false. I also tried if($editMode === true) {//edit} else {//add}, and it does the opposite. Whether $editMode is true or false, it performs the else clause. Please enlighten me.
All POST requests sent will be treated as strings - and if I'm not mistaken, a boolean value of true in JavaScript becomes the string of "true" in PHP (as it is converted to a sting before being sent to PHP).
I would suggest sending the data as an integer representation of the boolean value, that is doing sending the editMode data as editMode ? 1 : 0.
$.post('includes/sql/register.php', {
fName: fName,
lName: lName,
//... and the rest of post values coming from UI input
editMode: editMode ? 1 : 0
},
Which in PHP becomes if ("1") for true and if ("0") for false. Since PHP is a weakly typed language, these will be treated as integers (if (1) and if (0)) which will be true and false expressions respectively.
So in PHP you can do
if ($editMode) {
echo "true: edit"; //fires update query
} else {
echo "false: edit"; //fires insert query
}
You can validate the boolean value before checking in your conditional statement:
$editMode = 'False';
$editMode = filter_var($editMode, FILTER_VALIDATE_BOOLEAN);
if ($editMode) {
echo $editMode . ": edit"; //fires update query
} else {
echo $editMode . "add"; //fires insert query
}
if you want to keep your code as it is just send the false in string
instead of
var editMode = false;
use
var editMode = "false";
and in your php file
if($editMode == "true") {

Ajax returns with PHP

Alright so I am trying to put this thing together, but I do not understand what is the problem with this code. I am basically trying to return false in case name exists in the database, but no matter what ajax will just pass it as a "success"
Here is the code:
Running the
function checkName(username) {
$.ajax({
url:"assembly/handler.php",
type:"POST",
data:{func:"run_namecheck", user_name:username},
success:function(data){
return true;
},
error:function(data) {
return false;
}
});
}
The code is executed perfectly and it actually passed all the things it needs, and the PHP function does get called.
PHP function bellow.
public function nameExists($name) {
$handler = new sql();
$sql = $handler->connect();
$sql->real_escape_string($name);
$name_final = ucfirst($name);
$result = $sql->query("SELECT ime FROM users WHERE ime='".$name_final."'");
if($result->num_rows != 0) return true;
else {
$handler->log_write($name, "login_fail","NULL");
return false;
}
$sql->close();
return false;
}
Now the problem is success and the error. No matter what it will always be success. It doesn't like pay attention at when I return FALSE from the PHP at all and such.
AJAX calls are literally just an HTTP request, like any other HTTP request. You're not directly "executing" PHP code when you make an ajax call, you're doing an HTTP request to the server, which (eventually) executes a PHP script on your behalf.
That means any return from the PHP code are completely invisible to Javascript.
Only OUTPUT from PHP will ever be seen by Javascript, which means you need to echo that data, not return it.
And note that any HTTP response from PHP is also literally plain text. Any output you perform in PHP will be converted to text, which means that boolean false you're trying return will be converted to the string equivalent of a boolean false - an invisible zero-length string.
"error" condition in your js code is only for bed requests, like 500, 404 etc.
return a json { error: true } or something like with and use it in your js
success:function(data){
if(data.error) {
// do...
}
},
As far as I can see your code, you're returning nothing to client. You shall return some data that represents the boolean value about the user existence. For instance:
// PHP server-side
if( nameExists( $name)) echo "T";
else echo "F";
that will return value can then be captured by the data parameter in your AJAX function for success and be tested about the server answer.
// Javascript in client
success:function(data){
if( data === "T") return true;
else return false;
},
Hope I can help!
instead of return from php you need:
echo "True" or "false"
to on javascript side:
function checkName(username) {
$.ajax({
url:"assembly/handler.php",
type:"POST",
data:{func:"run_namecheck", user_name:username},
success:function(data){
if(data=='true'){
alert("success process");
}else{
alert("fail process");
};
},
error:function(data) {
console.log("error Ajax");
}
});
}
The data transferred between the client and the server is always text. You need to make sure that the client and server know how the client should deserialize the text. So you might return one of four things:
HTML (if it's going to populate page elements)
JSON (if you want a lightweight, fast way to send data to the client)
XML (if you want a heavier-weight, fast way to send data to the client)
Plain text (for whatever you want, really)
What the client does will depend on what Content-Type header you use in your PHP page.
so, use a header in PHP, for eg:
header('Content-Type', 'application/json');
...and the return this text from it:
{"success": true}
or
{"success": false}
I hope it will help.

Return true to jquery from php file

I was looking at this question: Return true/false to javascript from php file
But is not what I'm looking for, as I don't need to return text/strings in JSON.
What I want is to return true or false statements from loaded php file to jQuery.
jQuery: (How I think it could work)
if($("#lvlupann").load("/templ/checknlvl.php") == true){
$("#lvlupann").addClass("nlvlann");
}
And the mighty php file : (checknlvl.php)
if(1 == 1){
return true;
}
But obviously it doesn't return true/false, and class is not added... I know I'm going probably wrong on it, but don't know what to overwrite...
Any help would be appreciated.
You are doing it wrong.
The .load() method is asynchronous and does not return the value from the server (it returns the element that it was called on: $("#lvlupann")), so using the returned value in an if statement does not make sense.
You have to wait for the request to finish before you can use the value, like so:
$("#lvlupann").load("/templ/checknlvl.php", function (value) {
if (value == true) {
$("#lvlupann").addClass("nlvlann");
}
});
As for the PHP file, the return true; will just stop the script. It does not send anything to the client. In order to send two or more things from PHP to the client you need to package the output in some fashion.
The $.get method would be useful:
$.get('/templ/checknlvl.php').done(function (data) {
$("#lvlupann").html(data.content);
if (data.success) {
$("#lvlupann").addClass("nlvlann");
}
});
<?php
echo json_encode([
'content' => '<strong>Some content...</strong>',
'success' => true,
]);
die;
If all you want to do is get a boolean value from the PHP script then something like this would do it:
$.get('/templ/checknlvl.php').done(function (value) {
if (value === "true") {
$("#lvlupann").addClass("nlvlann");
}
});
<?php
if (1 == 1) {
echo 'true';
} else {
echo 'false';
}
die;

How do I pass the correct data type to Javascript from PHP

I am using the jQuery post method to create a record in MySQL. When I evaluate the output of the PHP with ==, all three conditionals work properly. However, when I use ===, the first two conditionals return false. How do I pass the correct data type to Javascript from PHP?
jQuery:
$("#form").validate({
submitHandler: function(form) {
// do other stuff for a valid form
$.post('inc/process_form.php', $("#form").serialize(), function(data) {
//alert(data);
if (data == 1) {
$('#results').html("Success");
} else if (data == 2) {
$('#results').html("No Success");
} else {
$('#results').html(data);
}
});
}
});
This is the PHP (which I've truncated to only show the execute conditional):
$value = $stmt->execute();
if ($value === TRUE) {
echo 1; //success
} else {
echo 2; //failure
}
try this:
if(parseInt(data) === 1){
The problem is the return variable data is a string, you can't do anything (as far as I know) from PHP to return it as a integer.
As the comment by Marc Costello suggested, this makes the === useless since you are forcing both sides to be integer, so data == 1 is better in this case.
I never needed something like this but if you really have to you can simply cast it using +data:
data = +data;
if (data === 1) {
$('#results').html("Success");
} else if (data === 2) {
$('#results').html("No Success");
}
In this case you can pass boolean value instead of 0 or 1 i.e true or false from php

Java Script is not working inside the php

public function actionAjaxUpdate()
{
$action = $_GET['act'];
if(!isset($_POST['selectedId']))
{
echo '<script> alert("No row is selected"); </script>';
}
else
{
$selectedAll = $_POST['selectedId'];
if(count($selectedAll)>0)
{
foreach($selectedAll as $selectedId)
{
$model=$this->loadCompositeModel($selectedId);
switch ($action) {
case 'Delete':
$model['account']->delete();
break;
case 'Active':
$model['account']->active = '1';
break;
case 'Inactive':
$model['account']->active = '0';
break;
default:
break;
}
$model['account']->save();
}
}
}
}
List item
In this code Alert is not working, if no id is selected.So some one help me out. i have tried alot but js is not working.
I have used js inside the php and this is the first time when js is not working inside the php
Without seeing the code that makes the HTTP request, it is hard to say what the problem is.
Them most likely explanation that selectedId is set to an empty string when no id has been selected. The condition !isset($_POST['selectedId']) will then not give you the result you want. Use empty() instead (and make sure that 0 is not an acceptable id value).
Unless you're injecting the response back into the page, the Javascript will never be evaluated.
If you were to do...
document.write('<script src="/path/to/phpscript.php">')
then the response will be appended to the page and evaluated.
However, if you do...
$.ajax({
success: function(response) {
//Blah....
}
});
or something to that effect, the response is never evaluated, it's passed to your success function as a string. So you could just get the PHP to print 1 or 0 for success/failure - or even better return a Json object
<?php
...
if(!isset($_POST['selectedId']))
{
$Ret->Success = false;
$Ret->Reason = "No row is selected";
header("Content-Type: application/json");
print json_encode($Ret)
}
?>
Then use the $.getJson Ajax call to retrieve the response as a Js object (See this manual page)
It seems $_POST['selectedId'] is an array. then you should use isset for elements of $_POST['selectedId'] for example if (!isset($_POST['selectedId'][0]))
EDIT 1: try this one
$array_id = array_filter($_POST['selectedId']);
then use if (!empty($array_id)) instead of if (!isset($_POST['selectedId']))

Categories