For an ajax query, is there any time constraint for server to respond? if yes how can i set this time? this should be happen in javascript , front end , where if a problem happen and server does not respond an error is occurred . In my code , By this URL , a function execute and some operations are done . Surly these operations have no problem but take a long time , and message "error is occurred" is shown .
`
$(document).ready(function(){
$.ajax({
url : "/ajaxUpdateOrInsertReportResult",
type : "GET"',
data : "projectId="'+projectId,
success: successFn,
error : function(xml, error) {
alert(error is occurred);
}
});
});
function successFn(result){
alert("update done successfully")
}
`
Please read the $.ajax doc Here is the details.
$.ajax({
url: "your/url",
error: function(){
// will fire when timeout is reached
},
success: function(){
//do something
},
timeout: 3000 // sets timeout to 3 seconds
});
Also You can use
$.ajax({
url: '/getData',
timeout:3000 //3 second timeout
}).done(function(){
//do something
});
Related
I have the following Ajax but it needs to handle a 422 error being returned (which means Out of Stock). I've tried a few ways around but it error's and refuses to POST stating:
Failed to load resource: the server responded with a status of 422 ()
I'm unsure how to catch the 422 error and return something to the user displaying that it's out of stock.
Shopify.moveAlong = function() {
// If we still have requests in the queue, let's process the next one.
if (Shopify.queue.length) {
var request = Shopify.queue.shift();
var data = 'id='+ request.variant_id + '&quantity='+request.quantity_id;
$.ajax({
type: 'POST',
url: '/cart/add.js',
dataType: 'json',
data: data,
success: function(res){
Shopify.moveAlong();
},
error: function(){
// if it's not last one Move Along else update the cart number with the current quantity
if (Shopify.queue.length){
Shopify.moveAlong()
}
}
});
}
else {
window.location.href = "/cart";
}
};
Shopify.moveAlong();
I've tried a few ways around but it error's and refuses to POST.
What I have understood is, you are seeing this error in Browser console. It cannot be prevented, but it does not mean that you request is not going through. The POST request is recieved by Shopify and a response with status 422 is sent, so that is treated as an error (Non 2xx response codes are treated as error).
To handle the error and display error message, adapt the code accordingly. Check updated code and code comments.
Shopify.moveAlong = function() {
// If we still have requests in the queue, let's process the next one.
if (Shopify.queue.length) {
var request = Shopify.queue.shift();
var data = 'id=' + request.variant_id + '&quantity=' + request.quantity_id;
$.ajax({
type: 'POST',
url: '/cart/add.js',
dataType: 'json',
data: data,
success: function(res) {
Shopify.moveAlong();
},
error: function(jqXHR, textStatus, errorThrown) {
// Check status code
if (jqXHR.status === 422) {
// display error wherever you want to
console.log(jqXHR.responseText);
}
// if it's not last one Move Along else update the cart number with the current quantity
if (Shopify.queue.length) {
Shopify.moveAlong()
}
}
});
} else {
window.location.href = "/cart";
}
};
Shopify.moveAlong();
AJAX Error Docs
I'm trying to grab some data from the database on a page in typo3 using Ajax . So after a long time looking for the appropriate way to do it , I got convinced that The Ajax Dispatcher is the best tool to do the job . So I created the file following the instructions to be found here.
Now when I make an Ajax call on my page , the console displays a 500 (Internal Server Error).
joined is a snapshot of my console tab.
and this is the jquery function that gets run on an onchange event .
function getContent(id) {
console.log("Start process ...");
$.ajax({
async: 'true',
url: 'index.php',
type: 'POST',
data: {
eID: "ajaxDispatcher",
request: {
pluginName: 'listapp',
controller: 'Pays',
action: 'getMyCos',
arguments: {
'id': id,
}
}
},
dataType: "json",
success: function(result) {
console.log(result);
},
error: function(error) {
console.log(error);
}
});
}
Could someone please help me , I just started developing with this CMS of shit :p
I just had to change the file AjaxDispatcher :
line 101 to: \TYPO3\CMS\Core\Core\Bootstrap::getInstance();
It seems like I've tried everything and I finally just switched to using the CORS npm module:
var cors = require('cors');
And my one route I want to use CORS on:
app.post('/hangouts', cors(), hangoutsController.hangouts); // user CORS
I'm implementing a custom app in Google Hangouts, but need to post to my server, and the Hangout is run from a Google server. I put the AJAX call on a loop so that it will keep trying - this post going through is crucial to my app.
Here's the relevant AJAX call in the Hangout app:
var shouldpostHangoutId = true;
/* Post the Hangout ID to server */
var postHangoutId = function(hangoutId) {
var startData = gapi.hangout.getStartData();
$.ajax({
type: 'POST',
url: rootURL + "/hangouts",
crossDomain: true,
dataType: "json",
data: {
"hangouts_id" : hangoutId,
"start_data" : startData
},
success: function( response ) {
console.log( "postHangoutId -- success" ); // server response
console.log( response ); // server response
shouldpostHangoutId = false;
},
error: function(xhr, textStatus, error){
console.log( "postHangoutId -- error" ); // server response
console.log(xhr.statusText);
console.log(textStatus);
console.log("error = " + error);
// Try again
if (shouldpostHangoutId) {
postHangoutId(hangoutId); // Try again
};
}
});
};
What's driving me crazy is that sometimes it goes through on the first go, sometimes it takes 5 times. And the whole process is super slow. Here's the log I get when it doesn't come through:
XMLHttpRequest cannot load https://www.foo.bar/hangouts. No 'Access-Control-Allow-Origin' header
is present on the requested resource. Origin 'https://ts6d5n5om59gt6cin9c39faccjf890k5-a-hangout-
opensocial.googleusercontent.com' is therefore not allowed access.
I'm using Node + Express ~4 on Heroku.
I think the problem had something to do with pre-flight requests. I changed the AJAX call to the following:
$.ajax({
type: 'POST',
url: rootURL + "/hangouts",
dataType: "json",
data: {
"hangouts_id" : hangoutId,
"start_data" : startData
},
error: function( error ){
// Log any error.
console.log( "ERROR:", error );
// Try again
if (shouldpostHangoutId) {
postHangoutId(hangoutId); // Try again
};
},
complete: function(){
console.log( "postHangoutId -- success" ); // server response
shouldpostHangoutId = false;
}
});
And it goes right through, first time without delay.
I am getting data from php file through ajax. Based on the data I need to do some processing. I have put a few alerts in my code, and from that I realize that the code outside the ajax is being executed before ajax gets the data. I want the code to be done after the data is received from php file.
Code:
$(function () {
var originalData="";
$.ajax({
url: 'data.php',
data: "",
dataType: 'text',
success: function(data)
{
originalData=data;
alert("originalData 1 "+ originalData);
}
});
alert("originalData 2 "+ originalData);
...
Processing code
...
});
The sequence of alerts is:
First : "originalData 2"
Second : "originalData 1"
One option is that I include the Processing code inside the success function, but I cannot do it because later I want to put a logic such that I can have a buffer of data (atleast 4-5 stack deep) because I want user to get new data instantly after processing code for current data, rather than wait for the data to be retrieved through php.
Ajax uses asynchronous processing model, where once the request to server is sent the client will executing the next statements without waiting for the response to comeback. Once the server response either the success or failure callback will get called depending on the status of the response.
You need to put all your processing using the data from the ajax call in the success callback.
ex:
$.ajax({
....
}).done(function(data) {
//To all you post processing here
}).fail(function(){
//Do your error handling here
});
A ajax call doesn't stop the next line execution so you will have to do something like below:
$(function () {
var originalData="";
$.ajax({
url: 'data.php',
data: "",
dataType: 'text',
success: function(data)
{
originalData=data;
alert("originalData 1 "+ originalData);
myFunction();
}
});
function myfunction()
{
alert("originalData 2 "+ originalData);
...
Processing code
...
}
});
It seems that the success, error, and complete callbacks only fire when the ajax request is able to get some response from the server.
So if I shut down the server the following error callback is not executed and the request fails silently.
$.ajax({
type: "GET",
url: "http://localhost:3000/",
dataType: "script",
success: function() {
alert("success");
},
error: function() {
alert("error");
}
});
What's the best way to throw an error when the server can't be reached at all.
Edit - From what I've tried and read it appears that jQuery's built in error handling doesn't work with JSONP, or dataType: "script". So I'm going to try setting a manual timeout.
Edit - Did a little more research and it looks like not only does the ajax error callback not work, but you can't abort an ajax request with dataType script or jsonp, and those requests ignore the timeout setting.
There is an alternative - the jquery-jsonp plugin, but it uses hidden iframes which I'd rather avoid. So I've settled on creating a manual timeout as suggested below. You can't abort the request if it times out, which means the script may still load even after the timeout, but at least something will fire if the server is unavailable.
You can use a setTimeout, and clear it with clearTimeout in the complete handler.
var reqTimeout = setTimeout(function()
{
alert("Request timed out.");
}, 5000);
var xhr = $.ajax({
type: "GET",
url: "http://localhost:3000/",
dataType: "script",
success: function() {
alert("success");
},
error: function() {
alert("error");
},
complete: function() {
clearTimeout(reqTimeout);
}
});
jQuery.ajax already has a timeout preference and it should call your error handler should the request time out. Check out the fantastic documentation which says — I’d quote it here, emphasis mine:
timeoutNumber
Set a local timeout (in milliseconds) for the request…
and:
error (XMLHttpRequest, textStatus, errorThrown) Function
A function to be called if the request fails. The function is passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror". This is an Ajax Event.
error: function (jqXHR, textStatus, errorthrown) {
if (jqXHR.readyState == 0) {
//Network error, i.e. server stopped, timeout, connection refused, CORS, etc.
}
else if (jqXHR.readyState == 4) {
//HTTP error, i.e. 404 Not found, Internal Server 500, etc.
}
}
Use readyState of XMLHttpRequest to determine the status of the ajax request.
'readyState' holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
If I remember correctly, jQuery throws exceptions. Thus, you should be able to work with a try { ... } catch() { ... } and handle it there.
You can use Jquery's AjaxSetup to handle your error handling.
$.ajax({
type: "GET",
url: "http://localhost:3000/",
dataType: "script",
success: function () {
alert("success");
}, error: function () {
alert("error");
}
//AJAX SETUP "error"//
$.ajaxSetup({
"error": function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + ' ' + textStatus + ' ' + errorThrown); //however you want
}
});
in ie8,can use:
success: function(data, textStatus, XMLHttpRequest) {
if("success"==textStatus&&XMLHttpRequest){
alert("success");
}else{
alert("server down");
}
}
but it's can't work on chrome,firefox...
i tried