Checking boolean variable from JQuery POST in PHP - 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") {

Related

How to focus on a form field only if my data variable is not empty

I have been using php and ajax to validate if an email inserted in my form exists in my database.
I am using jquery to send the email value to my php file and return a message if the email is found. My code is working fine but I want if an email is found the cursor be on focus on the #usu_email field until the email be changed. After this, it should allow me to continue to next field.
This is the jquery code I am using:
function getemail(value) {
var usumail = $("#usu_email").val();
$.ajax({
type: "POST",
url: "ajax_email.php",
data: "usu_email=" + usumail,
success: function(data, textStatus) {
if (data !== null) {
$("#eresult").html(data);
$("#usu_email").focus();
}
},
});
};
My problem is that if and email does not exist in my database the cursor keeps doing focus on my #usu_email field and does not allow me to continue to next field.
I will appreciate any help about this problem because I know very little about jquery.
First... Your condition if (data !== null) always will be true since there always will be a data provided... Be it an empty string.
The only case where there will be no data is on Ajax error... And the condition won't even be evaluated because the success callback won't execute.
Next, I assume that your Ajax request is triggered on $("#usu_email") blur... Else, I don't know how you achieve «does not allow me to continue».
Modify it in this way to compare a response:
function getemail(value) {
var usumail = $("#usu_email").val();
$.ajax({
type: "POST",
url: "ajax_email.php",
data: "usu_email=" + usumail,
datatype: "json",
success: function(data) { // There is only one argument here.
// Display the result message
$("#eresult").html(data.message);
if (data.email_exist == "yes") {
$("#usu_email").focus();
}
if (data.email_exist == "no") {
// Something else to do in this case, like focussing the next field.
}
},
});
};
On the PHP side, you have to provide the json response. It would look like something like this:
<?php
// You have this variable to compare against the database
$email = $_POST[usu_email];
// You say it is working.
// ...
// Then, you certainly have a result... Say it's $found (true/false).
// Build an array of all the response param you want to send as a response.
if($found){
$result[email_exist] = "yes";
$result[message] = "The submitted email already exist.";
}else{
$result[email_exist] = "no";
$result[message] = "A success message about the email here.";
}
// Add this header to the returned document to make it a valid json that doesn't need to be parsed by the client-side.
header("Content-type:application/json");
// Encode the array as a json and print it. That's what is sent in data as an Ajax response.
echo json_encode($result);
?>
Be carefull not to echo anything else. Not even a blank space or a line return.
Depends on what type of data you're expecting (simple text response or JSON), but at first i would start to replace your if(data !== null) with if(typeof data != "undefined" && data !== null && data != "") because the returned response might just be empty and not NULL.
If it doesn't work you should consider adding your php code to the question so we can figure out exactly what it returns when no matching email is found.

Get multiple data from an Ajax response

When process.php responds to an Ajax request made by form.html it replies with "false" or "true [hash value]" (where hash value is the output of a hashing function). In form.html I want to call a different function for the two possible responses but how do I parse the response? For example must I call
var responses = xmlhttp.responseText.split(" ")
Assuming the hashing function never outputs "false" I could use
if(xmlhttp.responseText != "false")
Both these ways seem kind of hacky and inefficent, is there a better way?
You could do the following in your PHP Code:
$returnValue['ValueA'] = "a value";
$returnValue['ValueB'] = "another value";
echo json_encode($returnValue);
in your JavaScript Code (JQuery is used here):
$.ajax({
type: "GET",
dataType: "json",
url: "./myphpfile.php",
data: "parameter=parametervalue",
success: function(data){
printresult(data);
}
});
function printresult(data)
{
alert(data['ValueA']);
alert(data['ValueB']);
}
Is this helping you?
I've had a similar situation, here is my solution using basic Javascript.
First on the PHP side, I can have one of four outcomes (PASS or FAIL on an INSert or UPDate), so my response to AJAX carries those outcomes upfront:
[...]
$echoStr = 'PASS/INS/Adding ID Succeeded.'; // INSert successful
[...]
$echoStr = 'FAIL/INS/Adding ID Failed'; // INSert failed
[...]
$echoStr = 'PASS/UPD/Updating D Succeeded.'; // UPDate successful
[...]
$echoStr = 'FAIL/UPD/Updating ID Failed'; // UPDate failed
[...]
echo $echoStr; return; // Reply to AJAX request.
On the Javascript side (ajax1 is my AJAX obj), I split the response string into three components and process accordingly:
[...]
ajax1.onreadystatechange = function() {
if (ajax1.readyState == 4 && ajax1.status == 200) {
response = ajax1.responseText; // PASS or FAIL, INS or UPD, free form text alert
passFail = response.substr(0,4); // PASS or FAIL
insUPD = response.substr(5,3); // INS or UPD
usrMsg = response.substr(9); // Free form alert text
if (passFail == 'PASS' && insUPD == 'INS') {
// do what you need to do here
}
alert(usrMsg);
} // if (ajax1.readyState == 4 && ajax1.status == 200) {
} // ajax1.onreadystatechange = function() {
[...]

Blank response from jQuery Ajax call to PHP script

I hope this isn't a duplicate; the other similar questions I read didn't help me solve my problem.
I'm receiving a blank response (i.e. data = "") from a jQuery Ajax call to my PHP script, used to validate a user's submitted CAPTCHA value. I'm using Cryptographp for my CAPTCHA, and it works as expected, so I'm thinking it's most likely an error either in my Ajax call or the PHP script.
Firebug showing correct POST values ('code' is the submitted CAPTCHA value to test):
code a
email a#a.com
emailtext a
firstname a
lastname a
phone
Ajax function called onsubmit to determine whether or not to submit the form:
function validateCaptcha()
{
// Assume an invalid CAPTCHA
var valid = false;
// The form containing the CAPTCHA value
var data_string = $('form#emailform').serialize();
// Make the Ajax call
$.ajax({
url: "captcha.php",
data: data_string,
type: "POST",
async: false,
success: function (data) {
if (data == "true")
{
valid = true;
}
alert ("data: " + data);
}
});
return valid;
}
captcha.php
<?
$cryptinstall="crypt/cryptographp.fct.php";
include $cryptinstall;
// Begin the session
session_start();
//Check if CAPTCHA values match
if(chk_crypt($_POST["code"]))
return true;
else
return false;
?>
My expectation is that the above snippet should return a response of simply "true" or "false," but perhaps this is not the case.
Any help pointing out my error would be greatly appreciated!
You need to use "echo" instead of "return" and write is as a string. return is for returning results of functions.
<?
$cryptinstall="crypt/cryptographp.fct.php";
include $cryptinstall;
// Begin the session
session_start();
//Check if CAPTCHA values match
if(chk_crypt($_POST["code"]))
echo "true";
else
echo "false;
?>
From your captcha.php you are not echoing/printing anything so it's returning nothing. Just replace your return true; and return false; with echo.
Browser can only receive something when you'll print something from the script.
if(chk_crypt($_POST["code"])) echo true; // 1
else echo false;// 0
or
if(chk_crypt($_POST["code"])) echo 'true'; // true
else echo 'false';// false

How does Ajax work with PHP?

I'm having troubles using ajax and php. What I'm trying to do is call an ajax function that grabs a value from an form's input, and checks if that email exists in a database. Here is my current javascript:
//Checks for Existing Email
function checkExisting_email() {
$.ajax({
type: 'POST',
url: 'checkExist.php',
data: input
});
emailExists = checkExisting_email();
//If it exists
if (emailExists) {
alert("This email already exists!");
}
Unfortunately, I can't get my alert to go off. In my PHP function, it checks whether the input is a username or an email (just for my purposes, and so you know), and then it looks for it in either column. If it finds it, it returns true, and if not, it returns false:
include ('func_lib.php');
connect();
check($_POST['input']);
function check($args)
{
$checkemail = "/^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";
if (!preg_match($checkemail, $args)) {
//logic for username argument
$sql = "SELECT * FROM `users` WHERE `username`='" . $args . "'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) > 0) {
return true;
} else {
return false;
}
} else {
//logic for email argument
$sql = "SELECT * FROM `users` WHERE `email`='" . $args . "'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) > 0) {
return true;
} else {
return false;
}
}
}
SO my issue is, how does ajax respond to these returns, and how do I make ajax function accordingly? Mainly, why doesn't this work?
Any help is very much appreciated. Thank you!
You need to add the success option to your Ajax request, which is the JS function which gets executed when the XHR succeeds. Have a look at the jQuery documentation for more info.
Without running the script, I think you'll find that $_POST['input'] is empty; you need to pass your data as something like data: {'input': input} to do that.
Your PHP also needs to return some content to the script; consider changing your call to check() to something like this:
echo (check($_POST) ? 'true' : 'false');
You can now check the content in JavaScript.
Basically ajax is a hand-shaking routine with your server.
Ajax:
$.post('yoursite.com/pagewithfunction.php',
{postkey1:postvalue1, postkey2:postvalue2...},
function (response) {
// response is the data echo'd by your server
}, 'json'
);
pagewithfunction:
yourFunction(){
$var1 = $_POST['postkey1'];....
$result = dosomething($var1..);
echo json_encode($result); // this is passed into your function(response) of ajax call
}
So in $.post you have the url of the php page with the function, { var:val } is the post data, and function(response) is where you handle the data that is echo'd from your server -- the variable, response, is the content that is echo'd.

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

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.

Categories