Help with getting Json Format data from external website - javascript

I am trying to get Json format data from this website .. http://www.livetraffic.sg/feeds/json
however when i use ajax.. i run into this particular error in my chrome console.
Error:XMLHttpRequest cannot load. Origin null is not allowed by Access-Control-Allow-Origin.
Is the external website preventing my from using information?
Thanks for your help!!!
Sample of my code:
url = "http://www.livetraffic.sg/home2/get_erp_gantry";
$().ready(function(){
$.get(resturl, function(data) {
//do something here with data
});
});

This is your browser enforcing the same-origin policy. You are not allowed to make requests to domains other than the domain your script was fetched from.
You will have to set up some server-side proxy on the same domain as the one your script is served from and have it supply the data. (You could also cache this data on the server if it would make sense.)

You cannot make cross-domain JSON requests. Your browser will not allow it. If the target domain allows JSONP requests http://en.wikipedia.org/wiki/JSONP#JSONP then you'll be able to use this work-around instead. Else you'll have to make the request server-side.

Simpler you can perform an ajax query to a local php page which contains
header("Content-type: application/json; charset=utf-8");
echo file_get_contents('http://www.livetraffic.sg/home2/get_erp_gantry');
You just must have allow_url_fopen true.

Thanks All! Manage to pull down the Json data from external website using a server side PHP script and then passing variables to my javascript :)

Related

Can I use javascript to get a request header in http get request? [duplicate]

I want to capture the HTTP request header fields, primarily the Referer and User-Agent, within my client-side JavaScript. How may I access them?
Google Analytics manages to get the data via JavaScript that they have you embed in you pages, so it is definitely possible.
Related:
Accessing the web page's HTTP Headers in JavaScript
If you want to access referrer and user-agent, those are available to client-side Javascript, but not by accessing the headers directly.
To retrieve the referrer, use document.referrer.
To access the user-agent, use navigator.userAgent.
As others have indicated, the HTTP headers are not available, but you specifically asked about the referer and user-agent, which are available via Javascript.
Almost by definition, the client-side JavaScript is not at the receiving end of a http request, so it has no headers to read. Most commonly, your JavaScript is the result of an http response. If you are trying to get the values of the http request that generated your response, you'll have to write server side code to embed those values in the JavaScript you produce.
It gets a little tricky to have server-side code generate client side code, so be sure that is what you need. For instance, if you want the User-agent information, you might find it sufficient to get the various values that JavaScript provides for browser detection. Start with navigator.appName and navigator.appVersion.
This can be accessed through Javascript because it's a property of the loaded document, not of its parent.
Here's a quick example:
<script type="text/javascript">
document.write(document.referrer);
</script>
The same thing in PHP would be:
<?php echo $_SERVER["HTTP_REFERER"]; ?>
Referer and user-agent are request header, not response header.
That means they are sent by browser, or your ajax call (which you can modify the value), and they are decided before you get HTTP response.
So basically you are not asking for a HTTP header, but a browser setting.
The value you get from document.referer and navigator.userAgent may not be the actual header, but a setting of browser.
One way to obtain the headers from JavaScript is using the WebRequest API, which allows us to access the different events that originate from http or websockets, the life cycle that follows is this:
WebRequest Lifecycle
So in order to access the headers of a page it would be like this:
browser.webRequest.onHeadersReceived.addListener(
(headersDetails)=> {
console.log("Request: " + headersDetails);
},
{urls: ["*://hostName/*"]}
);`
The issue is that in order to use this API, it must be executed from the browser, that is, the browser object refers to the browser itself (tabs, icons, configuration), and the browser does have access to all the Request and Reponse of any page , so you will have to ask the user for permissions to be able to do this (The permissions will have to be declared in the manifest for the browser to execute them)
And also being part of the browser you lose control over the pages, that is, you can no longer manipulate the DOM, (not directly) so to control the DOM again it would be done as follows:
browser.webRequest.onHeadersReceived.addListener(
browser.tabs.executeScript({
code: 'console.log("Headers success")',
});
});
or if you want to run a lot of code
browser.webRequest.onHeadersReceived.addListener(
browser.tabs.executeScript({
file: './headersReveiced.js',
});
});
Also by having control over the browser we can inject CSS and images
Documentation: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/onHeadersReceived
I would imagine Google grabs some data server-side - remember, when a page loads into your browser that has Google Analytics code within it, your browser makes a request to Google's servers; Google can obtain data in that way as well as through the JavaScript embedded in the page.
var ref = Request.ServerVariables("HTTP_REFERER");
Type within the quotes any other server variable name you want.

How to load website HTML using jquery

How can I load some website in my java-script so that I can parse it?
I want to get Html of e.g. www.google.com and I want to select all the tags in it using jquery.
You can't as jquery doesn't allow you to load external resources, unless in the page you want to parse is present the header:
header('Access-Control-Allow-Origin: http://thesitewhereyourjscodeishosted');
If you can't set it, you could use PHP:
<script>
var website = <?php echo file_get_contents("http://websitetoload"); ?>;
</script>
Due to browser security restrictions, Ajax requests are subjected to the same origin policy; the request can not be successfully retrieve data from a different domain, subdomain, port, or protocol.
But you can build a script on your server that requests that content or can use a proxy, then use jQuery ajax to hit the script on your server.
Working Fiddle
It's just proxying a request through Yahoo's servers and getting back a JSONP response even if the requested server doesn't support JSONP.
HTML:
<div id="example"></div>
JavaScript
$('#example').load('http://wikipedia.org');
Here is a similar question like yours Ways to circumvent the same-origin policy?
good luck!
You can easily set up node server that gets the content of the page, and then make an ajax request to your server and get whatever data you need.

Header using with Javascript and PHP

I am developing an application. For the security reasons I used json ajax calls with GET method.
First I would like to ask first thing is that is there any way to hide my data which send in AJAX JSON request, I want to protect it from Hacking.
Secondly I am using headers with my PHP function files. Header are :
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Method: GET");
header("Access-Control-Max-Age: 100");
Any one tell me these headers are okey and safe for AJAX CALLS?
What I understand is that you want to prevent yourself from a man in the middle hack or any sniffing of your network traffic,
if so you need to configure your website to be accessed via HTTPS.

Javascript Instagram API showing answer in browser but not in JS

I'm just writing a little Instagram app. In a fact when I try to get response from this url in JS :
https://api.instagram.com/v1/tags/search?q=money&client_id=f40dfb17ddd144598d562a6f58179006
but for some reason I dont get an answer and no error at all. If I call the url in my Browser I got a JSON formated answer.
Here my fiddle
http://jsfiddle.net/XQ28k/
Since you are planning to do a cross domain request, you should try the JSONP variant of the API by adding &callback=? to the end of the URL
https://api.instagram.com/v1/tags/search?q=money&client_id=f40dfb17ddd144598d562a6f58179006&callback=?
You cannot access a different domain from your current domain (where you make the ajax call).
It will give you cross origin error
Ajax calls only works on the same domain!
A workaround for this is to call a page in your server that this page will make the remote call to Instagram servers and make an ajax call to this page:
php example - in your server page.php:
$url = 'https://api.instagram.com/v1/tags/search?q=money&client_id=f40dfb17ddd144598d562a6f58179006';
$content = file_get_contents($url);
echo($content); //no need to json_encode cause the response returning a json already!
and in your client side code just call to page.php (which is in your server - so it's the same domain):
$.getJSON("page.php",function(json){
alert(json.data);
});

Cross-Site Ajax Call

I am able to execute a web service through the browser but when I try and execute it through xmlhttprequest in javascript I get this error: Origin [] is not allowed by Access-Control-Allow-Origin.
How can I call the webservice through javascript? I'd prefer not to use a framework and just use basic client-side javascript.
For reference this is an instance of the web service I'm trying to consume: http://musicbrainz.org/ws/1/track/?type=xml&query=track:alive
Thanks.
Not possible. You can't have an AJAX call to a different domain. It would need to be done by the server.
You cannot use XMLHttpRequest on a page hosted at one domain to retrieve information from another domain. The browser simply won't allow it.
One common workaround is quite reliable if you have some control over the resource you're retrieving. It's called "JSONP" and the technique is to simply append a <script> tag to the header (dynamically, using JavaScript). That script can of course be hosted on any domain, so there's no cross-site scripting restrictions. If the script were to consist simply of JSON data, it wouldn't do much good. But wrap that JSON data in a function call — a function you control on your side — and it works great.
someFunctionName( { ... } );
If the resource you're retrieving doesn't support JSONP, your only recourse is to write a script on your own server (hosted on the same domain as the page, of course) that retrieves the target data. You can then make a normal AJAX call to your own script.
XmlHttpRequest is for requests for the same domain - it is called "Same origin policy".
If you want to do cross-domain ajax request you have to use jsonp format.
I do not think that using plain JavaScript is good idea - much better solution
is ready-to-use framework e.g. jQuery or Mootools.
In jQuery you have got method $.getJSON to making simple JSON and JSONP requests.
More read about:
How exactly is the same-domain policy enforced?
http://api.jquery.com/jQuery.getJSON/
http://en.wikipedia.org/wiki/JSON#JSONP
NOT Possible, but you can create a proxy on your server, and access the data through the proxy:
Here is a proxy example in PHP:
proxy.php
<?php
//header('Content-type: text/xml');
$url = 'http://musicbrainz.org/ws/1/track/?type=xml&query=track:alivehttp://www.example.com/';
$xml = file_get_contents($url);
echo xml;
?>
You can now use proxy.php as your source url from javascript.

Categories

Resources