I'm trying to get the output of a webpage and I found that jQuery has a method for doing this through the $.get method.
From the link above, I found the following example code:
$.get('ajax/test.html', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
I modified the example code to the following:
$.get('http://www.google.com', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
But it doesn't work. See it here: http://jsfiddle.net/6WQqD/1/
What am I doing wrong? How can I make a simple HTTP request that outputs the content of the page?
Same origin policy:
In computing, the same origin policy is an important security concept for a number of browser-side programming languages, such as JavaScript. The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites.
For cross-domain request you can use one of the following approaches:
1 JSONP
It requires the server part supports jsonp (contains specific code for crossdomain requests).
For GET requests try use dataType = jsonp in ajax settings:
$.ajax({
url: "other-domain-url",
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
jsonpCallback:'callback',
cache: false
});
You should specify callback function to be executing after the response is retrieved. Response will be passed as a parameter.
2 Use transparently proxy on the server part of your site. Configurate proxy (e.g. nginx) to redirect necessary local requests to other domain.
So in js you will use local ajax:
$.ajax({
url: "/local",
type: 'GET'
}
and in config you should use proxy settings:
location /local {
proxy_pass http://other-domain-url
}
Related
When I test the code below it only fails
Any Ideas? The link works fine
$.ajax({
url: 'http://ulacit3352.cloudapp.net/Login/webresources/generic/search/gera',
type: 'GET',
datatype: 'json',
success: function(data) {
alert("works")
},
error: function() {
alert("it does not");
}
});
I get this on Chrome:
The response of the link is not of type "json", instead, it is a plain text, therefore it cannot be parsed. You should change to
dataType: 'text',
Also, for normal ajax, you need to make sure the url is in the same domain of the webpage, which means the code should reside at http://ulacit3352.cloudapp.net/ as well. Otherwise, you should seek for "jsonp" or (better) some server-side solution, such as setting Access-Control-Allow-Origin or make your server as a proxy of the request.
The requested url is server on http which will give rise to This request has been blocked; the content must be served over HTTPS error since the connection is open for eavesdropping and man-in-the-middle (MITM) attacks. It is better to use https provided the url accept https request.
Still there is way to bypass the issue. You can check this LINK
It could be I have completely misunderstood how web services work.
So there's a webservice I want to access through a javascript file sitting in a folder on my desktop. The server I am trying to access has not set a CORS header, so I have some trouble just using regular ol' ajax.
And frankly I am not sure where to go from here.
$.ajax({
type:"get",
crossdomain: "true",
url: "https://name", //actual name redacted from this question
success: function(data){
console.log(data);
}
});
A regular get like this will print the following in firefox's console.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://ws.zooom.no/v1/channels. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
I got a hint from the task giver that I need to set the following in my "hosts file"
#127.0.0.1 www.domainname.com
Which confuses me. I have little to no experiences hosting anything, but does this hint that I need to maybe virtually host my "webpage" to access the webservice? It probably doesn't help to say I feel at a loss here.
So the bad news is that unless the 3rd party service either allows cross-domain requests (this is a configuration on that 3rd party server), or allows JSONP requests, you really have no option to access this service using a browser and javascript.
You could perhaps build your own service to proxy requests to that third party service. This would give you control over domain, CORS, JSONP, etc.
I found a solution.
Using something called "JSONP" that I had never heard of until now, i wrote a request like this
$.ajax({
type: 'GET',
url: "https://DOMAINNAME.com",
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
console.log(data)
},
error: function(e) {
console.log(e.message);
}
});
This somehow completely negated the CORS problems
I am trying to call a resource from a server using REST, the Restful Service is on another server.
When i run the script below i get XMLHttpRequest cannot load file:///C:/xampp/htdocs/Rest_Client/application/views/www.creadevz.com/Restful_Server/index.php/api/Example/users/. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
<script>
document.write('Started');
jQuery.ajax({
type: "GET",
url: "www.creadevz.com/Restful_Server/index.php/api/Example/users/",
dataType: "json",
crossDomain: true,
success: function(html){
document.write('success');
document.write(html);
}
});
</script>
I have 2 Questions:
1- Why did it append file:///c:/xampp/htdocs/Rest_Client/application/views
2- how to over come the cross domain resource access restrictions.
Extra information:
1- I am using CodeIgniter with Philip Sturgeon's REST server.
2- I followed the Philip Sturgeon's tutorial and used the Example api supplied with the framework
3- I used hurl.it to test the api and it worked fine.
Solutions I have found:
1- CORS
2- JSONP
Most opinions online suggest CORS over JSONP but i am not sure how to implement it in an efficient way, also since hurl.it called the api perfectly there must be a way they are over coming the cross domain resource access restrictions without the CORS Headers.
Thanks in Advance for your help
Edit:
I failed to mention that this is done with the purpose of using it with Phonegap
In an attempt to use the CORS Headers efficiently i added it at the start of the response function in Rest_Controller.php
To answer you first question
please correct is url ,it shoud have "http://" now your code will look like this .
<script>
document.write('Started');
jQuery.ajax({
type: "GET",
url: "http://www.creadevz.com/Restful_Server/index.php/api/Example/users/",
dataType: "json",
crossDomain: true,
success: function(html){
document.write('success');
document.write(html);
}
});
</script>
This will now not append append file:///c:/xampp/htdocs/Rest_Client/application/views
It's simple, if you are working on chrome, you can install this plugin , it works for me. I hope that works for you.
Good luck
Strictly using Javascript, is it possible to call a remote URL and store it in a variable? To specify, this would not be on the same domain. Basically, what i am trying to figure out the best solution for scraping/parsing data in a chrome extension.
If you're trying to load the page from an external domain, you'll run into the same-origin policy. You can get around this limitation by setting up a simple proxy on your own site. This would be a bit of server-side code whose function is to make the http request to the external page on your behalf, retrieve the response, then serve that content back to the on-page asynchronous JavaScript code making the original request.
So if you set up your proxy at /your_internal_proxy.foo, and you're using jQuery, you could build a JS function something like this:
var foreignContent = {};
var loadPage = function(pageURL,varName) {
$.ajax({
type: 'get',
url: '/your_internal_proxy.foo',
data: {
url_to_get: pageURL
},
success: function(result) {
foreignContent[varName] = do_something_to( result );
}
});
};
Then, to load content into JS variables:
loadPage('http://www.google.com/','goog');
loadPage('http://stackoverflow.com','stack');
While Ajax may be the way to go it depends on what you mean by "remote URL". Ajax will only work for url's with the same domain as the domain where the javascript originated from, due to Javascript cross-domain restrictions. There are various work arounds but most require the co-operation of the remote domain. I've have heard of using YQL as an intermediary but have never tried it. Easiest is to host a proxy on your own server.
If you are allowed to use jQuery you can have something like:
$.ajax({
url: url,
data: data,
success: success,
dataType: dataType
});
Also the $.get() can be used to achieve this
http://api.jquery.com/jQuery.get/
$.get("test.html",
function(data){
// do something with response data
});
I'm horrible at Javascript, so sorry in advance for what I'm going to go ahead and assume is an amazingly stupid question.
I'm simply trying to perform a GET request to GitHub's public repo API for a given user, and return the value as JSON.
Here's the function I'm trying to use:
function get_github_public_repos(username) {
var the_url = "http://github.com/api/v2/json/repos/show/" + username
$.ajax({
url: the_url,
dataType: 'json',
type: 'get',
success: function(data) {
alert('raw data: ' + data)
var json_response = $.parseJSON(data);
alert(json_response);
}
});
}
This is returning Null for data. And in the console, I see Failed to load resource: cancelled. I know the URL is correct, because if I run curl on the url, it returns the expected data.
jQuery's ajax function supports JSONP which allows cross-domain requests (which you need because you're trying to request data from github.com from another domain). Just change the dataType from 'json' to 'jsonp';
function get_github_public_repos(username) {
var the_url = "http://github.com/api/v2/json/repos/show/" + username
$.ajax({
url: the_url,
dataType: 'jsonp',
type: 'get',
success: function(data) {
var json_response = data;
alert(data);
}
});
}
UPDATE: It's import to note that the end pint (in this case github.com's API) has to support JSONP for this to work. It's not a guarnateed solution for ANY cross-domain request as pointed out in the comments.
JavaScript is subject to cross-domain restrictions when making requests on a different server.
Well, unless you run your code in the github.com domain, that won't work.
You can use simle ajax only in your domain.
One solution is to create a proxy for it. Make a page on your server that does one thing, gets your requested (out of domain) content with curl, and prints it. Then you call this proxy with ajax.
The XmlHttpRequest object (which $ajax uses) cannot download content from a different domain due to the same origin policy. You would need to use something such as JSONP to be able to do this from a browser.
As the others have said, you cannot execute ajax on a remote domain.
You will need to write a server sided script on your domain (such as php), that will do the dirty work retrieving the information needed from the github domain.
Then, use your ajax to query your server side script for the information.
I know the URL is correct, because if
I run curl on the url, it returns the
expected data.
Use that idea to get your ajax working. Create a proxy page on your site that uses curl to retrieve the data you want, then have your "the_url" variable point to that page on your site. Cross-domain restrictions prevent you from being able to use ajax in the manner you attempted.