Get cancelled xhr Status in javascript - javascript

I am making xmlhttprequest to server to get data, I am getting the data successfully, But i want to get the status if my server gets failed or shutdown unexpectedly. I have the Below code from which i am making a xmlhttprequest.
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", usersResponse);
xhr.responseType = "json";
xhr.open("GET", CONFIG.api_url + `/api/users`);
xhr.setRequestHeader("Content-type", "application/json");
xhr.setRequestHeader("Authorization", token);
xhr.send();
function userResponse(){
if(this.status===200){
console.log(this.response);
}else{
alert('something went wrong');
}
can anyone please tell the any method, which can be used to get the server error response.
Thanks in advance.

It is fixed, Just add
xhr.addEventListener("error", transferFailed);
when making the xhr request & in transferFailed function, you will get this.response is null like below,
function transferFailed(){
console.log(this);
}

Related

sending form data with javascript with XMLHttpRequest asynchronously

I am sending some form data with an XMLHttpRequest
let xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
try {
let data = JSON.stringify(sendForm);
xhr.send(data);
alert(xhr.status);
}
catch (error) {
alert(error);
}
This works as it will go into this after the alert pops up in the browser
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
location.href = 'thanks.html';
}
and data will be inserted into the database as expected. However, if I comment out the alert after the xhr.send(data); this code will no longer inserts data into the database or display the correct page, it just displays the js file. If I set a break point at xhr.send(data) when I step past it is when the js file is displayed.
Any thoughts as to why the data is being sent if I include the alert(xhr.status) step in the code but not when I comment it out? Also, any thoughts why the try{}catch{} is not catching the error? Thanks I am not very familiar with javascript right now.

No Access-Control-Allow-Origin header JS Get Request

I Have write a code using JS, to send GET Request to a URL. This error appears in the console when I'am clicking the button to make the GET request: ERROR
Below you can see the code, I saw some solutions but it didn't work for me. I'am working in a index.html file should I insert something in my code to fix this error?
function call()
{
var url = "http://urlexample";
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}};
xhr.send();
}
<button onclick="call();">Make a request</button>

XmlHttpRequest.onload not working in Edge browser

I'm running into an issue where Microsoft Edge browser isn't able to execute XmlHttpRequest.onload. But it does execute in Chrome, Firefox, and Safari.
I'm creating an XmlHttpRequest object:
var xhr = new XMLHttpRequest();
xhr.responseType = "json";
xhr.open("POST", authenticateUrl, true);
xhr.setRequestHeader("X-OpenAM-Username", email);
xhr.setRequestHeader("X-OpenAM-Password", password);
xhr.setRequestHeader("Content-Type", "application/json");
alert("XHR object is created");
xhr.onload = function () {
alert("start onload...");
//...receives response from service...
}
xhr.send();
The alerts in place to validate it's reaching a specific line of code. After the XMLHttpRequest object is created, the code goes into the onload function. Microsoft Edge won't go into it. As I said, Chrome, Firefox, and Safari execute this code fine.
Is there something additional needed for making Microsoft Edge run this code?
The onload function shouldn't be called until you send the XHR and the response comes back (unless there is an error). Are you calling xhr.send()?
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestEventTarget/onload
Place the xhr.responseType = "json" line after the xhr.open(...)
Because the xhr.responseType is not allowed for synchronous requests which is determined by the third parameter in the open() call.
Wait, that was in IE11, i've tried your snippet in Edge and it ran just fine.
Try adding a
xhr.onerror = err => alert('Error:' + err.message);
to see if an error occurred.

Check if ajax was aborted

I am not using jquery (cause I cant in this specific project) so how do I know the request was aborted by user using .abort() method? I read a lot and there is no abort method in the object XMLHttpRequest.
I know I can chek the status and readyStatus of onreadystatechange but it does not tell me anything if the connection was aborted
thans.
You can determine if the request has been aborted by testing the readyState, which will again be 0.
var xhr = new XMLHttpRequest();
console.log(xhr.readyState); // 0
xhr.open('GET', '/');
console.log(xhr.readyState); // 1
xhr.abort();
console.log(xhr.readyState); // 0
If you need to know when it's aborted, not just if, then you'll have to use onabort as onreadystatechange won't be triggered by it.
var xhr = new XMLHttpRequest();
xhr.onabort = function () {
console.log('Was aborted', xhr.readyState);
};
xhr.open('GET', '/');
xhr.send();
xhr.abort(); // Was aborted 0

facebook graph api ajax XMLHttpRequest - Null result?

Summary: Keep getting null response despite public data and setting callback to enable cross domain JSON. Please help!
A similar question has been answered here
Using the new facebook graph api, ajax calls returns null (empty)
but I'm not using jquery and have tried to adapt my code to reflect that answer.
I'm trying to use a simple example to test a simple xmlhttprequest handler. I have this link in my page:
<a href='javascript:loadXMLDoc(\"https://graph.facebook.com/btaylor?callback=methodname\",\"\")'>AJAX LINK</a>
The callback=methodname parameter is to enable cross domain JSON
I'm using a generic XMLhttprequest builder:
var req; // Request object
function loadXMLDoc(url,params){
// branch for native XMLHttpRequest object
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.setRequestHeader("Content-length", params.length);
req.setRequestHeader("Connection", "close");
req.send(params);
// branch for IE/Windows ActiveX version
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.setRequestHeader("Content-length", params.length);
req.setRequestHeader("Connection", "close");
req.send(params);
}
}
}
I then have a handler :
function processReqChange(){
if (req.readyState == 4) {
if (req.status == 200) {
alert("Done");
} else {
//alert("There was a problem retrieving the data:\n" + req.statusText);
alert("Status Code = "+req.status);
alert("There was a problem retrieving the data:\n");
alert("Failed : object = "+req);
alert(req.responseXML);
alert("Failed : response = "+req.responseText);
alert("Failed : status = "+req.statusText);
}
}else{
}
}
But I keep getting a null response (statusText OK, status code 0). Any ideas?
Thanks in advance
You can't make a cross-domain ajax request. Look into whether or not they support JSONP, or use the FB.api method from their javascript SDK
http://developers.facebook.com/docs/reference/javascript/FB.api
EDIT: I didn't read your post very thoroughly when I replied.
I see that you're adding the callback name to your ajax request, which isn't going to do any good because you're still making an XHR request, so it will still fail cross-domain. You seem to be misunderstanding how JSONP works.
Normally I'd just suggest using a framework like jQuery to abstract out the work that you shouldn't have to reinvent. If you're absolutely dedicated to doing this without jQuery, start by reading the wikipedia article on how JSONP works:
http://en.wikipedia.org/wiki/JSON#JSONP
The basic idea is:
Create a script node where the src attribute looks just like the URL you're trying to request now.
The server will respond with something like : methodname({"foo": "bar"}); instead of just JSON. Since this is being requested via a script node, your browser will execute the "methodname" function and pass in the results.
implement methodname(response) function to handle the response (i.e. do the work you intended to do in processReqChange)
Remove this line and try again:
req.setRequestHeader("Connection", "close");
It sets up the connection to close automatically, often before the send is complete.

Categories

Resources