Repeat jQuery ajax request - javascript

I make an ajax request to the server. And sometimes I receive 502 error. So, if that happened error() method is called.
How can I repeat request if receive an error? The code should looks like this:
$.ajax({
url: 'http://server/test.php',
type: 'GET',
dataType: 'jsonp',
cache: 'false',
timeout: 32000,
success: function(data) {
//some actions here
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error[refresh]: " + textStatus);
console.log(jqXHR);
// here I want to repeat the request like "this.repeat()"
},
});

you can do it like this,
function ajaxCall(){
$.ajax({
url: 'http://server/test.php',
type: 'GET',
dataType: 'jsonp',
cache: 'false',
timeout: 32000,
success: function(data) {
//some actions here
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error[refresh]: " + textStatus);
console.log(jqXHR);
ajaxCall(); // recursion call to method.
},
});
}

Put your code in function and call this function again. like:
function ajaxFunction()
{
....
error:function(){ajaxFunction();}
}

With calling limit, as suggested by Hadas:
function ajaxCall(count) {
count = typeof count == 'undefined' ? 0 : count;
limit = 5;
if(count === limit) return;
// no need to specify cache and type:
// type has 'GET' as default value
// cache has default value of false if the dataType is jsonp
$.ajax({
url: 'http://server/test.php',
dataType: 'jsonp',
timeout: 32000,
async: false
}).done(function(data) {
// some actions here
}).fail(function(jqXHR, textStatus, errorThrown) {
count += 1;
console.log("Error[refresh]: " + textStatus);
console.log(jqXHR);
// 500, 1000, 1500, 2000 etc
setTimeout(function() {
ajaxCall(count);
}, 500*count);
});
};

Related

Firebase Dynamic Link Creation With JavaScript

var object={
"longDynamicLink": "https://[APP_NAME].page.link/?link=[LINK_HERE]",
"suffix":{
"option":"SHORT"
}
}
$.ajax({
url: 'https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=[KEY_HERE]',
type: 'POST',
dataType: "json",
data: object,
success: function(response, textStatus, jqXHR) {
alert(response.shortLink);
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
The above code works if the "suffix" is deleted from the request. That makes an "UNGUESSABLE" url, but I want a short URL. As stated in the documentation at https://firebase.google.com/docs/dynamic-links/rest?authuser=0 I added the suffix option parameter, but it results with a 400 response. Any ideas why?
I haven't ever tried this but, ...
POST https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=api_key
var params = {
"longDynamicLink": "https://example.page.link/?link=http://www.example.com/&apn=com.example.android&ibi=com.example.ios",
"suffix": {
"option": "SHORT"
}
}
$.ajax({
url: 'https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=[KEY_HERE]',
type: 'POST',
data: jQuery.param(params) ,
contentType: "application/json",
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});

Ajax call not working for every controller

I am using mvc 4 ,I need to call controller actions using ajax.So I created a new scripts.js file at Scripts folder.In my project there are lot of controllers and I wrote ajax functions for each of them in the same js file.But except the default controller other controllers are not initiated by the ajax code. Scripts.js file contains:
$(document).ready(function () {
//END COUNTRY ................................................................
$("#savecountry").click(function () {
//var car = { id: 4, name: "India" }
$.ajax({
type: "POST",
url: '/Country/SaveCountry',
data: {name: $('#country').val() },
dataType: 'json', encode: true,
async: false,
cache: false,
//contentType: 'application/json; charset=utf-8',
success: function (data, status, jqXHR) {
// alert("success");
console.log(jqXHR);
console.log(status);
console.log(data);
//$.each(data, function (index, customer) {
// alert(customer.Name + " " + customer.UserName);
//});
},
error: function (jqXHR, textStatus, errorThrown) {
//console.log(jqXHR);
//console.log(textStatus);
//console.log(errorThrown);
if (typeof (console) != 'undefined') {
alert("oooppss");
}
else { alert("something went wrong"); }
}
});
});
$("#updatecountry").click(function () {
//var car = { id: 4, name: "India" }
$.ajax({
type: "POST",
url: '/Country/Update',
data: { id:$('#id').val(), name:$('#country').val() },
dataType: 'json', encode : true,
async: false,
cache: false,
success: function (data, status, jqXHR) {
alert("success");
//$.each(data, function (index, customer) {
// alert(customer.Name + " " + customer.UserName);
//});
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
if (typeof (console) != 'undefined') {
alert("oooppss");
}
else { alert("something went wrong"); }
}
});
});
$('#cancel').click(function () {
$('input:text').val('');
});
//$('.deleteRow').click(function () {
// alert('ewewrwr');
// $.ajax({
// type: "POST",
// data: { id: $('#id').val() },
// url: "/Country/DeleteCountry",
// dataType: 'json', encode: true,
// async: false,
// cache: false,
// success: function (data, status, jqXHR) {
// alert("success");
// //$.each(data, function (index, customer) {
// // alert(customer.Name + " " + customer.UserName);
// //});
// },
// error: function (jqXHR, textStatus, errorThrown) {
// console.log(jqXHR);
// if (typeof (console) != 'undefined') {
// alert("oooppss");
// }
// else { alert("something went wrong"); }
// }
// });
//});
$("#updateoffer").click(function () {
//var car = { id: 4, name: "India" }
$.ajax({
type: "POST",
url: '/Offer/Update',
// contentType: "application/json; charset=utf-8",
data: { id: $('#id').val(), name: $('#offer').val(), description: $('#description') },
dataType: 'json', encode: true,
async: false,
cache: false,
success: function (data, status, jqXHR) {
alert("success");
//$.each(data, function (index, customer) {
// alert(customer.Name + " " + customer.UserName);
//});
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
if (typeof (console) != 'undefined') {
alert("oooppss");
}
else { alert("something went wrong"); }
}
});
});
});
Here Country is the default controller and ajax call working well.But call to Offer controller Update ajax not working .Page not responding error will result.
You should take project name to baseUrl for call ajax function.
$(document).ready(function(){
var baseurl = "";//your project name
$("#savecountry").click(function () {
$.ajax({
type: "POST",
url: baseurl+'/Country/SaveCountry', // baserurl+"/controller name/action"
.....
}
The accepted answer has a serious flaw in commercial deployments, so offering alternatives.
Yes, you need the base address of the website, but you do not want to hard-wire it into the code.
Option 1
You can inject a global javascript variable into your master page as a string constant.
e.g. put this at the top of your master page
<script>
window.baseurl = "#Url.Content("~/")";
</script>
then just use window.baseurl prepended to your URLs
e.g
$("#savecountry").click(function () {
$.ajax({
type: "POST",
url: window.baseurl+'/Country/SaveCountry',
Option 2
You can inject a data- attribute into the DOM in your master page. e.g. on the body tag
then extract it using jQuery:
e.g.
var baseurl = $('body').data('baseurl');
$("#savecountry").click(function () {
$.ajax({
type: "POST",
url: baseurl+'/Country/SaveCountry',
Option 3 (I do not advise this one)
Inject the string literal into your Javascript
$("#savecountry").click(function () {
$.ajax({
type: "POST",
url: "#Url.Action("SaveCountry", "Country")",
This is bad for maintenance and debugging as the code must be in a Razor view in order to work.
We used to use option 2 a lot, but now tend to use option 1.

ajax not called..even alerts are not working

i am writing this code in my html page to hide one id in that page..alerts are also not working..method is not called
*<script>
alert("yo");
$(function checkUsertype(email_id)
{
alert("yup")
var usertype = $("#txtusertype").val();
$.ajax({
alert("hide")
url: 'rest/search/userType?email_id='+email_id,
type : "GET",
datatype : 'json',
cache : false,
success : function(data)
{
if(usertype=='webuser')
{
$("#themer").hide();
}
},
error : function(xhr, data, statusText,errorThrown)
{
}
});
})
alert("yo");
<script/>*
This is the problem.
$.ajax({
alert("hide")
You're trying to alert inside the ajax which is Syntax error. Try removing the alert inside ajax and it should work.
You can use alert in success, error callbacks as follow:
$(function checkUsertype(email_id) {
var usertype = $("#txtusertype").val();
$.ajax({
url: 'rest/search/userType?email_id=' + email_id,
type: "GET",
datatype: 'json',
cache: false,
success: function(data) {
alert('In Success'); // Use it here
console.log(data); // Log the response
if (usertype == 'webuser') {
$("#themer").hide();
}
},
error: function(xhr, data, statusText, errorThrown) {
alert('In Error'); // Use it here
console.log(errorThrown); // Log the error
}
});
});

AJAX Get status was Ok but jsonp callback returns undefined data

I am sending an ajax request to retrieve data from salesforce using jsonp but jsonp callback data returns undefined
My ajax request is,
$j.ajax({
type: "POST",
async: this.asyncAjax,
url: "https://na14.salesforce.com/services/data/v26.0/
sobjects/customobject?callback=mycallback",
contentType: 'application/json',
cache: false,
processData: false,
data: payload,
jsonp: false,
jsonpCallback: function(data, textStatus, jqXHR){
alert('Data is '+data);
alert('Text status is '+textStatus);
alert('jqXHR is '+jqXHR);
},
error: (!this.refreshToken || retry ) ? error : function(jqXHR, textStatus, errorThrown) {
if (jqXHR.status === 401) {
that.refreshAccessToken(function(oauthResponse) {
that.setSessionToken(oauthResponse.access_token, null,
oauthResponse.instance_url);
that.ajax(path, callback, error, method, payload, true);
},
error);
} else {
error(jqXHR, textStatus, errorThrown);
}
},
dataType: "jsonp",
beforeSend: function(xhr) {
if (that.proxyUrl !== null) {
xhr.setRequestHeader('SalesforceProxy-Endpoint', url);
}
xhr.setRequestHeader(that.authzHeader, "OAuth " + that.sessionId);
xhr.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + that.apiVersion);
if (that.userAgentString !== null) {
xhr.setRequestHeader('User-Agent',that.userAgentString);
}
}
});
But, i got my response is,
Data is undefined.
Text status is undefined.
jqXhr is undefined.
How do i solve this? Is that ajax request in the right format?
Thanks
You are manually setting the name of the callback parameter sent to the URL, but there is no function called mycallback.
You are setting jsonpCallback to a function. jQuery will take the return value of that function and send it as the callback parameter (if you let it send that parameter).
The correct way to do JSONP is:
$j.ajax({
type: "POST",
async: this.asyncAjax,
url: "https://na14.salesforce.com/services/data/v26.0/sobjects/customobject",
contentType: 'application/json',
cache: false,
processData: false,
data: payload,
dataType: 'jsonp',
success: function(data, textStatus, jqXHR){
alert('Data is '+data);
alert('Text status is '+textStatus);
alert('jqXHR is '+jqXHR);
},

function calling ajax returns false

I have a javascript function which makes a JSON call to a web service using jQuery.
In the success function I need to evaluate the JSON response and if necessary make another call to a different method in the same web service.
Here is how I do it:
function firstAjaxCall(aid, tid) {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method1",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (response) {
var respData = response.d;
//do some stuff
if (respData.HasEnded == true) {
clearInterval(tid);
var end = false;
end = endFunction(aid);
if (end) {
// do some other stuff
}
}
},
failure: function (errorMsg) { alert(errorMsg.toString()); }
});
}
and the endFunction which is being called from within the ajax success function:
function endFunction(aid) {
var hasEnded = false;
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method2",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (callbackData) {
var endRespData = callbackData.d;
hasEnded = endRespData.Success;
alert(hasEnded.toString());
},
failure: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
return hasEnded;
}
Here is the weird stuff. The ajax-call is made all right. The code on the server is running according to plan. However, if I try to set a firebug breakpoint in the success function of endFunction(aid) is is not hit, but the alert box is shown displaying the word true. This is somewhat good since it seems that we are actually reaching the success function. The hasEnded variable however is never set to true so it always returns false.
Calling endFunction(1) from the Firebug console displays an alert box with the word true and returns value false.
What's going wrong?
AJAX is asynchronous — the $.ajax call will not wait for the server to reply.
Therefore, the return hasEnded; line runs before the AJAX callback.
You need to make your endFunction take a callback parameter, like $.ajax does.
http://api.jquery.com/jQuery.ajax/
It looks like you're using "failure" in the documentation you have "error":
error(XMLHttpRequest, textStatus, errorThrown)
also you should do something like this:
function firstAjaxCall(aid, tid) {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method1",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (response) {
var respData = response.d;
//do some stuff
if (respData.HasEnded == true) {
clearInterval(tid);
var end = false;
endFunction(aid,function(endv){
if (endv) {
// do some other stuff
}
});
}
},
error: function (errorMsg) { alert(errorMsg.toString()); }
});
}
function endFunction(aid,endcallback) {
var hasEnded = false;
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method2",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (callbackData) {
var endRespData = callbackData.d;
hasEnded = endRespData.Success;
alert(hasEnded.toString());
endcallback(hasEnded);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
endcallback("?");
}
});
//return hasEnded;
}

Categories

Resources