Why I cannot keep call api if fail? - javascript

Below if my code...
$(document).ready(function() {
var counter=0;
$.ajax({
url: "http://www.test.com:1234/testService",
method: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: data
})
.done(function(data) {
console.log(data);
})
.fail(function(errMsg) {
console.log(errMsg);
counter++;
console.log(counter);
if(counter <=3){
$.ajax(this);
}
else {
alert("Three times failed");
}
});
});
Run this code will get correct data from API.
However, if I remove the "e" in the end of api url, the API will failed and what I want is to retry again until failed three times and alert some message.
But this code is not working.
What should I do?

What you can do is create a function that makes the ajax request and on failure invoke the function again.
$(document).ready(function () {
var counter = 0;
function apiCall() {
$.ajax({
url: "http://www.asiavista.com.tw:9595/ccplapi/service.svc/CheckService",
method: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ClientType: 1})
})
.done(function (data) {
console.log(data);
})
.fail(function (errMsg) {
console.log(errMsg);
counter++;
console.log(counter);
if (counter <= 3) {
apiCall(); // Try api call again
} else {
alert("Three times failed");
}
});
}
apiCall(); // Trigger the first api call
});

Related

Check(validate) send form data with ajax

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

Ajax. On Ajax success call same ajax function one more time

This is what i tried.
tjq.ajax({
type: 'POST',
url: '<?php echo base_url();?>getCmsHotel?t=<?php echo $traceId;?>',
dataType: 'JSON',
encoding:"UTF-8",
contentType: "application/json",
traditional: true,
async: true,
error: function (request, error) {
searchApiCount++;
hotelssearchObj.reloadFunctions(searchApiCount);
return false;
},
success: function (data) {
//alert(data.status);
if(data.status == 'FAILURE'){
//searchresults = data;
searchApiCount++;
hotelssearchObj.reloadFunctions(searchApiCount);
return false;
}else if(data.status == 'SUCCESS'){
var recalajx = '2';
if(recalajx =='2' && recalajx!=3){
recalajx ='3';
tjq.ajax(this);
}
alert(recalajx);
tjq('.searchresultsDiv').remove();
hotelsresults = data;
//hotelssearchObj.hotelsResults(data);
gblStartCount = 1;
gblHotelData = tjq.extend(true, {}, data);
gblHotelDisplayData = tjq.extend(true, {}, data);
hotelssearchObj.hotelsResults(gblHotelDisplayData);
searchApiCount++;
hotelssearchObj.reloadFunctions(searchApiCount);
tjq("div#divLoading").removeClass('show');
}
}
});
This code calling multiple times. Am trying to call tjq.ajax(this); only once after 1st ajax SUCCESS.
when tried to alert getting 3 but still axaj calling for multi times.
How to stop this can some help!
One solution is to put the Ajax call in a function, and check how many times it has been called with a counter. If the counter is less than 2, call the function again.
here's an example:
ajaxCall();
function ajaxCall(counter = 0) {
$.ajax({
type: 'POST',
success: function() {
counter++
if (counter < 2) {
ajaxCall(counter);
}
}
});
}

ajax jquery message show after the function completed

I think it is simple question. I've tried to search but still not found an answer yet.
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
success();
}
messageBox(result.d);
},
error: error
});
},
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
I want to show message after success() performed.
That means the comment left already then show message.
Thanks anyway!
P/s: I read a topic about jQuery Callback Functions at https://www.w3schools.com/jquery/jquery_callback.asp.
Can we use it in here? If we can, how to use?
You can try like this
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
success();
}
$.when(this).then(setTimeout(function(){ messageBox(result.d)}, 200));
// if you dont want use set timeout then use
// $.when(this).then(messageBox(result.d), 200));
},
error: error
});
},
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
Provides a way to execute callback functions based on zero or more Thenable objects, usually Deferred objects that represent asynchronous events.
Considering your implementation of var success = function() you may try with following approach:
Modify the success() to accept callback function as follows:
var success = function(callback) {
self.removeComment(commentId);
if(parentId)
self.reRenderCommentActionBar(parentId);
if(typeof callback == "function")
callback();
};
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
//passing the callback function to success function
success(function(){
messageBox(result.d);
});
}
},
error: error
});
},

How do keep calling API using jQuery ajax if failed until three times?

Below is my jQuery ajax sample code
$.ajax({
url: 'http://api.test.com',
method: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: data
})
.done(function(returnObj) {
return returnObj;
})
.fail(function(err) {
console.log(err);
});
If failed, I will console log the error message, but how do I keep calling until three times failed and stop calling again and alert some message?
Leveraging promises, you could just do it this way. Might not be particularly elegant, but it works quite well and is very readable:
var func = function() {
return $.ajax(...);
};
func() //call 1
.then(null,function() { return func(); }) //call 2
.then(null,function() { return func(); }) //call 3
.then(null,function() { console.log('3 times'); })
EDIT:
If you are using jQuery less than 1.8, you'll have to change .then to .pipe
var repeat = function(request,times) {
var r = request();
while( times > 0) {
r = r.then(null,function() { return request(); })
times--;
}
return r;
}
repeat($.ajax.bind(null,{url:'https://www.google.com'}),10)
.then(
function() {
console.log('success!');
},
function() {
console.log('failed 10 times');
}
);
try this, (using recursion)
var counter = 1;
var ajaxFunc = function(){
$.ajax({
url: 'http://api.test.com',
method: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: data
})
.done(function(returnObj) {
return returnObj;
})
.fail(function(err) {
console.log(err);
counter++;
if(counter<=3) ajaxFunc();
});
}
ajaxFunc(); // first call
$.ajax({
url: 'http://api.test.com',
method: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: data
tryCount : 1,
retryLimit : 3,
error: function(xhr, textStatus, err){
if (this.tryCount <= this.retryLimit) {
console.log("error")
this.tryCount++;
$.ajax(this);
} else {
console.log("max number ...");
}
}
})
.done(function(returnObj) {
return returnObj;
})
.fail(function(err) {
console.log(err);
});

Call ajax.fail() from ajax.success()

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 :)

Categories

Resources