jquery ajax - how to use response in success - javascript

page.php
$sqlQuery = "";
$result = $mysqli->query($sqlQuery);
if (mysqli_affected_rows($mysqli) > 0) {
echo "success";
} else {
echo "error";
}
I want to use response text in success but with if condition is not working.
How can i use with if.
Thanks for your help.
$.ajax({
metod: "POST",
url: "page.php",
data: {data},
success: function (response) {
console.log(response); // It is working
notification("success"); // It is working
// response text is succes or error
if (response == 'success') {
btnLabel.html("DONE"); // It is not working
} else if (response == 'error') {
btnLabel.html("ERROR"); // It is not working
}
},
error: function (err) {
notification("error"); // It is working
}
});

Related

AJAX Success function if there is no returned JSON data

I know this is simple but I am struggling to get this right. I am using jQuery/AJAX to retrieve some data (JSON) from my database. I then have a success function to display the data. This works fine but I want to have alert the user if there are no returned results.
My PHP excerpt which encodes the JSON:
...
while($row = $result->fetch_all())
{
$returnResult = $row;
}
echo json_encode(['result' => $returnResult, 'errors' => $errors]);
....
My JSON data format looks like this:
{"result":[["Grade 12","Studies","John","Doe"]],"errors":false}
My jQuery that then uses the JSON data and displays in html elements:
function getworkload(){
$.ajax({
type: "POST",
url: "modules/getworkload.php",
dataType: 'json',
data: {id:id},
cache: false,
})
.success(function(response) {
if(!response.errors && response.result) {
$.each(response.result, function( index, value) {
$("#divwork").append('<li class="list-group-item"><b>'+value[0]+'</b> : '+value[1]+'</li>');
$("#spnname").html('<b>'+value[2]+' '+value[3]+' Workload </b>');
});
} else {
$.each(response.errors, function( index, value) {
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
}
I have tried to replace if(!response.errors && response.result) { with the following:
if(!response.errors && response.result=null) {
if(!response.errors && !response.result) {
if(!response.errors && response.result.length < 1) {
Instead of passing errors false in your JSON, throw an HTTP error code like 404 or 500. Then, you can put an error section in your javascript instead of checking in the success section.
Assuming the returned JSON is as follow,
{"result":[["Grade 12","Studies","John","Doe"]],"errors":false}
You just have to put one condition to check if the result length is 0 or not.
Like this,
if(!response.errors && response.result) {
$.each(response.result, function( index, value) {
$("#divwork").append('<li class="list-group-item"><b>'+value[0]+'</b> : '+value[1]+'</li>');
$("#spnname").html('<b>'+value[2]+' '+value[3]+' Workload </b>');
});
} else if(!response.errors && response.result && response.result.length==0) {
// Handle 0 result output here...
} else {
$.each(response.errors, function( index, value) {
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
In your PHP script change your echo json_encode... to
echo json_encode(['result' => (count($returnResult)) ? $returnResult : 0, ...]);
Then in your JS simply do
if(!response.errors && !!response.result) {...
Let the server return the word 'nothing' for example in case of no result and split the code to three cases if result and if error and if nothing
if(isset($returnResult) && $returnResult!=null){
echo json_encode('result' => $returnResult);
}
else if (isset($errors) && $errors!=null){
echo json_encode('errors'=>$errors);
}
else { echo "nothing";}
Check that response is not nothing on success function
.success(function(response) {
if(response=='nothing'){
alert('nothing');
}
else {
//rest of the success function
}
Another suggestion is to use this if statement with in success function
.success(function(response) {
if(!response.result && !response.errors){
alert('nothing');
}
else {
//rest of the success function
}
Or
.success(function(response) {
if(response.result==null && response.errors==null){
alert('nothing');
}
else {
//rest of the success function
}
your code is not correctly parsing json value from php file to javascript and you have to parse json before using in javascript
function getworkload(){
$.ajax({
type: "POST",
url: "modules/getworkload.php",
dataType: 'json',
data: {id:id},
cache: false,
})
.success(function(response) {
console.log(response);
var res = JSON.parse(response);
console.log(res);/* console json val*/
if(!res.errors && res .result) {
$.each(res.result, function( index, value) {
$("#divwork").append('<li class="list-group-item"><b>'+value[0]+'</b> : '+value[1]+'</li>');
$("#spnname").html('<b>'+value[2]+' '+value[3]+' Workload </b>');
});
} else {
$.each(res.errors, function( index, value) {
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
}
Just use JSON.parse(responce) in success() at firstline and then use it.

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

Delete a file with ajax request

I'm trying to delete a file with ajax request:
javascript:
function deleteFile(file_path)
{
var r = confirm("Sure?")
if(r == true)
{
$.ajax({
url: 'delete_file.php',
data: {'file' : file_path },
method: 'GET',
success: function (response) {
alert('Deleted!');
},
error: function () {
alert('Not Deleted!');
}
});
}
}
delete_file.php :
unlink($_GET['file']);
It returns true on succes,but the file is not deleted.
Check the response in AJAX, Best is use JSON DATA to check the response:
// Default AJAX request type is GET so no need to define
$.ajax({
url: 'delete_file.php',
data: {'file' : file_path },
dataType: 'json',
success: function (response) {
if( response.status === true ) {
alert('File Deleted!');
}
else alert('Something Went Wrong!');
}
});
Do It like this in PHP:
// First Check if file exists
$response = array('status'=>false);
if( file_exists('FILE_PATH/FILENAME') ) {
unlink('FILE_PATH/FILENAME');
$response['status'] = true;
}
// Send JSON Data to AJAX Request
echo json_encode($response);
Make sure you are giving the complete path with filename to unlink() function
Try this you need to check file, give permission, then delete it
$filename = 'full absolute file path';
if(file_exists($filename)) {
#chmod($filename, 0777);
#unlink($filename);
return true;
}
As there can be two issues either the file path is not correct or the file is not having permission.
With the above code both will be checked.

Check returned data from ajax/php

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

Categories

Resources