Random jquery ajax error readyState=0 - javascript

I have a web application that uses jQuery ajax to get some data. In this site I also have a Logger that reports to me when an error happens.
Very frequently I get this error on ajax calls:
{"readyState":0,"responseText":"","status":0,"statusText":"error"}
The problem is that this error is randomly and I'm not able to reproduce it. I get this for all ajax scripts. The request is made on same origin and at the server I've defined "Access-Control-Allow-Origin", "*".
All browsers get this error:
Safari 9
Chrome
Internet explore 11
etc...
The jQuery ajax code:
$.ajax({
url: 'MyUrl',
type: 'POST',
dataType: "json",
data: {dataVars},
error: function(response, ajaxOptions, thrownError) {
log.error( 'StringError: ' + ajaxOptions + '\n\nthrownError: ' + JSON.stringify(thrownError) + '\n\nResponse: ' + JSON.stringify(response));
},
success: function(res){
}
});
The request is performed to a servlet. What could be the problem?

From W3schools:
readyState=0
Means that the request isn't sent. (your broswer isn't connected to the targeted server).
It's mean that the socket is not opened : no TCP handshake, so the targeted URL is just not reached...
So check the validity of myUrl (is it a good domain? no cross-origin), and also connectivity of the client (proxy? if myUrl is secured / use an other port, maybe it is just not opened...)
I think the issue might be on server side, if it is random. but especially for myUrl, if you can get the web page anyway...
But the error is strange, if it comes from the same server!
Anyway, I think it is because the connection between your client and the targeted server is unstable, so maybe you can try to inscrease the timeout of the request, or retry it on error (example with recursive loop):
var remainingRetry = 3; //or something else
function handleRequest()
{
$.ajax({
url: 'MyUrl',
type: 'POST',
dataType: "json",
data: {dataVars},
error: function(response, ajaxOptions, thrownError) {
if (remainingRetry)
 {
remainingRetry--;
setTimeout(handleRequest, 1000); //timeout between two tries
}
else log.error( 'StringError: ' + ajaxOptions + '\n\nthrownError: ' + JSON.stringify(thrownError) + '\n\nResponse: ' + JSON.stringify(response));
},
success: function(res){
}
});
}

I had the same issue before and in my case the problem was
that other js function redirecting to another page before my first request has a chance to complete which is practically canceling or killing my request
some thing like
function redirectToAnotherPageFn () {
window.location = "/otherpage.html";
};

Related

POST (url) net::ERR_BLOCKED_BY_CLIENT

I am getting the below below when i try to the url
https://www.cshippers.com/orderManagement/OrderManagementReportAction.action?actionCommand=submit&menuRef=REP_APP005_0001MT
The error:
POST (url) net::ERR_BLOCKED_BY_CLIENT
The JavaScript Function:
$.ajax({
url:targetUrl, //supposed to be the url as mentioned in question
data: formData.serialize(),
cache: false,
type: 'POST',
success: function (dataofconfirm) {
openPage( url.substring(0, url.indexOf(".",2)) + ".action?menuRef="+menuRef );
/*hideLoader();*/
},
error: function (xhr, ajaxOptions, thrownError) {
hideLoader();
console.log( thrownError );
}
});
Usually, there are two problems:
Related to adblocker and you need to turn it off
You need to add an extra segment at the end of your URL
For example "https://--your api--/movie.json". You need to add the target node in your database, here it is movie, at the end of the URL.
Firebase needs this .json at the end of the URL you are sending requests to, otherwise your request will fail.
If you are using Firebase, it could solve your problem.
You can test your API with one of the online open API testing.

SSL_ERROR_HANDSHAKE_FAILURE_ALERT with JQuery GET request

There is a server which provides a XML under a certain URL (for example: https://myxmlfile). For this server request is a p12 certificate with password needed which I installed in Firefox and on my machine. If I enter the URL in the webbrowser (https://myxmlfile), the xml will be shown.
Now I try to make a jQuery GET Request from my website (which is just running on my local machine at the moment). In that GET Request I want to get the same XML, but this doesn't work and I get SSL_ERROR_HANDSHAKE_FAILURE_ALERT.
I'm pretty new to certificates. So is it not enough to install the certificate in the browser? Do I have to send the certificate in the GET request or something like that?
This is the request:
$.ajax({
type: "GET",
url: 'https://myxmlfile',
data: 'subscriptionID=0011',
dataType: "xml" ,
async: false,
error: function(xhr, status, error){
console.log('Error: '+ xhr.status+ ' - '+ error);
console.log("error");
},
success: function(xml) {
console.log(xml);
}
});
Thanks for your help.

jQuery invalid label jsonp

I use jQuery to get php-script result with ajax-function. Problem is php-script is on the another domain, so I should use "jsonp" as returned dataType, BUT php-script returns json, not jsonp (maybe script is not correct) and I get syntax error. How can I handle it? I suppose, that I can somehow get json string before ajax-function handles it and rises error, is it possible?
This is my ajax function:
$.ajax(
{
type: "POST",
dataType: "jsonp",
url: "http://www.pecom.ru/bitrix/components/pecom/calc/ajax.php",
data: res,
error: function (xhr, ajaxOptions, thrownError) {
alert("error: " + xhr.status);
},
success: function (data) {
alert("Data Loaded: " + data)
}
}
)
Thank you!
The short answer is that you can't.
The longer one is that you have to set up some sort of proxying: make the request on the server side from a machine you control, transform the results to proper JSONP there, and connect to that server via AJAX.
(Or, in the very unlikely event that the target server supports CORS, you can use that instead of JSONP.)

Download JSON file via JavaScript/JQuery - HTTP-Status Ok - JQuery Error

I've got the following problem: I need to download a JSON file from an API via JQuery / JavaScript. In theory this should be quite basic.
I tried $.ajax and all of its siblings like $.get or $.getJSON. I alway get an 200 OK but my Firebug reports an error. Printing the error just says: "error" - so not that helful.
I read that maybe the JSON file is corrupt. So I tried it with a plain text file (*.txt). Same result.
The JSON file is valid, I check it against a validator.
I also tried ContentType and dateType and experimented with json and jsonp...
I basically used something like this (with a million variations for testing purposes):
$.ajax({
url: 'http://www.myurl.com/api/v1/myfile.json',
...
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error.statusText);
}
});
Am I missing something important here? It's really odd that nothing seems to change the behavior of the AJAX-call.
In fact I don't really need AJAX because I need to grab the JSON file when loading the page...
And the JSON file is not on the same domain as the AJAX caller.
Is that URL located on the same server you're trying to get the data from?
If not, you ran into a cross-domain request, which can only be handled using JSONP. So, the JSON file itself must be compatible with JSONP format, otherwise jQuery won't be able to process it (even if you provide a 'jsonp' dataType).
P.S.: Firebug will always show response code 200 but give an empty response body for such requests
Try in this way by disabling security
$.ajax( {
type : 'GET',
contentType : "application/json; charset=utf-8",
url : surl, \\specify your url
async : false,
dataType : 'json',
headers : {
Accept : "application/json",
"Access-Control-Allow-Origin" : "*"
},
crossDomain : true,
success : SucceedFunc,
error : function(data, textStatus, errorThrown) {
console.log("error" + ' ' + JSON.stringify(data) + ' ' + textStatus + ' ' + errorThrown);
}
});
function SucceedFunc(data) {
alert("success");
}
}
Did you try to catch the error the correct way?
$.ajax({
url: 'http://www.myurl.com/api/v1/myfile.json',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error.message);
}
});
If you are using chrome go to cmd prompt and run the chrome by disabling the security. You can disable security using pathwhere_chrome_is_located\chrome.exe --disable-web-security
and run the html page. I think this may help you.

Is there a way to return JSON rendered by javascript through ajax call

I have a situation that I have to run some javascript and get a response on a clients site from my site, and I'm trying to think of the best way to do this because of cross domain scripting security.
I have access to placing a snippet of code on a client page.
I can modify my own site as much as I want.
One option is to open the page up via an iframe have the snippet on their site run get the response and set a cookie that I can poll for to get the response from...yikes...
I have been thinking of different ways to do this, and I'm trying to get creative. I'm a backend guy with a bit of javascript experience, but nothing having to deal with cross domain stuff. Please I would appreciate any help.
Thanks,
You could use JSONP in your situation.
Example with JQuery could be found here
with your snippet on the client side create the iframe dynamically - then you will be in a clients domain sandbox and will be able to send a request to your site
May be you can call a web service via ajax call and return JSON string by following way..
$.ajax({
type: "POST",
url: "JSON.asmx/Getdata",
data: {},
contentType: "text/javascript; charset=utf-8",
ContentLength: 15000,
dataType: "text",
async: true,
// timeout:10000,
success: function (msg) {
asmxdata(msg);
return false;
},
error: function (xhr, ajaxOptions, thrownError, request, error) {
alert('xrs.status = ' + xhr.status + '\n' +
'thrown error = ' + thrownError + '\n' +
'xhr.statusText = ' + xhr.statusText + '\n' +
'request = ' + request + '\n' +
'error = ' + error);
return false;
}
});
Then on success of the Web service call (i.e method asmxdata() in here) you can evaluate the JSON string into a JSON object by following way:
function asmxdata(data) {
var JObject = eval('(' + data + ');');
}
and assign values to controls
document.getElementById('lblfirstname').value = JObject.Table[i].FirstName;
If anything is unclear please Comment.

Categories

Resources