How to convert Ajax response to string to compare with JS string - javascript

How do I convert Ajax response into plain text string?I have global variable and I store the ajax response to it but when I'm going to compare it with javascript string when even they are equal It returns false.
Here is my code:
function checkUsn(){
var usn = document.getElementById("usn").value;
if(usn){
$.ajax({
type: 'post',
url: 'checkdata.php',
data: {
emp_username: usn,
},
success: function(response){
console.log(response);
myGlobalContainer.usn = response; //convert it to compare with string
$('#status').html(response);
}
});
}
}
in console when I type the existing username in database it logs OK. This OK stores in myGlobalContainer.usn, but when I do comparison like code below it return false.
if(myGlobalContainer.usn == "OK"){
return true;
}else{
return false;
}
I will add php file.
<?php
header("Content-Type: text/plain");
include 'db_config.php';
$conn = new mysqli($db_servername, $db_username, $db_password, $db_name);
if(isset($_POST['emp_username'])){
$usn = $_POST['emp_username'];
$checkdata = "SELECT emp_username FROM emp_details where emp_username='$usn'";
$query = mysqli_query($conn, $checkdata);
if(mysqli_num_rows($query) > 0){
echo "OK";
}else{
echo "Your Username not exist";
}
exit();
}
if(isset($_POST['emp_pw']) && isset($_POST['emp_usn'])){
$pw = $_POST['emp_pw'];
$usn = $_POST['emp_usn'];
$get_pw = "SELECT emp_password FROM emp_details where emp_username='$usn'";
$query = mysqli_query($conn, $get_pw);
//$get_num_rows = mysqli_num_rows($query);
//echo $get_num_rows;
$row = mysqli_fetch_assoc($query);
//echo $row["emp_password"];
// check if password is match with username
if($pw == $row["emp_password"]){
echo "MATCH";
}else{
echo "Wrong password";
}
exit();
}
?>
Please help Thanks!

By default, jQuery's ajax function will determine the type of data it is receiving from the Content-Type response header.
You can override that with the dataType parameter.
$.ajax({
dataType: "text",
// etc etc
});
… however, since the response seems to be "OK" and not HTML, it is likely that your PHP should be adjusted so it outputs the correct Content-Type:
<?php
header("Content-Type: text/plain"); # Override the default (text/html)
echo "OK";
So also make sure that the response is really simply "OK" and that you are not outputting (for example) "OK" followed by a new line.

I've change my code to
success: function(response){
console.log(response);
myGlobalContainer.usn = response.trim(); //convert it to compare with string
$('#status').html(response);
and It works but Guys thanks for your help very appreciated!
also thanks to this question
Ajax response doesn't equal what I think it should

i seem you should use a function in ajax success.
var myGlobalContainer.usn = "";
function signAndCompare(str)
{
myGlobalContainer.usn = str
if(myGlobalContainer.usn == "OK")
{
console.log("true");
return true;
}
console.log("false");
return false;
}
function checkUsn(){
var usn = document.getElementById("usn").value;
if(usn){
$.ajax({
type: 'post',
url: 'checkdata.php',
data: {
emp_username: usn,
},
success: function(response){
console.log(response);
signAndCompare(response);//this line: **compare** and sign response
$('#status').html(response);
}
});
}

Related

jQuery AJAX Getting json parseError in the console and responses goes to error function but php script runs fine

I tried researching a lot before posting here.
There are two files login.php and login-validation.php
Login.php file contains code including login form and jQuery AJAX script to call login.validation.php
--- Code of login.php ---
$(document).ready(function() {
$('#login-form').submit(function(e) {
e.preventDefault();
mobile_no = $('#mobile_no').val();
upassword = $('#upassword').val();
console.log(mobile_no, upassword);
$.ajax({
type: "POST",
url: "server/login-validation.php",
data: {
Mobile_no: mobile_no,
Password: upassword
},
cache: false,
dataType:'json',
success: function(response) {
console.log("Data gone successfully");
if(response["type"] == 'LoginSuccess'){
$('#success-message').text(response); // This works but not below ones
}
if(response["type"] == 'WrongCredentials'){
$('#success-message').text(response);
}
else{
$('#success-message').text(response);
}
},
error: function(xhr, textStatus, errorThrown){
console.log(xhr.responseText); Shows my echo message i.e. Wrong credentials for wrong credentials
console.log(textStatus); // Shows parseError
console.log(errorThrown); // Shows SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
}
});
});
});
</script>
---Code of login.validation.php---
session_start();
$message = array(); //Creating array variable to display custom messages depending on [TYPE]
//Require DB
require_once('db.php');
//Get values from the login form
$Mobile_number = $mysqlconnect->real_escape_string(trim($_POST['Mobile_no']));
$Password = $mysqlconnect->real_escape_string(trim($_POST['Password']));
//Query database for valid input match
$validation = "SELECT * from team_captain WHERE Mobile_Number = '$Mobile_number'";
$query = $mysqlconnect->query($validation);
$result = mysqli_num_rows($query);
if($result > 0){
$fetch_pass = mysqli_fetch_array($query);
$password_hash = $fetch_pass['User_Password'];
if(password_verify($Password,$password_hash))
{
$message["type"] = 'LoginSuccess';
$_SESSION['sess_username'] = $fetch_pass['Full_Name'];
}
else{
$message["type"] = 'WrongCredentials';
echo "Wrong credentials". $mysqlconnect->error;
}
}
else{
$message["type"] = 'WrongMobile';
echo "Mobile number doesn't exists";
}
header('Content-type: application/json');
echo json_encode($message);
?>
Tried dataType: 'json' - Didn't work
Tried without dataType - Didn't work
Php script is running properly with right error messages for different "if" statements but AJAX responses goes to error:function() rather than success: function()
In the network tab - The response type is JSON and it displays [type] i.e [WrongCredentials]
Not understanding what is wrong here. Any help would be appreciated.
You need to parse the JSON response using jQuery.parseJSON()
var data = jQuery.parseJSON(response);
Now, you can check it
if(data.type == "LoginSuccess"){
// do something
}elseif(data.type == "Wrong Password"){
// do something else
}
And remove echo from your php code
session_start();
$message = array(); //Creating array variable to display custom messages depending on [TYPE]
//Require DB
require_once('db.php');
//Get values from the login form
$Mobile_number = $mysqlconnect->real_escape_string(trim($_POST['Mobile_no']));
$Password = $mysqlconnect->real_escape_string(trim($_POST['Password']));
//Query database for valid input match
$validation = "SELECT * from team_captain WHERE Mobile_Number = '$Mobile_number'";
$query = $mysqlconnect->query($validation);
$result = mysqli_num_rows($query);
if($result > 0){
$fetch_pass = mysqli_fetch_array($query);
$password_hash = $fetch_pass['User_Password'];
if(password_verify($Password,$password_hash))
{
$message["type"] = 'LoginSuccess';
$_SESSION['sess_username'] = $fetch_pass['Full_Name'];
}
else{
$message["type"] = 'WrongCredentials';
}
}
else{
$message["type"] = 'WrongMobile';
}
header('Content-type: application/json');
echo json_encode($message);
?>

How to retrieve boolean value from php to javascript file

is that possible to retrieve Boolean value from php to javascript?
All I want to do is simple: Retrieve Boolean value from php variable $x into js
Should be true when emails are sent
And False when emails are not sent
Then take that Boolean value with javascript print the appropriate message
Complete code of my work can be found here, on my other case I had opened yesterday
PHP:
if (!$mail->send()) {
$x = false; //when email is not sent
} else {
$x = true; //when email is sent
}
JS Pseudocode
.done(function (data) {
if(php Boolean variable is false) {
("$formText").html("Message sent");
} else (if php Boolean variable is true) {
("$formText").html("Message not sent");
}
});
I am assuming you are already passing data (via AJAX) you just don't know how to encode it.
Use: json_encode()
PHP:
if (!$mail->send()) {
$x = true;
} else {
$x = false;
}
header("Content-type: application/json");
echo json_encode(array('x'=>$x));
Javascript:
.done(function (data) {
if (data.x) {
$("#formText").html("Message sent");
} else {
$("#formText").html("Message not sent");
}
} //end function data
);//end done function
While returning bool value from PHP code use json_encode(). It convert from native PHP types to native Javascript type.
http://php.net/manual/en/function.json-encode.php
using response code and handling them with done and fail
PHP
<?php
// ...
$success = '{"message": "your mail is send"}';
$error = '{"message": "failed sending mail"}';
$code;
$out;
if(mailSend){
$code = 200;
$out = $success;
} else {
$code = 400;
$out = $error;
}
http_response_code($code);
echo $out;
JS
// ...
var data = 'yourData';
$.ajax({
url: 'yourApiUrl'M,
data: data,
method: 'POST',
xhrFields: {withCredentials: true},
crossDomain: true,
dataType: 'json'
}).done(function() {
// mail was send
}).fail(function() {
// error on sending
});
a list of status codes you can find on https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

How to handle success with 'if - else' in ajax call and response?

I have a written code in AJAX which checks whether password exists or not. if yes it sends "OK" as output else "Incorrect " as output . i want to success handler in AJAX call's response to do task based on that. How can handle it? I want if password is correct , to remove Attribute of disabled in a form element else i want i want that form element's attribute remained back as disabled.
AJAX code goe like this :
$("#currentpassword").keyup(function() {
var name = $(this).val();
if (name.length > 5) {
$("#result").html('checking...');
$.ajax({
type: 'POST',
url: 'checkPassword.php',
data: $(this).serialize(),
success: function(data) {
if (data == "1") {
$("#result").html(data);
$("#newpassword").removeAttr("disabled");
$("#confirmpassword").removeAttr("disabled");
} else {
$("#result").html(data);
}
}
});
return false;
} else {
$("#result").html('');
}
});
checkpassword php file looks like below :
<?php
include_once 'includes.php';
// Submitted form data
$currentpassword=$_POST['currentpassword'];
$result = mysqli_query($db,"SELECT * FROM `users` WHERE `password`='$currentpassword' AND `username`='$session_username'");
$row = mysqli_num_rows($result);
if($row!=1) {
echo "<span style='color:red;'>Incorrect Password !!!</span>";;
}
else {
echo "OK";
}
// Output status
?>
The Good way is The PHP file should look like this
<?PHP
header('Content-type:application/json;charset=utf-8');
include_once 'includes.php';
$currentpassword=$_POST['currentpassword'];
$result = mysqli_query($db,"SELECT * FROM `users` WHERE `password`='$currentpassword' AND `username`='$session_username'");
$count = mysqli_num_rows($result);
if($count! = 1) {
header('HTTP/1.1 401 Unauthorized', true, 401);
echo json_encode('In Correct Password');
} else {
header('HTTP/1.1 404 Not Found', true, 404);
echo json_encode('Not Found');
}
And your Jquery will be
$.ajax({
type: 'POST',
url: 'checkPassword.php',
data: $(this).serialize(),
success: function(data) {
// Only 200 comes here
}, error(jqXHR, exception) {
// All errors except 200 comes here.
}
});
Hope this helps

Ajax POST to PHP - How do I do a reply?

I have sent an email address via an ajax post from javascript to php. I have then searched the database in php to find out if this email exists in the database. How can i then send a message back to the javascript/html to say that the value was present?
This is what I used to send the request:
function postEmail(){
var checkEmail = "someone#gmail.com";
var dataString = 'checkEmail1='+ checkEmail;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "myfile.php",
data: dataString,
cache: false,
success: function(result){
alert("Sent successfully");
}
});
}
and then in the PHP:
$checkEmail2=$_POST['checkEmail1'];
$results = mysql_query("select id from myTable where emailaddress='$checkEmail2' ");
$row = mysql_num_rows($results);
if ($row > 0 ) {
echo "email already exists";
} else {
if ($row == 0 ) {
echo "email doesnt exist";
}
}
Not sure if I should do a get request? Or if you return values or something. Thanks.
(p.s, Im developing a hybrid app so need to use JSON to send/retrieve from PHP)
I think you need to remove second condition! output json or any other format you want. I use json_encode for arrays
try:
$checkEmail2=$_POST['checkEmail1'];
$results = mysql_query("select id from myTable where emailaddress='$checkEmail2' ");
$row = mysql_num_rows($results);
if ($row > 0 ) {
echo "email already exists";
} else {
echo "email doesnt exist";
}
JAVASCRIPT
from your success function, print the result to the console to see the output
console.log(result);
What you echo from the PHP script is sent back to the success function in the javascript, as the result parameter. So the result parameter will contain "email already exists" or "email doesnt exist"

Convert ajax response array object to javascript array?

I am using ajax to submit a login form in Yii. Here is my ajax function:
$("#login-form").submit(function() {
var email = $("#email").val();
var password = $("#password").val();
$.ajax({
url: "<?php echo Yii::app()->request->baseUrl; ?>/site/validatelogin",
type: "post",
data: "email=" + email + "&password=" + password,
success: function(response) {
if (response === "1") {
window.location.href = "<?php echo Yii::app()->getBaseUrl(true); ?>/dashboard";
}
else
{
//Dispaly response errors above login form
}
},
error: function() {
alert("Could not perform the requested operation due to some error.");
return false;
}
});
});
My PHP controller function is validatelogin as follows:
$email = $_POST['email'];
$password = $_POST['password'];
$model = new LoginForm();
$model->email = $email;
$model->password = $password;
if ($model->validate() && $model->login()) {
echo "1";
} else {
print_r($model->getErrors());
}
If the user enters correct credentials I send 1 as response to view and user is redirected to dashboard.
But if user enters incorrect credentials then different errors are received in ajax response depending upon the type of error.
I want to display those errors above login form in else part of success function through a loop.
But when I run the loop over response then that array has very large length i.e for example if the error in response was "Incorrect password" then the response array has length of 18(the number of characters) in the error message. In short the response array is like:
array('I','n','c','o','r','r'....)
rather than
array([0]=>"Incorrect password")
How do I convert response array in the latter format and iterate over each index to display error message to the user above the login form?
Encode it to JSON.
In your php:
echo json_encode($model->getErrors());
In your js (in the else):
var errors = $.parseJSON(response);
Edit:
In your case it would be better to always return JSON.
Your JS could be changed to:
var jqxhr = $.post("<?php echo Yii::app()->request->baseUrl; ?>/site/validatelogin", {
email: email,
password: password
}, 'json');
jqxhr.done(function(response) {
if (response.valid) {
window.location.href = "<?php echo Yii::app()->getBaseUrl(true); ?>/dashboard";
} else {
if (response.errors) {
...
}
}
});
jqxhr.error(function(response) {
alert("Could not perform the requested operation due to some error.");
});
Your PHP:
$response = array('valid' => false);
if ($model->validate() && $model->login()) {
$response['valid'] = true;
} else {
$response['errors'] = $model->getErrors();
}
header('Content-type: application/json');
echo json_encode($response);
In addition to #sroes's answer, use Yii library for JSON
echo CJSON::encode($response);
instead of
echo json_encode($response);
why ?
Why use CJSON encode when we have json_encode

Categories