Cant make comparison with php echo output in javascript (jquery-post) - javascript

I enter password in password field, and send it from javascript to php, and compare it with the '123' key variable in php. So if it is true it echo outs true, otherwise false.
Then, in my javascript file at callback function field, the data can not be used in if statement. I dont know why.
However, when I just want to write data it writes true in my html file, but i cant make comparison with this 'true'
My javascript:
$.post('validation.php', { input: pass }, function(data) {
if ( data === "true")
{
// even if it is true, It skips here, goes else
}
else
{
}
});
My php file is:
<?php
$key = '123';
if (isset($_POST['input'])) {
$pass = $_POST['input'];
if ($pass === $key)
{
echo 'true';
}
else
{
echo 'false';
}
}
?>

you might need to trim the returned value when comparing it in your javascript:
...if(data.trim() === "true")...
or
var option = data.trim();
if(data.trim() === option)...

use the function localeCompare. for example:
data.localeCompare("true")

Related

Comparing php value with javascript variable?

I am working on php and javascript project. I just want to compare echo return value of php with javascript variable.
php backend code which returns 'no' using echo
if($connection){
$sql ="SELECT secondname FROM account WHERE email = '$email' && password = '$password'";
$searchquery = mysqli_query($connection, $sql);
if(!(mysqli_num_rows($searchquery) == 0)) {
$row = mysqli_fetch_array($searchquery);
$secondname = $row['secondname'];
echo $secondname ;
} else {
echo 'no';
}
Now comparing with javascript variable
$.post("signnin.php",{
email: email,
password: password,
},
function(data, status){
if(data == 'no'){
console.log('same');
}else{
console.log('not same');
}
});
it give same result if value are same or not. i also JSON.stringify but it still not working
The output from the URL probably includes white space.
JSON is a good way to normalize that, but you need to apply it at the PHP end, not the JavaScript end.
$secondname = $row['secondname'];
header("Content-Type: application/json");
echo json_encode([ "secondname" => $secondname ]);
} else {
header("Content-Type: application/json");
echo json_encode([ "failure" => "Login failed" ]);
}
and then:
$.post(
"signnin.php",
{ email, password },
function(data, status){
if(data.failure){
console.log('same');
} else {
console.log('not same');
}
}
);
You are probably sending whitespaces in your PHP script. There are 2 ways to solve this -
Ensure that you put the starting php tag from the very first line and don't put the ending php tag (?>).
Instead of comparing texts, compare numbers. In php script echo 1 and in js compare data==1. This way whitespaces are automatically ignored.

Redirect to URL if input exists in database

I'm trying to redirect a user to an existing URL (stored in a MySQL database) if the value they input already exists in the database. I've got most of it working, but I've run into some issues.
I'm using AJAX to check the database. It sends the input value to another PHP file & checks the database to see if it already exists.
if($row) {
echo ".$row["itemNum"].";
} else {
}
It's within the AJAX code that I'm having issues, in particular this:
success: function (response) {
if (response == <?php ".$row["itemNum"]." ?>) {
window.location.href = "http://www.example.com/" <?php echo "+"; if (".$row["itemNum"].") { echo ".$row["itemNum"]." } else {""}
} else {
// do other stuff
}
}
$row["itemNum"] doesn't always exist, so it's in a conditional statement to prevent a syntax error.
The above doesn't work regardless of how I do it.
I have a feeling the main issue is with the if (response == <?php ".$row["itemNum"]." ?>) line?
Based on this code:-
if($row) {
echo $row["itemNum"]; // check the change here
} else {
}
You have to do like this:-
success: function (response) {
if (response !== '') { // if response have some value
window.location.href = "http://www.example.com/"+response;
} else {
// do other stuff
}
}
As you suspected you have problem with following line.
if (response == <?php ".$row["itemNum"]." ?>) {
The Problem is your use of (") and (.) characters
Following syntax will give you what you want.
if (response == <?=$row["itemNum"]?>) {

Use data from JQuery .get function in an Else If statement

I am running a simple .get statement with JQuery:
$.get("check.php", function(data)
{
if (data == "yes")
{
$('#thisimg').attr('src' ,'yes.jpg');
}
else
{
$('#thisimg').attr('src' ,'no.jpg');
}
});
When I call an alert with data as the parameter it returns "yes", however the if statement is still not running and changing the images src.
This is my check.php file:
<?php
//connect to db here
//run sql select statement to check whether or not the value is 0 or 1
//value is saved into variable $selected, and the value is 1
if ($selected == 1)
{
echo "yes";
}
else
{
echo "no";
}
?>
Oftentimes there will be an invisible character in returned data. If you .trim data it should work:
if (data.trim() == "yes")
{
$('#thisimg').attr('src' ,'yes.jpg');
}
else
{
$('#thisimg').attr('src' ,'no.jpg');
}

How has the return of a PHP-function to look like to be valid for use by AJAX and PHP?

I got an input field. The user-input is getting checked on the fly by some AJAX request. The user is then getting informed whether his/her input is ok or not.
After submitting, the input has to be checked again for the same characteristics as it was checked before by AJAX(in case of JavaScript is deactivated).
AJAX uses "check.php" asynchronously.
<?php
include 'foo.php';
$input= $_POST['input'];
checkSomethingElse(testSomething($input));
?>
Then i got a "submit.php" file that is getting called on submission. It checks the input, and then writes the input into Database.
<?php
include 'foo.php';
$input= $_POST['input'];
checkSomethingElse(testSomething($input));
foo(){
//write input into Database}
?>
The "foo.php" looks like this
<?php
function testSomething(){
//do something
}
function checkSomethingElse(){
//test...
echo value // e.g. echo "true"
return value // e.g. return true
?>
(e.g. validate and sanitize input and other checks)
For the purpose of AJAX/JS/JQuery to use the returned value, it is returned trough "echo".
For the purpose of PHP to use the returned value, it is returned trough "return".
In case of AJAX-request there is everything fine, since it ignores the "return" and uses only "echo". In case of PHP it uses the "return value" and prints out the "echo value".
So the question is:
Is this structure logically and functionally ok? And how can i fix this code to spit out a string trough the "echo", when the user is not using JavaScript?
Thank You.
first of all the first issue i can see is that you are calling echo after return ... which will never happen, because execution of the function ceases once it hits return.
I would suggest just making your functions that return a value and then determine if you need to echo it afterwards ...
<?php
function some_function() {
return "value";
}
$value = some_function();
if (isset($_POST["returnajax"])) {
echo $value;
}
?>
as #rm-vanda suggests - json_encode may be useful to you if you are processing the AJAX request expecting a JSON. In this case it might look something like this...
function some_function() {
return "value";
}
function some_other_function() {
return "another_value";
}
$values = array();
$values[] = some_function();
$values[] = some_other_function();
if (isset($_POST["returnajax"])) {
header("Content-Type: application/json");
echo json_encode($values);
}
the resulting echo would look something like this:
["value","another_value"]
unfortunately, you may find that jquery will not like non well formed json. what i usually do is the following:
if (isset($_POST["returnajax"])) {
header("Content-Type: application/json");
echo json_encode(array("values"=>$values));
}
which would result in:
{"values":["value","another_value"]}
Separate the display logic from the validation logic.
For example:
// validation functions
function testSomthing(){
//test...
return $value; // e.g. return true
}
function checkSomethingElse(){
//test...
return $value; // e.g. return true
}
// calling logic in check.php
include 'foo.php';
$result = false;
if (!empty($_POST['input']) {
$input= $_POST['input'];
$result = checkSomethingElse(testSomething($input));
}
$return = new stdClass();
$return->result = $result;
header("Content-Type: application/json");
echo json_encode($return);
Note: it is not clear from your example why you have nested validation function calls (i.e. checkSomethingElse(testSomething($input))). I don't think it will work that way (because you will pass true/false result to outer function call), but I am showing the code here the same as you do, as I certainly don't have full picture as to function usage to offer up an alternative.
You can check the variable $_SERVER['HTTP_X_REQUESTED_WITH']
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
/* special ajax here echo for example*/
}
else {
/* Not AJAX use return*/
}

Parameter from url with php and write it into js variable in an if condition

I am trying to get a parameter from the url with php and write it into a js variable to do some jquery stuff.
my url looks like that
www.example.com/?v=12345
My Code
vnew = "<?php echo $_GET["v"];?>";
if (vnew == null) {
myfunction();
}
else {
$(".myDiv").attr('src','newsrc');
$(".title").html("bla");
};
if the url is like www.example.com shouldn't the value be 'null', so that my function fires?
However if i set it to '12345' the else condition does not fire either.
What is wrong here? Thank you!
Change it like this:
<?php if ($_GET["v"]) { ?>
myfunction();
<php } else { ?>
$(".myDiv").attr('src','newsrc');
$(".title").html("bla");
<?php } ?>
OR
<?php
if ($_GET["v"]) {
echo "myfunction();";
} else {
echo "$(\".myDiv\").attr('src','newsrc'); $(\".title\").html(\"bla\");";
} ?>
to check if your condition is working:
<?php
if ($_GET["v"]) {
echo "myfunction();";
} else {
echo "Hello";
} ?>
It'll never be null, only an empty string. Think about what the JS output is if no value is passed:
vnew = ""; //no PHP output between the quotes, as no value found
In any case you don't need PHP to grab the var, in any case.
var tmp = location.search.match(/v=([^&]+)/), vnew = tmp ? tmp[1] : null;
In this case, the value WILL be null if no value is found.
Try var_dump($_GET["v"]) on the base url. Use that value in your comparison.

Categories

Resources