Cross-Site Ajax Call - javascript

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.

Related

Parse image url from JSON api

I am having problems getting an image URL from a Wordpress JSON API and fill in an image tag.
Here's my non-working code:
$(document).ready(function() {
$.getJSON('http://interelgroup.com/api/get_post/?post_id=4683', {format: "json"}, function(data) {
$('#thumb').attr("src", data.post.thumbnail_images.full.url);
});
});
And the HTML is like:
<img id="thumb" src="#">
What am I doing wrong?
Help appreciated.
Thanks!
NOTE: My real case is dynamic (I am getting a dynamic list of post IDs and looping through them with $.each()), but for this case I am providing an example with an hardcoded post ID, so you can check the JSON returned.
Your problem is because you can't do cross request using Javascript, say websiteA.com wants to fetch information from websiteB.com with a plain XMLHttpRequest. That's forbidden by the Access Control.
A resource makes a cross-origin HTTP request when it requests a resource from a different domain than the one which served itself. For example, an HTML page served from http://domain-a.com makes an <img> src request for http://domain-b.com/image.jpg. Many pages on the web today load resources like CSS stylesheets, images and scripts from separate domains.
For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest follows the same-origin policy. So, a web application using XMLHttpRequest could only make HTTP requests to its own domain. To improve web applications, developers asked browser vendors to allow XMLHttpRequest to make cross-domain requests.
If you know the owner of the website you're trying to read, what you can do is asking them to add your domain to the whitelist in the page headers. If you do so, then you can do as much as $.getJSON as you want.
Another alternative could be using some sort of backend code to read that website and serve it locally. Say your website is example.com, you could have a PHP script that runs on example.com/retrieve.php where you can query that website, adding the "parameter" you need. After that, since example.com is your own website you can just do a $.getJSON to yourself. There's a simple PHP proxy you can use here with a bit of explanation on why you can do it this way.
A third option would be editing the Javascript code to use Yahoo! YQL service. Although there's no guarantee that'll work forever, you can use it to query the website on your behalf and then use it to print whatever you want to the screen. The downside is that this maybe is not ethically correct if you do not own the website you're trying to fetch (plus, they can add a robots.txt file preventing the access).
Hope that helps.
JSONP solves the problem. Just need to add a callback parameter and specify it is a JSONP, like:
$(document).ready(function() {
$.getJSON('http://interelgroup.com/api/get_post/?post_id=4683&callback=?', {format: "jsonp"}, function(data) {
$('#thumb').attr("src", data.post.thumbnail_images.full.url);
});
});
More info here: Changing getJSON to JSONP
Info on JSONP: https://en.wikipedia.org/wiki/JSONP

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.

Cross domain request with JSON response

I am trying cross domain request from my js file.
First,I was trying JSONP but my target domain URL is not support it. It return plain JSON object.
I am authorize person to access my target domain URL. but i can not modify it as per JSONP response.
SO how can i get JSON response from my target domain URL?
Without modifying a bit the server side there is not much you can do. The general policy is to not to allow cross domain requests.
There are few things worth mentioning though:
Try changing the server side so it will support JSONP.
If the HTTP response contains Access-Control-Allow-Origin header then you can communicate with it with normal AJAX. This feature is supported in modern browsers only. Check this out for more info.
You can do the cross domain requests with Flash and/or WebSockets. However server does have to support them.
I have always done it with jsonp, by passing a callback b/c services return json, if call back is passed then it will wrap all json in callback else they will simple return json.
But in your case
You can look up with this article
http://www.webdevdoor.com/jquery/cross-domain-browser-json-ajax/
Don't know what type application you are developing. But in ASP.NET you can do it by using a proxy page
These links may be helpful:
http://www.codeproject.com/Articles/667611/ASP-NET-Proxy-Page-Used-for-Cross-Domain-Requests
http://encosia.com/use-asp-nets-httphandler-to-bridge-the-cross-domain-gap/
https://gist.github.com/jkresner/3982746

jQuery cross domain image upload

Ok, so basically.
I inject some javascript code into a web page and it uploads an image on that page to another server.
Now I have it working when I run it on my domain (of course), but I need to post the multipart/form-data request to a PHP file that I do not own.
Since it is a upload and not a simple request to just get data, I cannot use jsonp in the initial call since the response would not be in json.
Using James Padolsey's cross domain script, I am able to do $.get and $.post request across domains, but since I am using $.ajax it does not work.
He uses the Yahoo Query Language to acomplish this
This is basically how I am making the request
$.ajax({
url: 'http://website.com/upload.php',
type: 'POST',
contentType:'multipart/form-data',
data: postData,
success: successCallback,
error : function(XMLHttpRequest, textStatus, errorThrown) {
console.log('Error');
}
});
I want to make it completely JavaScript based to avoid making my server do the request.
So to re-cap, I can get the image bytes and make the request with javascript. But so far I cannot make it cross domain since I am $.ajax to set the content Type to "multipart/form-data".
Is there another way to make the request cross domain with or without the YQL?
Making the request with an iframe will not work since the domain of the iframe would change and I would not have access to the response.
This is a well known and difficult problem for web development, know as the Same Origin Policy
Javascript prevents access to most methods and properties to pages across different origins. The term "origin" is defined using the domain name, application layer protocol, and (in most browsers) port number of the HTML document running the script. Two resources are considered to be of the same origin if and only if all these values are exactly the same.
There are several ways around this.
Create your own proxy
Create a page that simply forwards the request to the other server, and returns its response
or, Use Apache's rules to form a proxy (see above link)
Use someone else's proxy
For GET requests which are typical Use YQL to access yahoo's proxy
For POST requests, if the 3rd party supports Open Data Tables
or, Use some other public proxy
See if the 3rd party conforms to the CORS specification
Cross domain POST query using Cross-Origin Resource Sharing getting no data back
If you are willing to allow a little flash on your page, try flXHR
it claims to implement the exact XHR api and also has a jquery plugin
These are pretty much your only options

Help with getting Json Format data from external website

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 :)

Categories

Resources