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

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

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);
?>

Cant display json data on the page using php and ajax

I have create a php file that generates json data. As shown below but it does not seem to return any data.
When i try to get data.status i get an undefined error. it seems to be connecting to the file no problem as previously i have coded an alert which drags back all the data but i cant seem to get a specific value.
Below i have trying to retrieve the status: ok value.
Json Data:
{"status":"ok","Results":{"SiteId":"1","SiteCode":"RWP50","DateCreated":"2019-09-25 09:14:23","DateClosed":null}}
Ajax Code
$('#ddlsite').change(function () {
var SiteCode = $('#ddlsite').val();
alert(SiteCode);
$.ajax({
type: 'GET',
url: 'GetSites.php',
datatype: 'json',
contentType: "application/json; charset=utf-8",
success:function(data){
alert(data.status);
if(status == "ok"){
alert('It Worked');
}else{
alert('It Failed');
}
}
});
});
PHP File
<?php
// if(!empty($_POST['SiteCode'])){
$data = array();
// Create connection
include 'connecting_test.php';
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to delete a record
$sql = "SELECT * FROM Site";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
// while($row = $result->fetch_assoc()) {
$SiteData = $result->fetch_assoc();
$data['status'] = 'ok';
$data['Results'] = $SiteData;
// }
} else {
echo "0 results";
}
echo json_encode($data);
$conn->close();
// }else {
// echo "hello";
// }
?>
you just need to update your ajax
$.ajax({
type: 'GET',
url: 'xhr.php',
datatype: 'json',
contentType: "application/json; charset=utf-8",
success:function(data){
data = JSON.parse(data);
if(data.status == "ok"){
alert('It Worked');
}
else{
alert('It Failed');
}
}
});
Because you need to parse json which are return from php file
I assume your ajax api call is working fine, and returns correctly, as the datatype is json,
So the alert should work perfectly but the if statement
if(status == "ok") can't find the reference of variable status. It should be data.status if it's not declared somewhere else then type error will be thrown...

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

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);
}
});
}

Ajax failed registration do not echo result

I have a an ajax post method that if success will alert "account successfully created". my problem is when it's not created it should alert account already exists, But what the problem it still alert the same.
script code:
$(document).ready(function(){
$("#btn-register").click(function(){
var regaccount = $("#regaccount").val();
var regpass = $("#regpass").val();
if((regaccount == "") || (regpass == "")){
alert("Information required!");
}else {
$.ajax({
type: "POST",
url: "register.php",
data: "regaccount="+regaccount+"&regpass="+regpass,
success: function(data){
alert("account successfully created!");
},
error:function(){
alert("account already exists");
}
});
}
$("#regaccount").val('');
$("#regpass").val('');
return false;
});
});
register.php
<?php
include 'function.php';
session_start();
ob_start();
$userid = rand(100000, 999999);
$regaccount = $_POST['regaccount'];
$regpass = $_POST['regpass'];
$regaccount = stripslashes($regaccount);
$regpass = stripcslashes($regpass);
$salt = "dctech2015ABcRXd";
$regpass = md5($regpass) . $salt;
$regpass = sha1($regpass);
$con = new Functions();
$con = $con->db;
$stmt = $con->query("SELECT * FROM users WHERE username = '$regaccount'");
$count = $stmt->rowCount();
if($count != 1){
$con = new Functions();
$con = $con->db;
$status="Offline";
$stmt = $con->prepare("INSERT INTO users(user_id, username, password, status)VALUES(:userid, :account, :password, :status)");
$stmt->bindValue(':userid', $userid);
$stmt->bindValue(':account', $regaccount);
$stmt->bindValue(':password', $regpass);
$stmt->bindValue(':status', $status);
$stmt->execute();
}else{
echo '<script>alert("account name already exists");</script>';
}
ob_end_flush();
?>
You need to do following changes to make this work:
1) In your PHP code, do not write any alert.
2) Whether user exists in database or newly inserted, AJAX request will fetch only data. We have to handle the logic.
3) AJAX error method will be called only when AJAX request is failed (either request not sent or response status is not 200 OK).
4) In your case, error method will never be called if user already exists or even user is inserted as data is being correctly transferred from JavaScript to PHP.
if($count != 1){
$con = new Functions();
$con = $con->db;
$status="Offline";
$stmt = $con->prepare("INSERT INTO users(user_id, username, password, status)VALUES(:userid, :account, :password, :status)");
$stmt->bindValue(':userid', $userid);
$stmt->bindValue(':account', $regaccount);
$stmt->bindValue(':password', $regpass);
$stmt->bindValue(':status', $status);
$stmt->execute();
echo 'success';
}
else{
echo 'exists';
}
AND
$.ajax({
type: "POST",
url: "register.php",
data: "regaccount="+regaccount+"&regpass="+regpass,
success: function(data){
if (data == 'success') {
alert("account successfully created!");
}
else if (data == 'exists') {
alert("account already exists");
}
},
error:function(){
alert("Unknown problem occured.");
}
});
Here you are trying to prompt message into AJAX error section which is wrong. You need to handle both into success section.
The very simple example is, return $count and check that value if greater then 0 means record is exist.
Changes in register.php code:
if($count != 1){
$con = new Functions();
$con = $con->db;
$status="Offline";
$stmt = $con->prepare("INSERT INTO users(user_id, username, password, status)VALUES(:userid, :account, :password, :status)");
$stmt->bindValue(':userid', $userid);
$stmt->bindValue(':account', $regaccount);
$stmt->bindValue(':password', $regpass);
$stmt->bindValue(':status', $status);
$stmt->execute();
}
echo $count;
I remove else part which is not require. And use $count for AJAX response.
And make correspond change into AJAX part also:
$.ajax({
type: "POST",
url: "register.php",
data: "regaccount="+regaccount+"&regpass="+regpass,
success: function(data){
//If record exist...
if(data > 0){
alert("account name already exists");
}
else {
alert("account successfully created!");
}
},
error:function(){
alert("There is some error, Please try after some time OR contact site admin.");
}
});
Hope this is very easy to understand and help to other user also.

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