REST API call gives response code 0 - javascript

I'm doing an API call to the Insightly API using this code:
var x = new XMLHttpRequest();
x.open("GET", "https://api.insight.ly/v2.2/Projects/Search?status=in%20progress&brief=false&count_total=false", true);
x.setRequestHeader('Authorization', 'Basic: 'some-basic-key-and-user');
x.send();
console.log(x.status);
but the responsecode output equals 0
I've tried my URL and AuthKey using hurl.it's tool, and it gives back exactly the response I need. I've also tried x.statusText and x.Response
How come my script doesn't give me the output I need?
EDIT:
After trying adding those parameters from Mozilla's documentation (thank you Amy). I still don't get the correct response code.
My code now:
var x = new XMLHttpRequest();
x.open("GET", "https://api.insight.ly/v2.2/Projects/Search?status=in%20progress&brief=false&count_total=false", true);
x.setRequestHeader('Authorization', 'Basic: b4c6c660-e20f-4f31-b90d-b6a11bfe4ef2');
x.onprogress = function () {
console.log('LOADING', x.status);
};
x.onload = function () {
console.log('DONE', x.status);
};
x.send();
console.log(x.status);
The response code:
0
LOADING 0
Also I've read through the possible answer, and I still don't know how to fix my mistake, I know why it is asynchronous and why it doesn't work this way, but I don't know how to fix.

First of all, you have unnecessary quote symbol on row 3 (right after some-basic-key-and-user).
Second is that insight api doesn't support cross origin resource sharing (CORS for short).
You might want to introduce some proxy on the same domain you query data from.

Related

XMLHttpRequest always sends as GET

So I wrote an AJAX js library a while ago (a simple one) and today I suddenly noticed it wasn't working anymore.
Now, I've ripped some of the code out of it and manually put it into a script to test it. Again, it's not working correctly. I was wondering if anyone could help me figure out why?
This is the javascript code:
Now here, the first one works and the second one doesn't...
$loginBtn.on("click", function() {
if(validateForm($loginForm))
{
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/login/login/", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford");
var url = $loginForm.attr('action');
var params = "username=foo&password=bar";
var xhttp2 = new XMLHttpRequest();
xhttp2.open('POST', url, true);
xhttp2.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp2.send(params);
}
return false;
});
The end goal is to do this with formData(), but i'm going back to basics to see what's going wrong here.
The thing is, that even though the XMLHttpRequest DOES fire, it seems to completely ignore everything I set for it.
The headers return as a GET while I'm setting it to POST, the content-type I set is nowhere to be seen. No matter what header I add, it's not being added.
It just sends a GET for no apparent reason. The call in itself is succesful and gives the appropriate response, though.
things I've tried so far;
checked any type of caching and made sure I'm not using cached scripts
stripped away all extra functions to make sure there is nothing else going wrong
Made sure there is no server-side caching of any kind
Disabled all other scripts for testing reasons.

How do I suppress Chrome from issuing "net::ERR_NAME_NOT_RESOLVED" for my XMLHttpRequest?

My XML HTTP request requests a URL that does not exist:
var url = 'http://redHerringObviouslyNonexistentDomainName.com';
var myHttpRequest = new XMLHttpRequest();
myHttpRequest.open('GET', url, true);
myHttpRequest.onreadystatechange = function() {
if (myHttpRequest.readyState == 4 && myHttpRequest.status == 200) {
// Do stuff with myHttpRequest.responseText;
}
}
myHttpRequest.responseType = 'text';
myHttpRequest.send();
I'm OK with the URL not existing ... but I'm not OK with Chrome issuing the following error in the Console:
GET redHerringObviouslyNonexistentDomainName.com/ net::ERR_NAME_NOT_RESOLVED
How do I tell Chrome "I don't care that the URL does not exist - just suppress that error from the Console?"
If someone answers this question by buying that domain name, I will lol so hard ... but then you'll feel bad after I change the URL I use in this question.
as far as this problem, an option would be to send the request to a non-existent ip rather than a non-existent domain because it is throwing that error out of an attempt to find out what ip it points to failing. so by sending it to an ip that you know for a fact will not return anything you may be able to avoid this, although this is purely in theory and you could get an entirely different error thrown at you.
another option is to send the request and have the value returned made into a variable with
errorDomain = yourMethodOfRequestingStatus
this is pure theory and I have not tested any of the suggested methods but I hope it helped you at least a bit.

cannot manipulate response from xmlHttpRequest 2

I'm using XHR 2 to upload/save files.
According to the response of the server I want to perform an action. For example if the responce is "Saved" I want to hide a div or if the response is "Not Saved" I want to show another div etc...
I implemented what appears to be a simple code that should be working , but is not
Here is the snippet of the XHR
//initialize
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php');
xhr.responseType="text";
xhr.onload = function() {
//if all ok....
if (xhr.status === 200)
{
//update html5 progress bar
progress.value = progress.innerHTML = 100;
//get the respnse
var data=xhr.response;
//convert it to sting - kind of overkill, I know, but I'm stack
var data2=data.toString();
//alert it -- works
alert('data2 '+data2);
//now, do something, according to the response -- NOT working, never alert anything
if (data2=="Not Saved"){alert('Ooops, not saved');}
if(data2=="Saved"){alert('It's all good');}
if(data2=="File too big"){alert('hey, you are watching Jake and Amir');}
document.getElementById('imagesaved').innerHTML=data;
}
//refers to if (xhr.status === 200)
else {document.getElementById("imagesaved").innerHTML="Connect to server failed";}
What is wrong here? This should be working right? Any suggestions?
Thanks
EDIT
I put the alerts for testing. What I actually want to do is call some functions.
If I put
if (data2=="Not Saved"){functionOne();}
if(data2=="Saved"){functionTwo();}
if(data2=="File too big"){functionThree();}
the functions never get called
if I put
if (data2!="Not Saved"){functionOne();}
if(data2!="Saved"){functionTwo();}
if(data2!="File too big"){functionThree();}
ALL the functions are called!!!
I still dont get it...Maybe its something with the response? Or the onload function?
Thanks again
What I finally did is make the server response with numbers, not text. So encoding does not matter any more...
This is the code
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status == 200)
{
var data=xhr.response;
if(data==1)
//say to the user is saved
{document.getElementById('imagesaved').innerHTML="Saved";}
//say to the user, there was an error
else{document.getElementById('imagesaved').innerHTML="Error";}
}
//say to the user that connection to the server failed
else {document.getElementById("imagesaved").innerHTML="Cannot connect";}
};
xhr.open('POST', 'upload.php');
xhr.send(formData);
This is a workaround. I dont know if its the right way to solve this problem , technically. I decided to post it anyway, to help others to quickly solve similar problems. If anyboy else has a better way to suggest , please do.
In this line : if(data2=="Saved"){alert('It's all good');}, you have to escape " ' ".
So convert it to : if(data2=="Saved"){alert('It\'s all good');}
Are you sure that the response of your ajax is text/plain ?
Look on the console (ctrl+shift+i on chrome, F12 on firefox), on net or network tab.
Look on console tab if you got some javascript errors too.

Javascript cross-domain web request fails with Status=0?

EDIT: It's been pointed out below that this doesn't work because craigslist doesn't set an Allow-Cross-Domain header. OK, I'll buy that. Is there any other way to use javascript in firefox to download a page cross-domain then?
Yes, I know the following code does not work in IE. I know IE expects me to use XDomainRequest() instead. I don't care about that. This is firefox only.
I'm trying to do a cross-domain web request in firefox javascript. I keep getting a status of 0. Does anyone know why?
var url = "http://newyork.craigslist.org";
var xdr = new XMLHttpRequest(); //Yes, I know IE expects XDomainRequest. Don't care
xdr.onreadystatechange = function() {
if (xdr.readyState == 4) {
alert(xdr.status); //Always returns 0! And xdr.responseText is blank too
}
}
xdr.open("get", url, true);
xdr.send(null);
Shouldn't that work?
Craigslist doesn't allow cross-domain requests to it. It needs to send a proper Access-Control-Allow-Origin header.

Problem with making a simple JS XmlHttpRequest call

Edit: Maybe I made the question more complex than it should. My questions is this: How do you make API calls to a server from JS.
I have to create a very simple client that makes GET and POST calls to our server and parses the returned XML. I am writing this in JavaScript, problem is I don't know how to program in JS (started to look into this just this morning)!
As n initial test, I am trying to ping to the Twitter API, here's the function that gets called when user enters the URL http://api.twitter.com/1/users/lookup.xml and hits the submit button:
function doRequest() {
var req_url, req_type, body;
req_url = document.getElementById('server_url').value;
req_type = document.getElementById('request_type').value;
alert("Connecting to url: " + req_url + " with HTTP method: " + req_type);
req = new XMLHttpRequest();
req.open(req_type, req_url, false, "username", "passwd");// synchronous conn
req.onreadystatechange=function() {
if (req.readyState == 4) {
alert(req.status);
}
}
req.send(null);
}
When I run this on FF, I get a
Access to restricted URI denied" code: "1012
error on Firebug. Stuff I googled suggested that this was a FF-specific problem so I switched to Chrome. Over there, the second alert comes up, but displays 0 as HTTP status code, which I found weird.
Can anyone spot what the problem is? People say this stuff is easier to use with JQuery but learning that on top of JS syntax is a bit too much now.
For security reasons, you cannot use AJAX to request a file from a different domain.
Since your Javascript isn't running on http://api.twitter.com, it cannot request files from http://api.twitter.com.
Instead, you can write server-side code on your domain to send you the file.

Categories