Comparing php value with javascript variable? - javascript

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.

Related

How to check successful data Submit using MySQL in a PHP file

I'm submitting a form using MySQL command inside a PHP file. I'm able to insert the data without any problem.
However, I also, at the same time, want to display the user a "Thank you message" on the same page so that he/she knows that the data has been successfully registered. On the other hand I could also display a sorry message in case of any error.
Therein lies my problem. I've written some lines in Javascript to display the message in the same page. However, I'm stuck on what (and how) should I check for success and failure.
I'm attaching my code below.
Can you please help me on this with your ideas?
Thanks
AB
HTML Form tag:
<form id="info-form" method="POST" action="form-submit.php">
form-submit.php:
<?php
require("database-connect.php");
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$sql = "INSERT INTO tbl_details ".
"(name,email_id,mobile_number) ".
"VALUES ".
"('$name','$email','$mobile')";
mysql_select_db('db_info');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
return false;
}
echo "Entered data successfully\n";
mysql_close($conn);
?>
submit-logic.js:
$(function ()
{
$('form').submit(function (e)
{
e.preventDefault();
if(e.target === document.getElementById("info-form"))
{
$.ajax(
{
type:this.method,
url:this.action,
data: $('#info-form').serialize(),
dataType: 'json',
success: function(response)
{
console.log(response);
if(response.result == 'true')
{
document.getElementById("thankyou_info").style.display = "inline";
$('#please_wait_info').hide();
document.getElementById("info-form").reset();
}
else
{
document.getElementById("thankyou_info").style.display = "none";
document.getElementById("sorry_info").style.display = "inline";
$('#please_wait_info').hide();
}
}
}
)};
});
}
Per documentation: http://api.jquery.com/jquery.ajax/
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server.
You are explicitly setting this to json but then returning a string. You should be returning json like you are telling the ajax script to expect.
<?php
require("database-connect.php");
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$mobile = mysql_real_escape_string($_POST['mobile']);
$sql = "INSERT INTO tbl_details ".
"(name,email_id,mobile_number) ".
"VALUES ".
"('$name','$email','$mobile')";
mysql_select_db('db_info');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die(json_encode(array('result' => false, 'message' => 'Could not enter data: ' . mysql_error()));
}
echo json_encode(array('result' => true, 'message' => 'Entered data successfully'));
mysql_close($conn);
?>
I also added code to sanitize your strings, although mysql_* is deprecated and it would be better to upgrade to mysqli or PDO. Without sanitization, users can hack your database..
Nevertheless, returning json properly will ensure that your response in success: function(response) is an object, and response.result will be returned as expected, and you can use response.message to display the message where you want.

php string comparison search only returning one entry not returning correct entries

I'm using ajax to send a search string to a php script that executes a mysql like function to find all related entries with the username like the string being sent for friend searching. I have two current entries in the database zukeru and zukeru2. when i search z i only get zukeru returned in my console output. When i search 2 i still get zukeru and im really not sure why.
Also how to i remove a specific field from a php nested tupple. I don't want to include the password field for obvious reason. Sorry im new to php learning as i go so far its not as bad as I thought it would be kinda similar to python.
returned object when searching the number 2, but i get zukeru and not zukeru2 doesn't make sense.
Object {0: "2", 1: "you wish you could see", 2: "zukeru", 3: "deleted for security", 4: "grant", id: "2", email: "deleted for security", username: "zukeru", password: "deleted for security", name: "grant"}
this is the search string i used for the above result. You can see i searched 2 and got back zukeru and not zukeru2
profile.php:92 searchstring=2
<?php
$db = new mysqli(security reasons removed.);
extract($_POST);
//I think i can remove this session start ?
session_start();
$serach_string = $_POST['searchstring'];
$fetch=$db->query("SELECT * FROM users WHERE username LIKE '%$serach_string%'");
$friends=mysqli_fetch_array($fetch);
//echo $search_string
echo json_encode($friends);
?>
Here is my jquery incase you wanted to see
function search(){
var url = "search_friends.php";
$.ajax({
type: "POST",
url: url,
data: $("#search_friends").serialize(), // serializes the form's elements.
success: function(data)
{
//console.log(data);
var returned_friends = JSON.parse(data);
var html_built = '<br>';
console.log(returned_friends);
console.log($("#search_friends").serialize());
if (returned_friends){
$.each( returned_friends, function( key, value ) {
if (key =="username"){
html_built += '<li><a href="#"><button class="btn btn-primary" style="width:100%;" id="'+value+'" onClick="add_friend(this.id)"> Send '+value+' A Friend Request</button></li>';
}
});
}
html_built += ""
document.getElementById("list_friends").innerHTML = html_built;
}
});
return false;
}
this is what im currently using and I get undefined method. It cant find fetch_all(); and im using php 5.4
here is the console error returned.
<br />
<b>Fatal error</b>: Call to undefined method mysqli_result::fetch_all() in <b>/home/gzukel/public_html/search_friends.php</b> on line <b>7</b><br />
<?php
$db = new mysqli();
extract($_POST);
session_start();
$serach_string = $_POST['searchstring'];
if($fetch=$db->query("SELECT username FROM users WHERE username LIKE '%$serach_string%'")){
$friends=$fetch->fetch_all();
echo json_encode($friends);
}else{
echo 'no results';
}
?>
so something like this?
<?php
$db = new mysqli();
extract($_POST);
session_start();
$serach_string = $_POST['searchstring'];
$fetch=$db->query("SELECT * FROM users WHERE username LIKE '%$serach_string%'");
$friends=[]
while($row = $fetch->fetch_array())
{
$rows[] = $row;
}
foreach($rows as $row)
{
array_push($friends,$row['username']);
}
//echo $search_string
echo json_encode($friends);
?>
You Could use fetch all:
if($fetch=$db->query("SELECT username FROM users WHERE username LIKE '%$serach_string%'")){
$friends= $fetch->fetch_all();
echo json_encode($friends);
}else{
echo 'no results';
}

Trying to call PHP script from Javascript If statement

I have a form which gets validated by javascript. In one of the if statements, in the final condition (when everything else has been validated) I would like to put my PHP script that updates SQL with one of the passwords.
This is the final validation:
function passwordCheck() {
var password = '<?php echo $password; ?>';
if (document.passwordform.inputedPassword.value == password)
{
if (document.passwordform.Password1.value == document.passwordform.Password2.value)
{
*********************************************************
} else
{
document.getElementById("equalpasswords1").innerHTML = "Passwords should be equal";
document.getElementById("equalpasswords2").innerHTML = "Passwords should be equal";
}
} else
{
text = "Insert a correct password";
document.getElementById("editpassword").innerHTML = text;
}
return true;
}
And I would like to insert a call to my PHP script where the stars are. How could I do this? I read that you can't insert PHP into javascript, so it has to be an external PHP file. My SQL update code is this one:
<?php
$x = $_POST['Password2'];
define('DB_NAME', 'Students');
define('DB_USER', 'Students');
define('DB_PASSWORD', 'Password');
define('DB_HOST','HOST');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can\'t use'. DB_NAME. ': ' . mysql_error());
}
$result = "UPDATE `1956218_students`.`Students` SET `Password` = '$x' WHERE `Students`.`StudEmail` = '$email' ";
if (!mysql_query($result)) {
die('error: ' .mysql_error());
}
?>
You need to realize that JavaScript is being executed at client's side (in browser), while the PHP code is being executed at server's side.
So you need to make another request to the server, so that PHP codes can handle / process it (validate the password, prepare some response - ideally in JSON format etc.).
You might want to do something like:
How to validate a username / password via JQuery / Ajax?

Trying to show sucess message with jQuery concatenated with php echo

Im trying to do a recover password system with jQuery messages and Im having a problem.
The code below is working fine, when I click in the button to recover my username and password I get the message <p class="sucess">Email sent with your data..</p>.
But I want to put the email of the user in the message. Like this:
<p class="sucess">Email sent with your data for email#example.com!</p>
Im trying like this in my php
else {
echo 'sucess'; //here I show the jQuery message
echo $result['email']; //and then I want to show my $result['email']
return;
}
I already try like this:
echo 'sucess'.$result['email'].'';
But I have always the same problem, Im entering here in my jQuery:
else
{
alert('Error in system');
}
And if I dont put this echo in $result['email'] the sucess message works fine, but when I try to echo my $result['email'] Im always entering in this jQuery condition.
Somebody there have any idea why this is happening?
My php:
switch ($action){
case 'recover':
$email = $_POST['email'];
if($email == ''){
echo 'errorempty';
}else{
$searchEmail = $pdo->prepare("SELECT * FROM admins WHERE email=:email");
$searchEmail->bindValue(":email", $email);
$searchEmail->execute();
$num_rows = $searchEmail->rowCount();
$result = $searchEmail->fetch(PDO::FETCH_ASSOC);
if($num_rows <=0 )
{
echo 'erroremail';
return;
}
else {
echo 'sucess';
echo $result['email'];
return;
}
}
break;
default:
echo 'Error';
}
}
My jQuery:
$('#recover').submit(function(){
var login = $(this).serialize() + '&action=recover';
$.ajax({
url: 'switch/login.php',
data: login,
type: 'POST',
success: function(answer){
if(answer== 'erroempty'){
$('.msg').empty().html('<p class="warning">Inform your email!</p>').fadeIn('slow');
}
else if (answer == 'erroemail'){
$('.msg').empty().html('<p class="error">Email dont exist!</p>').fadeIn('slow');
}
else if(answer == 'sucess'){
$('.msg').empty().html('<p class="sucess">Email sent with your data..</p>').fadeIn('slow');
window.setTimeout(function(){
$(location).attr('href','dashboard.php');
},1000);
}
else{
alert('Error in system');
}
},
beforeSend: function(){
$('.loginbox h1 img').fadeIn('fast');
},
complete: function(){
$('.loginbox h1 img').fadeOut('slow');
},
error: function(){
alert('Error in system');
}
});
return false;
});
you can simple echo the $email like this
$email=$result["email"];
echo $email;
then in ajax success function
if(answer.email)
{
$('.msg').empty().html('<p class="sucess">Email sent with your data..'+answer.email+'</p>').fadeIn('slow');
}
The problem is, that you server side is returning just unstructured data and the client side part will just receive a plain string like sucessdummy#example.com in the answer variable.
This answer variable is compared with strings that do not match thought your script ends in the error case. I would go for a solution by returning some kind of structured data like json.
Your server side code could look something like
$result = array('msg'=>'success','mail'=>$result['email']);
header('Content-type: application/json');
echo json_encode($result);
You have to pass the dataType:'json' option in your jquery ajax call to make it work and can access the data in the call back function like answer.msg, answer.mail

Failing insert statement in msql

Below is the section of my code which is causing me problems:
$usertype = $_POST['usertype'];
if ($usertype == "Administration") {
?>
<script type='text/javascript'>
window.onload = promptMessage;
function promptMessage() {
var x = 38773;
var code = prompt('Enter the administration code you have been given:', 'Enter code here');
if (code == x) {
alert("Administration code accepted");
} else {
var secondcode = prompt('The code you have entered is inccorect', 'Enter correct code here or change Usertype');
if (secondcode == x) {
alert("Administration code accepted");
} else {
location.href = 'AdminCodeFail.html';
}
}
}
</script>
<?php
$con = mysqli_connect("localhost:3306", "root", "***********", "systemone");
$sql = "INSERT INTO completeinfo (FirstName, Surname, UniID,
HouseNumber, AddressLineOne, AddressLineTwo, City,
PostCode, County, PhoneNumber, Email, Username,
Password, UserType)
VALUES
('$_POST[firstname]','$_POST[surname]','$_POST[uniid]',
'$_POST[housenumber]','$_POST[addresslineone]',
'$_POST[addresslinetwo]','$_POST[city]','$_POST[postcode]',
'$_POST[county]','$_POST[contactnumber]','$_POST[email]',
'$_POST[username]','$_POST[password]','$_POST[usertype]')";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
} else {
header("Location:SignUpComplete.html");
}
The problem I'm having is that the insert query is just not working. The query fails to insert any data into the database and I am at a loss as to why. The connection to the database is working fine and I'm receiving no errors when testing the query itself. So why isn't the query functioning?
Add
error_reporting(E_ALL);
ini_set('display_errors', '1');
after your code and it will give you more descriptive errors as to why the query is failing.
You can't have array variables in double quotes like this:
$string = "hello $array['index'] world!";
They must be:
$string = "hello {$array['index']} world!";
Your code has SQL injection vulnerabilities up the wazoo. I strongly suggest reading: How can I prevent SQL injection in PHP?
How should I write PHP $_POST vars in a mysql_query function?
this is your error and this type of question has already been answered.
use
. mysql_real_escape_string to pop out of the string and recognize a value
LOOK AT THE LINK... it will help :)

Categories

Resources