xmlhttprequest error: access denied

I am trying to use the WMATA api but i get the following error:

SCRIPT7002: XMLHttpRequest: Network Error 0x80070005, Access is denied.

Here's my code
function start() {
        var params = {
            // Request parameters
            "StationCode": "Vienna",
        };
		
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","https://api.wmata.com/Rail.svc/StationParking&"+$.param(params), true);
xmlhttp.setRequestHeader("api_key","e190cf960240470f8a34a876675bf85e");
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
	if (xmlhttp.readyState==4) {
		if (xmlhttp.status==200) {
		//var jsonObject = JSON.parse(xmlhttp.response);
		console.log(xmlhttp.response);
	}
	else
	{
		console.log("Failure");
	}
  }
}
alert("HELLO WORLD");
}

start();

Open in new window


I did some research on the error and found the following on using CORS but I'm not quite sure how it works or how to use it with what I have.

Any help would be much appreciated.
LVL 5
IsaacSharePoint Client Side DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

hieloCommented:
>> Here's my code
OK, let's say the code you posted is currently saved on test.php.  At the beginning of test.php you need:
header('Access-Control-Allow-Origin: https://api.wmata.com');

See my post at http://www.experts-exchange.com/questions/28700511/JQuery-RESTful-GET-an-object.html
IsaacSharePoint Client Side DeveloperAuthor Commented:
I added the request header to my xmlhttprequest object but I still get the error:

<!DOCTYPE html>
<html>
<head>
    <title>JSSample</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>

<script type="text/javascript">

function createCORSRequest(method, url){
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr){
        xhr.open(method, url, true);
		xhr.setRequestHeader('Access-Control-Allow-Origin', 'http://api.wmata.com/');
		xhr.setRequestHeader("api_key","xxxxxx");
    } else if (typeof XDomainRequest != "undefined"){
        xhr = new XDomainRequest();
        xhr.open(method, url);
		xhr.setRequestHeader('Access-Control-Allow-Origin', 'http://api.wmata.com/');
		xhr.setRequestHeader("api_key","xxxxxx");
    } else {
        xhr = null;
    }
    return xhr;
}

        var params = {
            // Request parameters
            "StationCode": "Vienna",
        };
var request = createCORSRequest("get", "https://api.wmata.com/Rail.svc/StationParking&"+$.param(params));
if (request){
    request.onload = function(){
        //do something with request.responseText
		console.log(xmlhttp.responseText);
    };
    request.send();
}
</script>
</body>
</html>

Open in new window


Here's the page. Do an F12.
http://www.upscaleseconds.com/jshtml/wmata.html
hieloCommented:
You are not supposed to put that header on the javascript code.  You need a server header.  If your server supports php, then instead of wmata.html, rename the file to wmata.php and send the header from php:
<?php
header('Access-Control-Allow-Origin: https://api.wmata.com');
?>
<!-- the rest of what you have in wmata.html goes here -->
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

IsaacSharePoint Client Side DeveloperAuthor Commented:
I'm using SharePoint.
IsaacSharePoint Client Side DeveloperAuthor Commented:
It looks like this requires server side which I don't have access to.  I'm all client side.  All I'm trying to do is use the wmata api

At the link below, scroll to the bottom and click the JavaScript tab.

https://developer.wmata.com/docs/services/5476364f031f590f38092507/operations/5476364f031f5909e4fe3315
hieloCommented:
IsaacSharePoint Client Side DeveloperAuthor Commented:
Unfortunately, that solution requires access to the server which I don't have.
hieloCommented:
Unfortunately, there are limitations to front-end development.  Your only hope here is for that API to support "jsonp".  Take their json example (don't forget to include you api key if any) and add dataType:"jsonp", (see below).  If it is supported you should see the data in the alert().  If it fails, you will need to find an alternative server.
<!DOCTYPE html>
<html>
<head>
    <title>JSSample</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>

<script type="text/javascript">
    $(function() {
        var params = {
            // Request parameters
            "StationCode": "{string}",
        };
      
        $.ajax({
            url: "https://api.wmata.com/Rail.svc/json/jStationParking&" + $.param(params),
dataType:"jsonp",
            beforeSend: function(xhrObj){
                // Request headers
                xhrObj.setRequestHeader("api_key","{subscription key}");
            },
            type: "GET",
            // Request body
            data: "{body}",
        })
        .done(function(data) {
            alert("success" + JSON.stringify(data) );
        })
        .fail(function() {
            alert("error");
        });
    });
</script>
</body>
</html>

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
IsaacSharePoint Client Side DeveloperAuthor Commented:
jsonp not supported.  Will need to figure something else out.  Thanks for the help.
Nick MarkSoftware EngineerCommented:
Include the api key in the url parameters and it will return the requested data.

$(function() {
        var params = {
            // Request parameters
            'api_key': '{subscription key}'
        };
      
        $.ajax({
            url: "https://api.wmata.com/Rail.svc/json/jStationParking?" + $.param(params),
            type: "GET",
            headers: { 'Accept': 'application/json; odata=verbose' }
        })
        .done(function(data) {
            alert("success" + JSON.stringify(data) );
        })
        .fail(function() {
            alert("error");
        });
    });
}

Open in new window


Let me know if you still have issues as I have recently become quite familiar with using the WMATA API from both client side and server side in SharePoint applications.

Regards,
Nick
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.