Check returned data from ajax/php - javascript

I did an update with all things you told me, this is my result.
COMPLETE UPDATE:
$(document).ready(function(){
$("#submit").submit(function(e){
e.preventDefault();
var username = $("#username").val();
var result;
var request;
if(username){
request = $.ajax({
url: 'check.php',
data: {data: JSON.stringify(username)},
type: 'POST',
dataType: "json",
success: function (data) {
result = data;
}
});
} else {
alertify.error( "ERROR" );
}
request.done(function() {
console.log(result);
if(request.result == 1) {
alert("yes")
} else {
alert("no")
}
});
});
});
check.php:
$usernameChecker = new UsernameChecker($config);
$data = $_POST['data'];
$data = json_decode($data,true);
if(!empty($data)) {
if ($usernameChecker->check_regex($data)) {
if($usernameChecker->check_length($data)) {
if (!$usernameChecker->check($data)) {
echo json_encode(array("error" => "Username already taken" , "result" => 0));
} else {
echo json_encode(array("error" => "Username available" , "result" => 1));
}
} else {
echo json_encode(array("error" => "Username too long" , "result" => 0));
}
} else {
echo json_encode(array("error" => "Allowed symbols: a-z , A-Z , 1-9 and \"_\"" , "result" => 0));
}
} else {
echo json_encode(array("error" => "You forgot to type your username" , "result" => 0));
}
This is what I have now, just console says:
"result is not defined"
SO:
When I submit empty input, I get request is undefined.
When I submit filled input, I get alert "no". Moreover this part:
"Username available"
is marked red.
But data.result is "1" in console?

Assign data to another variable to use outside of the $.ajax function
var username = $("#username").val();
var result;
var request;
if(username){
request = $.ajax({
url: 'check.php',
data: {data: JSON.stringify(username)},
type: 'POST',
dataType: "json",
success: function (data) {
result = data;
}
});
} else {
alertify.error( "ERROR" );
}
Here is the edit for you
request.done(function() {
console.log(result.result);
if(result.result == 1) {
alert("yes")
} else {
alert("no")
}
});

Related

Ajax callback is firing after function call

Hi Have a ajax call in a function thats called on date input change event to check if a date is already in use for User. the success in the Ajax call fires after the click function is finished.
How do I get the success results and continue on with the #datepicker change funtion as I need the json results for rest of function.
controller
public ActionResult IsDateAvailable(DateTime date, int Id) {
var dateAvailable = !(_context.Trading.Any(t => t.uId == Id && t.TradingDate == date));
if (!(dateAvailable)) {
return Json(new {
status = false, msg = "This date already exists."
});
}
return Json(new {
status = true
});
}
JavaScript
$(document).ready(function() {
var message;
var isDateValid;
function CheckDate(para) {
var dateValid;
var mesg;
return $.ajax({
url: '#Url.Action("IsDateAvailable", "Trading")',
type: "GET",
data: para,
dataType: "json",
success: function(data) {
if (!(data.status)) {
message = data.msg;
} else {
isDateValid = true;
}
},
error: function(xhr, httpStatusMessage) {
alert(xhr + httpStatusMessage);
}
});
}
$("#datePicker").change(function() {
$("#alert").css({
'display': 'none'
});
if (Id == 0) {
$("#alert").attr('class', 'alert alert-danger');
$("#alert").text('Please select a User.');
$("#alert").show();
return false;
}
var date = $(this).val();
var para = {
date: date,
Id: Id
};
CheckDate(para);
if (isDateValid) {
$("#btnAdd").show();
} else {
$("#btnAdd").css({
'display': 'none'
});
$("#alert").attr('class', 'alert alert-danger');
$("#alert").text(message);
$("#alert").show();
}
});
});
You should turn to being asynchronous. change your code to match with these:
.
.
.
function CheckDate(para) {
return new Promise((resolve, reject) => {
return $.ajax({
url: '#Url.Action("IsDateAvailable", "Trading")',
type: "GET",
data: para,
dataType: "json",
success: function(data) {
if (!(data.status)) {
message = data.msg;
} else {
isDateValid = true;
}
resolve();
},
error: function(xhr, httpStatusMessage) {
alert(xhr + httpStatusMessage);
reject();
}
});
}
.
.
.
checkDate(para).then(res => {
if (isDateValid) {
$("#btnAdd").show();
} else {
$("#btnAdd").css({
'display': 'none'
});
$("#alert").attr('class', 'alert alert-danger');
$("#alert").text(message);
$("#alert").show();
}
}).catch(err => { /* do something */ });
You just need to set async: false inside your ajax request. You can also remove the word return from the CheckDate, because of it's redundant:
function CheckDate(para) {
var dateValid;
var mesg;
$.ajax({
url: '#Url.Action("IsDateAvailable", "Trading")',
async: false,
type: "GET",
data: para,
dataType: "json",
success: function(data) {
if (!(data.status)) {
message = data.msg;
} else {
isDateValid = true;
}
},
error: function(xhr, httpStatusMessage) {
alert(xhr + httpStatusMessage);
}
});
}

Always shows that the username is taken

When checking if a username is taken in the DB, the code always shows the message that the username is taken. If I change the condition in ajax the message changes, but it shows always same even if user is in the DB
$(document).ready(function() {
$("#email").keyup(provjeraEmaila);
$("#korime").blur(function() {
if ($("#korime").val().length >= 5) {
$.ajax({
type: "POST",
url: "korisnici.php",
data: {
fieldName: "korisnicko_ime",
filedVal: $("#korime").val()
},
success: [function(data) {
if (data == 0) {
$("#username-span").html("username is taken!");
$("#username-span").attr('class', 'username-span');
} else {
$("#username-span").html("username is free!");
$("#username-span").attr('class', 'username-span');
}
}]
});
$("#username-span").html("");
}
});
});
This is the PHP code:
<?php
include_once 'baza.class.php';
if (isset($_POST['registracija']))
{
$veza = new Baza();
$veza->spojiDB();
$korime = $_POST['korime'];
$upit = "SELECT korisnicko_ime FROM korisnik WHERE
korisnicko_ime='$korime'";
$rezultat = $veza->selectDB($upit);
if (mysqli_num_rows($rezultat) > 0)
{
echo 0;
}
else
{
echo 1;
}
}
?>

How do I throw an error message within AJAX?

For some reason I can't throw an error message to say whether or not an email exists inside of my user table. I understand that because AJAX is async I can't use try and catch error messages inside the complete function. But I tried splitting it into functions and it still doesn't work.
Try, Catch Function (I do call this else where in my code)
try {
// Check fields are not empty
if (!firstName || !lastName || !aquinasEmail || !sPassword || !sCPassword || !Gender) {
throw "One or more field(s) have been left empty.";
}
// Check the email format is '#aquinas.ac.uk'
if(!emailCheck.test(aquinasEmail)) {
throw "The email address you entered has an incorrect email prefix. ";
}
// Check there are not any numbers in the First or Last name
if (!regx.test(firstName) || !regx.test(lastName)) {
throw "First Name or Last Name is invalid.";
}
// Check the confirmation password is the same as the first password
if (sPassword != sCPassword) {
throw "The two passwords you've entered are different.";
}
if(duplicatedEmail()) {
throw "Sadly, your desired email is taken. If you have forgotten your password please, Click Here";
}
} catch(err) {
if (!error) {
$('body').prepend("<div class=\"error alert\">"+err+"</div>");
$('.signupInput.sPassword').val('');
$('.signupInput.sCPassword').val('');
setTimeout(function() {
$('.error.alert').fadeOut('1000', function() {$('.error.alert').remove();});
}, 2600);
}
event.preventDefault();
}
AJAX Function:
function duplicatedEmail() {
// Use AJAX function to do verification checks which can not be done via jQuery.
$.ajax({
type: "POST",
url: "/login/ajaxfunc/verifyReg.php",
dataType: "JSON",
async: false,
data: $('.signupForm').serialize(),
success: function(data) {
if (data.emailTaken == true) {
return true;
} else {
return false;
}
}
});
}
verifyReg.php
<?php
header('Content-Type: application/json', true);
$error = array();
require_once '../global.php';
$_POST['aquinas-email'] = "aq142647#aquinas.ac.uk";
// Check if an email already exists.
$checkEmails = $db->query("SELECT * FROM users WHERE aquinasEmail = '{$_POST['aquinas-email']}'");
if ($db->num($checkEmails) > 0) {
$error['emailTaken'] = true;
} else {
$error['emailTaken'] = false;
}
echo json_encode($error);
?>
to handle the error with jquery ajax function add error callback like this
function duplicatedEmail() {
// Use AJAX function to do verification checks which can not be done via jQuery.
$.ajax({
type: "POST",
url: "/login/ajaxfunc/verifyReg.php",
dataType: "JSON",
async: false,
data: $('.signupForm').serialize(),
success: function(data) {
if (data.emailTaken == true) {
return true;
} else {
return false;
}
},
error: function() {
//Your Error Message
console.log("error received from server");
}
});
}
to throw an exception in your PHP:
throw new Exception("Something bad happened");
Looking at your AJAX Function, and these two answers here and here, you need to make a small change to how you are returning the synchronous result:-
function duplicatedEmail() {
var result;
$.ajax({
type: "POST",
url: "/login/ajaxfunc/verifyReg.php",
dataType: "JSON",
async: false,
data: $('.signupForm').serialize(),
success: function(data) {
result = data.emailTaken;
}
});
return result;
}
use ajax error function..
function duplicatedEmail() {
// Use AJAX function to do verification checks which can not be done via jQuery.
$.ajax({
type: "POST",
url: "/login/ajaxfunc/verifyReg.php",
dataType: "JSON",
async: false,
data: $('.signupForm').serialize(),
success: function(data) {
if (data.emailTaken == true) {
return true;
} else {
return false;
}
},
error: function (result) {
alert("Error with AJAX callback"); //your message
}
});
}

Ajax success function not working in jquery mobile

I am trying to validate a basic login form with username and password fields. I need to validate username and password from check.php ajax page. There is no problem in ajax request and response. I am getting proper response from ajax page. But Ajax success function is not working properly.
ajaxrequest.html
$(document).on('pagebeforeshow', '#login', function(){
$(document).on('click', '#submit', function() {
if($('#username').val().length > 0 && $('#password').val().length > 0){
$.ajax({
url : 'serverurl/check.php',
data: {action : 'login', formData : $('#check-user').serialize()},
type: 'post',
beforeSend: function() {
$.mobile.loading(true);
alert("beforesend");
},
complete: function() {
$.mobile.loading(false);
alert("complete");
},
success: function (result) {
console.log("Ajax response");
res = JSON.stringify(result);
if(res.status == "success"){
resultObject.formSubmitionResult = res.uname;
localStorage["login_details"] = window.JSON.stringify(result);
$.mobile.changePage("#second");
}else{
$.mobile.changePage("#login");
alert("incorrect login");
}
},
error: function (request,error) {
alert('Network error has occurred please try again!');
}
});
} else {
alert('Fill all fields');
}
return false;
});
});
Here i have added my ajax page. This page only validates posted username and password. Finally it returns json object. What am i doing wrong?
serverurl/check.php
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
if(isset($_POST['formData']) && isset($_POST['action']) && $_POST['action'] == 'login'){
parse_str($_POST['formData'],$searchArray);
$uname = "arun";
$pwd = "welcome";
$resultArray = array();
if($uname == $searchArray['username'] && $pwd == $searchArray['password'])
{
$resultArray['uname'] = $searchArray['username'];
$resultArray['pwd'] = $searchArray['password'];
$resultArray['status'] = 'success';
}else{
$resultArray['status'] = 'failed';
}
echo json_encode($resultArray);
}
Your code should be
success: function (result) {
console.log("Ajax response");
//don't do this
//res = JSON.stringify(result);
if(result.status == "success"){
resultObject.formSubmitionResult = result.uname;
localStorage["login_details"] = window.JSON.stringify(result);
$.mobile.changePage("#second");
}else{
$.mobile.changePage("#login");
alert("incorrect login");
}
After JSON.stringify you are accessing like stringJson.status this will not work. it mast have "parsed" "json object" not stringify.
Don't need to convert your JSON to String.
$(document).on('pagebeforeshow', '#login', function(){
$(document).on('click', '#submit', function() {
if($('#username').val().length > 0 && $('#password').val().length > 0){
$.ajax({
url : 'serverurl/check.php',
data: {action : 'login', formData : $('#check-user').serialize()},
type: 'post',
beforeSend: function() {
$.mobile.loading(true);
alert("beforesend");
},
complete: function() {
$.mobile.loading(false);
alert("complete");
},
success: function (result) {
console.log("Ajax response");
//Don't need to converting JSON to String
//res = JSON.stringify(result);
//directly use result
if(result.status == "success"){
resultObject.formSubmitionResult = result.uname;
localStorage["login_details"] = window.JSON.stringify(result);
$.mobile.changePage("#second");
}else{
$.mobile.changePage("#login");
alert("incorrect login");
}
},
error: function (request,error) {
alert('Network error has occurred please try again!');
}
});
} else {
alert('Fill all fields');
}
return false;
});
});
Your AJAX call is perfect but datatype is not declared in ajax
Try with jSON OR JSONP. You will get success.
$.ajax({
url : 'serverurl/check.php',
type: 'post',
dataType: "json", OR "jsonp",
async: false,
data: {action : 'login', formData : $('#check-user').serialize()},
beforeSend: function() {
$.mobile.loading(true);
alert("beforesend");
},
complete: function() {
$.mobile.loading(false);
alert("complete");
},
success: function (result) {
console.log("Ajax response");
alert(JSON.stringify(result)); // Check response in alert then parse according to that
res = JSON.stringify(result);
if(res.status == "success"){
resultObject.formSubmitionResult = res.uname;
localStorage["login_details"] = window.JSON.stringify(result);
$.mobile.changePage("#second");
}else{
$.mobile.changePage("#login");
alert("incorrect login");
}
},
error: function (request,error) {
alert('Network error has occurred please try again!');
}
});
Under some circumstances your server might not return the response correctly. Have you tried to handle the actual response code (e.g. if your server returns 200) like this:
$.ajax({
url : 'serverurl/check.php',
data: {action : 'login', formData : $('#check-user').serialize()},
type: 'post',
....
statusCode: {
200: function (response) {
// do your stuff here
}
}
});

JSON ajax and jquery, cannot get to work?

I have the following script in my javascript...
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
data: {email: val},
success: function(response) {
alert(response);
}
});
And my php file looks like this...
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
}
else {
echo json_encode(error = true);
}
}
I cannot get either the variable error of true or false out of the ajax call?
Does it matter how I put the data into the ajax call?
At the minute it is as above, where email is the name of the request, and val is a javascript variable of user input in a form.
Try this instead. Your current code should give you a syntax error.
if (!$q -> rowCount()) {
echo json_encode(array('error' => false));
}
else {
echo json_encode(array( 'error' => true ))
}
In your code, the return parameter is json
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
dataType: 'json',
data: {email: val},
success: function(response) {
alert(response);
}
});
PHP FILES
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
return json_encode(error = false);
} else {
echo json_encode(error = true);
return json_encode(error = true);
}
}

Categories

Resources