JavaScript error when trying to fire simple XMLHttpRequest (GET) - javascript

Bit of a JavaScript newbie here -
I am firing this basic bit of JavaScript code from my website as a test:
var req = new XMLHttpRequest();
req.open('GET', 'http://www.google.co.uk/', false);
req.send();
if (req.status == 200) {
alert(req.responseText);
}
and I keep getting the following error:
[Exception... "Component returned
failure code: 0x80004005
(NS_ERROR_FAILURE)
[nsIXMLHttpRequest.send]" nsresult:
"0x80004005 (NS_ERROR_FAILURE)"
location: "JS frame ::
http://localhost/testEx3/Default.aspx
:: SendRequest :: line 402" data: no]
Does anyone know what I'm doing wrong here?
UPDATE:
OK - so what I'm actaully trying to do is a POST request to a web service I published on my local dev machine - I was getting the same error as above - that's why I put that example for simplicity. It now appears the "Same Origin Policy" has come into play - so now I have published the web service with the begining part of the URI as http://localhost/ instead of http://tempuri.org/.
Now I get a 500 error. Is there something I am missing in the headers?
var request = new XMLHttpRequest();
request.open("POST", "http://localhost/ApplicationServices.asmx?op=AddressSearch", false, "", "");
request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
request.send(x, y, buffer);
if (request.status == 200) {
alert("Success");
}
else {
alert("Failure: " + request.status);
}

It looks like you're trying to send a request that would violate the same origin policy.
Basically, in terms of AJAX requests, you're limited to sending requests to the same domain as the page sending that request. For example:
http://foo.com/bar -> http://foo.com/ajax (OK)
http://foo.bar.com/ -> http://foo.bar.com/biz/buzz (OK)
http://foo.com -> http://google.com (NO)
http://foo.bar.com -> http://biz.bar.com (NO)
You're trying to do #3 above.
If you need to send a cross-domain request, you can using JSONP or something like flensend/flxhr.

Unless you work for Google, that's not going to work. You can't pull information from another domain via XMLHttpRequest. It's called the "same origin policy".
edit — If you're getting a 500 error from your local server, that means that your HTTP request is making it to the server, and the some code in the server is failing. Check your server logs.

Related

Mixed Content on XMLHttp request

I'm currently working with the Bungie API and am having some trouble getting OAuth Tokens from a POST request. I am currently using javascript with XMLHttpRequest to make the post and handle the response, but every time I send a post, it gives me a Mixed Content page even though both the website I am hosting and the API endpoint is https. I've been searching everywhere and all I can find is that I either need to secure my site (even though my site has an SSL certificate) or alter the URL in the post by removing or adding a slash (I've done both many times). Any advice or ideas are appreciated, thanks!
Code:
var url="https://www.bungie.net/Platform/App/OAuth/Token";
https.onreadystatechange = function() {
if(this.readyState==4){
if (this.status==200) {
console.log(this.responseText);
}
else if (this.status==400) {
console.error("Bad Request (400) Response: " + this.responseText);
}
else if (this.status==401) {
console.error("Unauthorized (401) Response: " + this.responseText);
}
else {
console.error("There was a Problem: " + this.responseText);
}
}
}
https.open('POST', url, true);
https.setRequestHeader("X-API-Key","e76XXXXXXXXXXXXXXXXXXX");
https.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
https.setRequestHeader("Authorization", authHeader);
https.send(data);
Error Message:
Mixed Content: The page at 'https://mywebsiteurl.com/callbacks.html?
code=08fcbde4d71019d1d795a1c1dd79be67' was loaded over HTTPS, but requested an insecure
XMLHttpRequest endpoint 'http://www.bungie.net/Platform/App/OAuth/Token/'. This request has been
blocked; the content must be served over HTTPS.
This is a problem with the bungle.net server. It's redirecting from HTTPS to HTTP, and Chrome is then blocking this because it violates the restriction against mixed content.
I don't think there's anything you can do in your code to override the restriction.

Unable to retrieve data from http site to https using XMLHttpRequest()

I have a site hosted on https:// in which I want to pull data from the site which shows the properties of the shares. The URL which returns the data is:
http://ir1.euroinvestor.com/asp/ir/xmlirmultiiso2.aspx?companyid=281191
The code which I have developed to get the data is as follows:
function GetSharesUpdate(){
// makeing AJAX calls to the web service for getting the share update
var xhr = new XMLHttpRequest(); // Set up xhr request
xhr.open("GET", "http://ir1.euroinvestor.com/asp/ir/xmlirmultiiso2.aspx?companyid=281191", true); // Open the request
xhr.responseType = ""; // Set the type of response expected
xhr.send();
// Asynchronously wait for the data to return
xhr.onreadystatechange = function () {
if (xhr.readyState == xhr.DONE) {
var tempoutput = xhr.responseXML;
alert(tempoutput);
}
}
// Report errors if they happen
xhr.addEventListener("error", function (e) {
console.error("Error: " + e + " Could not load url.");
}, false);
}
I am getting the error on the statement xhr.send(); which is as below:
Mixed Content: The page at 'https://[SiteUrl]' was loaded over HTTPS,
but requested an insecure XMLHttpRequest endpoint
'http://ir1.euroinvestor.com/asp/ir/xmlirmultiiso2.aspx?companyid=281191'.
This request has been blocked; the content must be served over HTTPS.
If I change the URL to https i.e.
https://ir1.euroinvestor.com/asp/ir/xmlirmultiiso2.aspx?companyid=281191
then xhr.send(); is executed without any error but I am getting xhr.responseXML null.
What should I make changes in my code to make it working?
The first problem is you are doing ajax request to non-https domain but your domain has SSL installed.
The second problem is Cross origin request CORS, you will have this problem even you solve first (ie. even you try ajax request from non-http domain).
Since you are requesting data from another website this is most likely to happen unless the requested server is configured to serve requests for you domain
To solve this you need to call the data from your server(proxy server) or have the requested server configured to allow requests from your domain.
See more - https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Converting cURL to JQuery.ajax request

Hi I'm working on connecting to an API that is using Layer 7 as an IP authorizer and eGalaxy as a credentials authorizer, when the curl request is sent a line of xml is sent back to me. I'm currently working on localhost, I've implemented the Access-Control-Allow-Origin chrome extension.
My curl request looks as such:
curl https://client-url/eGalaxy.aspx -H 'Content-Type:text/html' --data '<?xml version:"1.0" encoding="UTF-8"?><Envelope><Header><SourceID>0</SourceID><MessageID>131</MessageID><MessageType>Authenticate</MessageType></Header><Body><Authenticate><Username>*username*</Username><Password>*password*</Password><PasswordEncrypted>NO</PasswordEncrypted></Authenticate></Body></Envelope>' --insecure
When I tried to create an ajax request I receive an "Invalid HTTP status code 500" error and "OPTIONS url" which drops down to show:
n.ajaxTransport.k.cors.a.crossDomain.send # jquery-2.1.3.js:4
n.extend.ajax # jquery-2.1.3.js:4
(anonymous function) # VM947:2
InjectedScript._evaluateOn # VM899:895
InjectedScript._evaluateAndWrap # VM899:828
InjectedScript.evaluate # VM899:694
My ajax code is as follows:
$.ajax({
url:'https://client-url/eGalaxy.aspx',
data:'<?xml version:"1.0" encoding="UTF-8"?><Envelope><Header>
<SourceID>0</SourceID><MessageID>131</MessageID>
<MessageType>Authenticate</MessageType></Header><Body>
<Authenticate><Username>*username*</Username>
<Password>*password*</Password>
<PasswordEncrypted>NO</PasswordEncrypted></Authenticate></Body>
</Envelope>',
type:'POST',
contentType:'text/xml',
dataType:'xml',
success: function(data){
},
error: function(){
}
});
Any help with translating into a proper AJAX request would be appreciated!
EDIT: If this makes a difference these are the headers that are returned with the client's xml when the curl is complete(client information deleted)
This application will be made into a widget as well, so it will not be running off of a hosting site.
UPDATE 1: I'm using #KevinB's suggestion that the CORS headers were still not properly added.
Here is my updated JS code, copied from this link:
var url = 'https://client-url/eGalaxy.aspx';
var data = '<?xml version="1.0" encoding="UTF-8"?><Envelope><Header><SourceID>1</SourceID><MessageID>131</MessageID><MessageType>Authenticate</MessageType></Header><Body><Authenticate><Username>*username*</Username><Password>*password</Password><PasswordEncrypted>NO</PasswordEncrypted></Authenticate></Body></Envelope>';
var xhr = createCORSRequest('POST', url);
xhr.send(data);
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
var xhr = createCORSRequest('GET', url);
if (!xhr) {
throw new Error('CORS not supported');
}
When run with the CORS Chrome extension off I receive an Access-Control-Allow-Origin =! 'null' error. Knowing that CORS needs Access-Control-Allow-Origin header to =! 'null' will this cause problems in the future with making this into a widget that will be put into a Content Manager system?
With it on the origin is set to 'www.evil.com', with the only error in the code being that it says the xhr.send() is an anonymous method. Using breakpoints I can see the xhr in xhr.send() is set to an empty request:
> XMLHttpRequest {response: "", responseText: ""}
Inside the createCORSRequest this line is undefined. I've tested using 'GET' and 'POST' as the method.
xhr.open(method, url, true)
EDIT 2:
Using #Fabiano's approach I've changed the web.config for two versions of what I suspect is my server(?). I'm attaching screenshots of what I've gone through
No luck, so far. Decided to use xhr.AppendHeader:
I decided to use xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
The Network tab Headers for eGalaxy.aspx
There is an error in your XML. You put version:"1.0", and this makes the XML invalid.
Change to version="1.0" and try to make your request. It should work.
This may be the cause for the "Bad request" error.
You can validate your XML here: enter link description here
EDIT: After some research, the problem may be with the headers sent by your server. Your server (or page, .aspx in this case) seems to skip the header you need, the "Access-Control-Allow-Origin: *".
Look at this link: http://enable-cors.org/server.html
This site shows you how to implement it for your server. Since the page you are requesting is called eGalaxy.aspx, then you have 2 ways to implement the headers:
1- Put the line Response.AppendHeader("Access-Control-Allow-Origin", "*"); if the page is a simple ASP.NET application. If it uses Web API 2, you need to implement a different way as it is shown here: http://enable-cors.org/server_aspnet.html
2- Edit the web.config file on the root of your server and add these lines inside the tag:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
For a ASP.NET application, these are the ways you have. The link I mentioned has solutions for other applications, take a look and choose the right one. :)
Note that the value * tells you that your server will accept any cross-origin request. This may lead to a security issue, so the best you can do is to put your domain address instead of *.
I hope it helps!

Error: create_flow on surveyMonkey API (Javascript)

I'm having a problem using surveyMonkey API.
I'm able to use any public method except the Crate_flow and Send_flow.
these two raise me an error in the console:
OPTIONS
http://api.surveymonkey.net/v2/client/create_flow?api_key=**MYAPI* 596 (596) Index.html:61 XMLHttpRequest cannot load http://api.surveymonkey.net/v2/client/create_flow?api_key=**MYAPI*. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. Index.html:61 Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://api.surveymonkey.net/v2/client/create_flow?api_key=**MYAPI*'.
the code that I'm using is this:
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://api.surveymonkey.net/v2/batch/send_flow?api_key="+MYAPI, false);
xhr.setRequestHeader('Access-Control-Allow-Origin' ,'*');
xhr.setRequestHeader('Authorization','bearer '+TOKEN);
xhr.setRequestHeader('Content-Type', 'application/json');
var body = '{"survey_id" :"54681373","collector":{"type":"email", "recipients":[{"email": "martins.nuno.santos#gmail.com", "first_name": "Nuno", "last_name": "Santos"}],"send":true}, "email_message":{"reply_email":"martins.nuno.santos#gmail.com", "subject":"YOLO", "body_text": "Vamos lá experimentar isto ! [SurveyLink], para remover carrega em [RemoveLink]"}}';
xhr.send(body);
console.log(xhr.status);
console.log(xhr.statusText);
console.log(xhr.responseText);
SSL Required
The reason you're getting that error message is that you're accessing the API using the wrong protocol (HTTP instead of HTTPS). Since SSL is required, you're getting an error message in the body of the response <h1>Service Requires SSL</h1>. That message, however, does not come to you with the "Access-Control-Allow-Origin" header and is triggering this error message.
If you change http://api.surveymonkey.net to https://api.surveymonkey.net, you should be good to go.
As a side note: the "Access-Control-Allow-Origin: *" header is something the server will send back to you. It's not something you need to send to the server. It's what's missing in the response you're getting. You can safely remove the line adding it to you request from your code.

sending email via XMLHttpRequest no response

I tried to manage editing the template but I'm still not able to send email, I'm creating an subscription box, here's my code so far:
var x= document.getElementById("emailtxt").value;
var uploadFormData = new FormData();
uploadFormData.append("email", x);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://realfashionstreet.com/Emailme.php',true);
xhr.onload=function() {
alert(this.status);
if(this.status==200) {
console.log('data sent');
alert(xhr.responseText);
} else {
//alert(this.status);
alert('Something Went Wrong, Try Again Later!');
}
};
/*xhr.addEventListener("load", function () {
document.getElementById('skm_LockPane').className= 'LockOff';
}, false);*/
xhr.send(uploadFormData);
return false;
}
Here's the box I'm getting :
http://realfashionstreet.com
It's just not showing any error or any response and also not sending email, but I think that site template doesn't allow to use php files if anyone have any other idea on how to send email using javascript…
Thanks
You can't for security reasons. See the same origin policy for JavaScript.
There are some workarounds that exploit browser bugs or corner cases, but using them is not recommended.
The best approach is having a server-side proxy that receives Ajax requests, and in turn, sends HTTP requests to other servers. This should be carefully implemented by sanitizing input and whitelisting the types of requests that are sent, and the servers that are contacted.
You're missing the www. in the request, this is causing a cross domain policy violation. This is the error I see in the console.
XMLHttpRequest cannot load http://realfashionstreet.com/Emailme.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.realfashionstreet.com' is therefore not allowed access. Default.asp:1
Ensure the URLs for the page and the XHR request have the exact same domains. Including subdomains like www

Categories