I want to get a short string hosted on a server where I do not have access to the data as XML, JSON, etc. I am trying to use either .load or .ajax to do this. I want to be able to parse the data into a javascipt array. The entire contents of the remote page is text and I am happy to take all of it and remove what I do not need via a small javascript. I have tried:
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url:"http://url:8888/data", success:function(result){
$("div").html(result);
}});
});});
</script>
I have two questions.
1- why does this not work?
2- What would be the best way to store the string in a javascript var?
I am sure JQuery is working correctly.
The answer would be to long to post here (really). But look those up:
Same Origin Policy
Padded JSON
If you have no control over the remote site, you have lost - you will not get any data from it by Ajax (which is actually a feature, not a limitation of the technology). One way of circumventing the protection would be to build a proxy that just mirrors the remote service you need to reach and makes it available in the same domain that your main HTML came from.
Related
I am trying to retrieve data from an XML file that is not located on my site's server, and then use that data fro various things, such as charts. Here is one example: http://forecast.weather.gov/MapClick.php?lat=40.78158&lon=-73.96648&FcstType=dwml. This is an XML file with the weather data for central park. I want to retrieve the data that is in the <value>tag, which is in the <pressure> tag, so I can create a graph with barometric pressure. I would prefer to do this with JavaScript, but I don't think it's possible to do so when the file isn't on my server.
Note: I do not want a different solution to retrieve the pressure data from somewhere else, because I want to retrieve other pieces of data from other XML files as well.
There's an interesting article about using Yahoo! Pipes to transform Xml weather data to JSON and use the result in a web page without need for any server side stuff (PHP, curl, etc.).
EDIT
Being new to jQuery myself, I a had to dig a little more to find out that (almost) everything described in the first article can be condensed down to
$.getJSON("<your Yahoo pipes url here>&_callback=?", function (data) {
alert(data.value.items[0].data[0].parameters.wordedForecast.text[0]);
});
using jQuerys builtin JSONP.
Pitfall!
Beware that Yahoo expects the callback url param to be named _callback
Nice summary on Cross-domain communications with JSONP which helped a lot to come up with this answer.
If your javascript code is on a server (as opposed to a mobile device), have PHP code load the xml, escape it and insert it into the HTML page. Then you just have to grab that in your code and process it with DOMParser.
You could use curl to pull the data to your server and act on it from there.
curl -o data.txt "http://forecast.weather.gov/MapClick.php?lat=40.78158&lon=-73.96648&FcstType=dwml"
This will give you the information in a file called data.txt. You could then either parse it server side and then just give the bits of data needed, or make the whole file available to your client, since they are both now in the same domain.
I'm hosting a page on an sharepoint site, and need to pull content from multiple other pages. The content I need is on a different domain in a div, so I cannot use an iFrame. I've tried the following code with JQuery attempting to load the stcakoverflow container div from the landing page, but this doesn't seem to work. I'm assuming this is due to different origin policy:
<script>
$(document).ready(function() {
$('#LoadMe').load("http://www.stackoverflow.com#container");
});
</script>
Is there a way to do this through Jquery, or is there an alternate solution?
If you can encode the other domain's data in JSON, you can do cross-domain requests using JSONP requests. This of course requires that you are able to change or request a different type of encoding from the other domains so if that's not under your control this approach is not possible.
No, you can't just load up another page (or a piece of it) like that with Javascript. You would need to do it on the backend via PHP, .NET, or some other server-side scripting language, then pass the results to your page.
You can also get the content of the page that you need and parse it with regexp or as above was said Nate B, Write some type of code for example Rss Feed, Pass content with json, create some web service and etc
Is it possible to:
From within my webpage, get all the HTML source from another webpage. I need to do this in order to pass that other pages html source to my function.
The following different attempts don't work:
var html = $.get("http://simplyrecipes.com/recipes/braised_turkey_legs/").html();
var html = $.get("http://simplyrecipes.com/recipes/braised_turkey_legs/");
var html = $("http://simplyrecipes.com/recipes/braised_turkey_legs/").html();
Using Ajax, and get is just a shortcut for ajax, it's not really possible to get the source html from other domains, if that is what your trying to do? as ajax has a same origin policy for security reasons.
However going thru YQL it is possible to do is, read this to see how, or you could proxy with php or something else, with just regular get requests however it's not doable.
If the pages you are trying to get are on your domain, .load(); would probably be better.
Javascript has a same origin policy, this is what's holding you back.
jQuery's get function does not return the loaded data - rather, it calls a callback function and passes the data as a parameter.
This is from the documentation:
$.get('ajax/test.html', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
P.S.: Note that in any case this will only work on the same domain, as cross-domain AJAX is normally not supported for security reasons.
I'm trying to load an external page using JSONP, but the page is an HTML page, I just want to grab the contents of it using ajax.
EDIT: The reason why I'm doing this is because I want to pass all the user information ex: headers, ip, agent, when loading the page rather than my servers.
Is this doable? Right now, I can get the page, but jsonp attempts to parse the json, returning an error: Uncaught SyntaxError: Unexpected token <
Sample code:
$.post('http://example.com',function(data){
$('.results').html(data);
},'jsonp');
I've set up a jsfiddle for people to test with:
http://jsfiddle.net/8A63A/1/
http://en.wikipedia.org/wiki/JSONP#Script_element_injection
Making a JSONP call (in other words, to employ this usage pattern),
requires a script element. Therefore, for each new JSONP request, the
browser must add (or reuse) a new element—in other words,
inject the element—into the HTML DOM, with the desired value for the
"src" attribute. This element is then evaluated, the src URL is
retrieved, and the response JSON is evaluated.
Now look at your error:
Uncaught SyntaxError: Unexpected token <
< is the first character of any html tag, probably this is the start of <DOCTYPE, in this case, which is, of course, invalid JavaScript.
And NO, you can't use JSONP for fetching html data.
I have done what you want but in my case I have control of the server side code that returns the HTML.
So, what I did was wrapped the HTML code in one of the Json properties of the returned object and used it at client side, something like:
callback({"page": "<html>...</html>"})
The Syntax error you are facing it's because the library you're using expects json but the response is HTML, just that.
I've got three words for you: Same Origin Policy
Unless the remote URL actually supports proper JSONP requests, you won't be able to do what you're trying to. And that's a good thing.
Edit: You could of course try to proxy the request through your server …
If you really just want to employ the client to snag an HTML file, I suggest using flyJSONP - which uses YQL.. or use jankyPOST which uses some sweet techniques:
jankyPOST creates a hidden iframe and stuffs it with a form (iframe[0].contentWindow.document.body.form.name).
Then it uses HTML5 (watch legacy browsers!) webMessaging API to post to the other iframe and sets iframe's form elements' vals to what u specified.
Submits form to remote server...done.
Or you could just use PHP curl, parse it, echo it, so on.
IDK if what exactly ur using it for but I hope this helps.
ALSO...
I'm pretty sure you can JSONP anything that is an output from server code. I did this with ClientLogin by just JSONPing their keyGen page and successfully consoleLogged the text even though it was b/w tags. I had some other errors on that but point is that I scraped that output.
Currently, I'm trying to do what you are so I'll post back if successful.
I don't think this is possible. JSONP requires that the response is rendered properly.
If you want another solution, what about loading the url in an iframe and trying to talk through the iframe. I'm not 100% positive it will work, but it's worth a shot.
First, call the AJAX URL manually and see of the resulting HTML makes sense.
Second, you need to close your DIV in your fiddle example.
I saw here similar questions but I didn't find any answer about Javascript.
I'm building a web site (lets call it 'A'), and I want to get content from another web site ('B') that requires a user-name and password.
I want a function at my site that get the content from a certain page at B. I'm always login manually to site B at my computer so I don't need the function to do the login (so I link it directly to the correct page of the info at B).
A and B are not in the same domain. Is there a way in Javascript to get content from B?
You need a cross-doman AJAX call (normally prevented by the same origin policy). jQuery has a handy helper function for this that will return JSON data called $.getJson()
$.getJSON('http://otherdomain/ajax/test.json', function(data) {
if (undefined != data) {
console.log(data);
}
});
This exploits a technique known as JSONP, which writes Javascript directly into the document to make the request (instead of using the XMLHttpRequest object), bypassing the same origin policy.
What I like to do is use YQL (Yahoo Query Language)
It's like an api for api's. I get whatever html I want using selectors and process that.
For example, I can grab all the images from this wikipedia link using a query like
SELECT * FROM html WHERE url="http://en.wikipedia.org/wiki/List_of_United_States_National_Parks_by_state" AND xpath="//img" and then processing the returned XML/JSON
you can test queries HERE
and see an example of grabbing and processing the images in this Fiddle
No there is no way to get content from external B page using pure javascript, but you can try to use php curl or file_get_contents