I have the following Ajax request which I make. Currently if the json response is true then the success callback runs. But if the json response is false then the success callback isn't run, even if the Ajax request itself is successfully made.
$.ajax({
url: "http://testdomain.com/wp-admin/admin-ajax.php",
type: "POST",
dataType: "json",
cache: false,
data: {
action: 'check_username',
user: user_email
},
success: function(json) {
if (json.user_exists == true) {
$.ajax({
url: "http://testdomain.com/wp-admin/admin-ajax.php",
type: "POST",
dataType: "json",
cache: false,
data: {
action: 'auto_login',
user: user_email
},
success: function(json) {
$('#aux_lightbox_overlay').fadeOut();
}
});
}
if (json.user_exists == false) {
$.ajax({
url: "http://testdomain.com/wp-admin/admin-ajax.php",
type: "POST",
dataType: "json",
cache: false,
data: {
action: 'auto_register',
user: user_email
},
success: function(json) {
$('#aux_lightbox_overlay').fadeOut();
}
});
}
}
});
So my question is, how do I get the callback to run even if the response is false?
Thanks
Maybe you need to use complete instead success and error.
$.ajax({
url: "http://testdomain.com/wp-admin/admin-ajax.php",
type: "POST",
dataType: "json",
cache: false,
data: {
action: 'check_username',
user: user_email
},
complete: function(json) {
if (json.user_exists == true) {
$.ajax({
url: "http://testdomain.com/wp-admin/admin-ajax.php",
type: "POST",
dataType: "json",
cache: false,
data: {
action: 'auto_login',
user: user_email
},
success: function(json) {
$('#aux_lightbox_overlay').fadeOut();
}
});
}
if (json.user_exists == false) {
$.ajax({
url: "http://testdomain.com/wp-admin/admin-ajax.php",
type: "POST",
dataType: "json",
cache: false,
data: {
action: 'auto_register',
user: user_email
},
success: function(json) {
$('#aux_lightbox_overlay').fadeOut();
}
});
}
}
});
Are you sure that when the user does not exist, json.user_exists is indeed equal to false? If I understand you correctly, the if (json.user_exists == false){...} statement is not triggered, so there is something weird there.
For more robust code, you could change
if (json.user_exists == true) {
// ...
}
if (json.user_exists == false){
// ...
}
into
if (json.user_exists == true) {
// ...
}
else {
// ...
}
Related
$.ajax({
url: '/inventories/'+inventoryJavaScriptData.id,
type: 'PATCH',
data: data,
contentType: false,
cache: false,
processData: false,
success: (response) => {
console.log(response);
if (response.status == 'true') {
}else{
}
},
error: (errorResponse)=>{
$.notify('error! please try again' , 'error' );
}
})
I,m try check(validate) form data by using AJAX.
First i create callback function with AJAX request(in my example it's field time)
When i found same record in database, my NodeJS server response with value false, it's means we have record and we don't need add second record with that time).
My problem is that the form is still sent, regardless of the server response.
here my code(front end)
function funABC(mdata,callback){
console.log(mdata);
$.ajax({
url:'/dashboard/materials/checkshowrange',
method: 'GET',
dataType: "json",
contentType: "application/json",
data:mdata,
success: callback ,
// error:callback,
});
}
$('.addForm').on('submit', function (event) {
let form = $('.addForm');
if (form[0].checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
// return false;
}
event.preventDefault();
checkdata = {
time_show : document.querySelector('.addForm').elements.time_show.value
}
functABC(checkdata,function(result) {
console.log(result);
if (result == 'true') {
alert(`For time: ${checkdata. time_show} there is already an event, choose a different time`);
return false;
}
})
form.addClass('was-validated');
some operations with form data, then send with ajax
$.ajax({
type: "POST",
url: "/dashboard/materials/add",
dataType: "json",
contentType: "application/json",
success: function (data) {
setTimeout(location.href = '/dashboard/materials', 10000);
},
data: JSON.stringify(formdata)
});
});
How and where did you call that post request ?
May be you would need to move post request into the callback
function funABC(mdata, callback) {
console.log(mdata);
$.ajax({
url: '/dashboard/materials/checkshowrange',
method: 'GET',
dataType: "json",
contentType: "application/json",
data: mdata,
success: callback,
// error:callback,
});
}
$('.addForm').on('submit', function(event) {
let form = $('.addForm');
if (form[0].checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
// return false;
}
event.preventDefault();
checkdata = {
time_show: document.querySelector('.addForm').elements.time_show.value
}
functABC(checkdata, function(result) {
console.log(result);
if (result == 'true') {
alert(`For time: ${checkdata. time_show} there is already an event, choose a different time`);
return false;
} else {
$.ajax({
type: "POST",
url: "/dashboard/materials/add",
dataType: "json",
contentType: "application/json",
success: function(data) {
setTimeout(location.href = '/dashboard/materials', 10000);
},
data: JSON.stringify(formdata)
});
}
})
form.addClass('was-validated');
});
Or you could async false for validation request
$.ajax({
url: '/dashboard/materials/checkshowrange',
method: 'GET',
dataType: "json",
contentType: "application/json",
data: mdata,
success: callback,
async: false,
// error:callback,
});
Here is the partial code from the remove PHP file:
if($action == 'trackings_get') {
$result = $trackings->get(getCourierSlugByID($GLOBALS['tracking_id']), $GLOBALS['tracking_id']);
$result_history = $result['data']['tracking']['checkpoints'];
echo json_encode($result_history);
// debugging
//pretty_print($result_history);
}
Here is the JS from the remote site i am trying to call the data for:
$.ajax({
url: '/login/tracking.php',
type: 'POST',
dataType: "json",
data: {
action: action,
tracking_id: tracking_id
},
success: function(json){
//debug
alert(JSON.stringify(json));
}
});
try this
function test(){
$.ajax({
url: 'url',
type: 'POST',
dataType: "json",
data: {
action: action,
tracking_id: tracking_id
},
success: function(json){
}
});
}
i try this code in inspect element in this page https://tracking.ambientlounge.com/
function test(){
$.ajax({
url: 'your url',
type: 'POST',
dataType: "json",
data: {
action: "action",
tracking_id: "tracking_id"
},
success: function(json){
//debug
console.log(json);
}
});
}
result is array . dont need JSON.stringify .
So all I want to do is conditionally call the .fail method from within the .success method, how?
var ajaxCall = $.ajax({
url: pUrl,
type: "POST",
data: pData,
dataType: "json",
processData: false,
contentType: "application/json; charset=utf-8"
})
.always(function () {
alert("always");
})
.success(function (data) {
if (data == "fail") { ajaxCall.fail(); return; }
alert("success");
})
.fail(function () {
alert("fail");
});
$.ajax return a promise so you can't do it directly. Your best shot is that :
var fail = function () {
alert("fail");
};
var ajaxCall = $.ajax({
url: pUrl,
type: "POST",
data: pData,
dataType: "json",
processData: false,
contentType: "application/json; charset=utf-8"
})
.always(function () {
alert("always");
})
.success(function (data) {
if (data == "fail") { fail(); return; }
alert("success");
})
.fail(fail);
You can simply call as this.fail(); as shown below :-
var ajaxCall = $.ajax({
url: pUrl,
type: "POST",
data: pData,
dataType: "json",
processData: false,
contentType: "application/json; charset=utf-8"
})
.always(function () {
alert("always");
})
.success(function (data) {
if (data == "fail")
{
this.fail();
return;
}
alert("success");
})
.fail(function () {
alert("fail");
});
For more information :-
http://www.youlikeprogramming.com/2013/07/jqueryajax-conditionally-call-error-method-fro-success/
just use the "this" keyword to actually call any other method of the ajax call, I have made a sample for error method.
$.ajax({
url: 'url',
dataType: 'json',
contentType: 'application/json; charset=utf-8;',
type: 'GET',
success: function (dataReturn) {
this.error('error called explicitly');
},
error: function (errorMessage) {
if(errorMessage.ResponseText) // or directly compare as errorMessage !== "error called explicitly" if u send the same message elsewhere
//actual error code
else
alert(errorMessage);
}
});
hope this helps :)
I'm putting an ajax call inside an ajax call, but in the second, the element is not being recognized, example:
$.ajax({
url: 'controleFatAcoes.php',
type: 'post',
dataType: 'html',
data: {
acao: 'validaenviofat',
id_cliente: cli.id_cliente,
dt_fat: cli.id_fat
},
success: function(data) {
$.ajax({
url: 'controleFatAcoes.php',
data: {id_cliente: cli.id_cliente,
id_fat: cli.id_fat, acao: 'getdadosnf'},
type: 'post',
dataType: 'json',
success: function(dados) {
**$('#templateEmpresa').html(dados.empresa);**
}
)};
});
When I run a console.log($('#templateEmpresa')), I get:
[context: document, selector: "#templateEmpresa", constructor: function, init: function, selector: ""…]
Try this code out:
Might be a problem of scope given that you are executing the second ajax call inside the success function of the first ajax call.
var firstajaxsuccess = 0;
$.ajax({
url: 'controleFatAcoes.php',
type: 'post',
dataType: 'html',
data: {
acao: 'validaenviofat',
id_cliente: cli.id_cliente,
dt_fat: cli.id_fat
},
success: function(data) {
firstajaxsuccess = 1;
}
});
if(firstajaxsuccess){
$.ajax({
url: 'controleFatAcoes.php',
data: {id_cliente: cli.id_cliente,
id_fat: cli.id_fat, acao: 'getdadosnf'},
type: 'post',
dataType: 'json',
success: function(dados) {
**$('#templateEmpresa').html(dados.empresa);**
}
)};
}