I have a situation where I need to get data from an HTML file existing in another server. It will contain simply plain text content and nothing else. I don't have access to change anything there nor I can get any structured html. What I have is only text content stored in an HTML which is hosted in http://host1.demoserver.com.
Now, from my application which is hosted in http://host2.demoserver.com, I need to get the content through an ajax call. Problem is without implementing CORS. So, upto to my knowledge level I have an option JSONP. But, when I make ajax call with JSONP, I can see the response in Firebug, but it starts throwing javascript exception. There reason that comes into my mind(may be I am not correct) is that, since the content comes as callback parameter it contains undefined variables.
HTML file: copyright-info.html
This is a simple copyright info which needs to be rendered.
And, if we make a call with ajax call:
$.ajax({
url: "http://host1.server.com/static/copyright-info.html?callback=?",
method: "GET",
dataType: "jsonp",
jsonpCallback: "callback",
callback: function(result) {
//code to excute after success
}
});
Then, response would be like:
callback(This is a simple copyright info which needs to be rendered.)
And, as parameter is not in double quotes its not recognizing it and throwing exception.
2nd, this whole thing was working without JSONP, when it was in localhost. And, I guess, http://host1.demoserver.com will be same localhost as it is for http://host2.demoserver.com. But, when it is deployed in server its failing.
Can anyone suggest what's wrong here? Or, any other way for implementing this.
Thanks in advance.
Related
I am trying to get a value from this URL (returns pure XML):
http://demo.piwik.org/?module=API&method=VisitsSummary.getUniqueVisitors&idSite=7&period=day&date=today&format=xml&token_auth=anonymous
And I want to store this value in this element on a separate site:
<div id="result" style="color:red"></div>
Every javascript or jquery attempt I try results in some "access-control-origin" error, which I understand to a point but I can't do anything about the remote server. I need a quick front-end solution.
Note: There is another format I can return the data in - JSON. But I have had similar issues above in trying to get that data as well.
Because you are trying to make cross domain request and because server only allow jsonp for cross domain request, then use jsonp. For example:
$.ajax({
url: 'http://demo.piwik.org/?module=API&method=VisitsSummary.getUniqueVisitors&idSite=7&period=day&date=today&format=json&token_auth=anonymous',
dataType: 'jsonp'
}).done(function(data){
$('#result').html(data.value);
});
-jsFiddle-
Ok, after an whole day trying to get this to work I just don't seem to know what's the deal with this, so here it goes:
I have a WebService hosted locally by now (http://localhost:15021/Service1.svc/[whatever_method]) and an HTML Page on a different file.
FYI, both WebService and HTML Page will get hosted on different servers.
I'm trying to get some info off the WebService to the HTML Page by the onload=load() method in the HTML Page.
My JavaScript code is:
function load() {
alert("Loading...");
$.ajax({
url: 'http://localhost:15021/Service1.svc/getAllNoticias',
type:'GET',
dataType: 'jsonp',
jsonp: 'loadNews_callBack'
});
}
function loadNews_callBack(result){
alert(result.data);
}
Additionally, the JSONP is loaded on the Page with an OK (200) status (As you can see here) which should (I guess) call the callback function, but it isn't.
What can I do to get around this? I already change the request parameters 500 times (e.g., added "?callback=? to the url, with or without jsonp attribute, etc...)
Any help would be great,
Thanks in Advance
Check the actual response text to verify that the response is correctly being wrapped by the callback function. It is possible that your service is not setup correctly to handle JSONP so it simply responding with JSON. It will still come back as 200, but fail to execute.
loadNews_callBack([json...])
vs
[json...]
See this question as reference on how to go about updating your service:
ASP.net MVC returning JSONP
I'm pretty new to programming, and recently have been playing with Twitter API. From statuses/sample method, how would you read the content of following URL using Javascript?
https://stream.twitter.com/1/statuses/sample.json
Edit: perhaps I shall explain my intention. I'm trying to read the Twitter sample data, read the hashtags every 30 seconds, and then sort them ascendingly every 30 seconds the top 10 hashtags.
The problem is, I'm not even sure how to read the Twitter data in the first place..
Not looking for solutions, but definitely could use some ideas.. especially for getting started.
You should be able to utilize JSONP which is a special type of response back from the server.
It basically takes the response, wraps it in an anonymous function callback, and returns it to the client inside of a script tag thereby calling it when the response gets back to the browser.
$.ajax({
type: 'post',
dataType: 'jsonp',
url: 'http://twitter.com/status/user_timeline/msdn.json?count=10&callback=?',
success: function (data) {
console.log(data);
}
});
Inspecting the request url in Chrome's debugger you'll see the request...
https://twitter.com/status/user_timeline/msdn.json?count=10&callback=jQuery1706531336647458375_1335842234009&_=1335842234045
And the response back is...
jQuery1706531336647458375_1335842234009( /* data */ );
Then jQuery wraps the data in the script tag and appends it to the body.
Notice how the callback in the request matches the function call in the response.
Hope that helps!
You can't. Read up on cross site scripting.
Basically you're going to need to proxy your request through the hosting server.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Load website into DIV
Hey all i am trying to find a way to call an external website and retreve its HTML so that i can check for something in it (wither the user entered a valid VIN # or not depending on what this website calls back)
This is the code i have:
$.ajaxSetup ({
cache: false
});
$("#load_callback").click(function(){
$.ajax({
url: 'http://www.google.com',
dataType: 'text',
success: function(data) {
alert(data);
}
});
});
It works but only if i have it pointed to my server (and running on my server also). Is there a way i can call an external website using jquery/ajax? I am aware of the Same origin policy but was hoping something like what i want to do did not fall into that catagory?
I cant even get an iFrames title? Really??? wow....
David
You need to use jsonp: http://en.wikipedia.org/wiki/JSON#JSONP
These links should explain it:
http://www.remysharp.com/2007/10/08/what-is-jsonp
http://www.ibm.com/developerworks/library/wa-aj-jsonp1-
The other option you have is to write your own server-side proxy to it, i.e. have a page/controller/handler on your server that passes your request through and returns the result. It won't be as fast as going direct, and it will increase your site's traffic, but it will get you around the security problem.
Stick to simple things, if you want to load websites, be simple and go with iframe. If you want to make request use PHP or similar. For example you can use curl method to make request to another websites through PHP. Or even simpler, setup a form to request to another web server.
I've written some HTML/Javascript that sits on a third-party server for security reasons. This page performs a javascript post to another page on the same site. However, instead of responding with useful data, it instead wants to perform a redirect (if you would post via a normal HTML form to this page, it would redirect your browser). How can I process this process? I basically want to be able to extract the url's query parameters that it is trying to redirect with (and then put this link into a hidden form field).
Here is my basic ajax post...
$.ajax({
url: '/someurl/idontcontrol',
data: serialized_form_data,
async: false,
type: 'POST',
success: function(data, textStatus, x) {
alert(x);
alert(x.getAllResponseHeaders());
return false;
$('#redirect_link').val(WHAT_DO_I_PUT_HERE);
}
});
Note that the URL I am posting to is not one that I control, so I have no power over what it returns.
UPDATE: When I use the above alerts, I receive "[object XMLHttpRequest]" and "null". I'm monitoring the headers with a Firefox plugin and they seem be coming back as expected, but I can't seem to access them via javascript (I've also tried x.getResponseHeader('Location'), but that and all other calls to getResponseHeader return empty).
ALSO: I don't know if it matters, but the status code is 302 (as opposed to 301 or 303).
Thanks!
According to the jQuery Documentation the success method can take a third argument which is the XMLHttpRequest object.
According to Mozilla's XMLHttpRequest page, this object should have a "status" property. If you check the value of this property, and it is a redirect code, such as 301 (permanent redirect) or 303 (temporary redirect) it is known the processing page is trying to perform a redirect. The "statusText" property should be able to be used to determine the location it is trying to redirect you to.
If you know it is trying to redirect, you can then re-post the data through Ajax to the new URL.
The strange thing is though, when researching this, stumbled across this page that indicates the XMLHttpRequest object should follow redirects (see the comments). So it seems like this would be a non-issue.
Unless the processing page is using an HTML meta redirect (like below) to do the redirection. In that case, I'm not sure what could be done - maybe try to parse the returned HTML for meta tags and see if any of them are attempting a redirect.
<meta http-equiv="refresh" content="0;url=http://www.example.com/some-redirected-page">
You can't get the full HTTP headers from an AJAX call in JQUery, so you can't process the redirect in this way.
However with a raw javascript request you do have access to the XMLHttpRequest getAllResponseHeaders() method which will allow you to process the redirect (this function for single headers).
Sorry, not directly an answer to your question, but I'm sure it's possible with jQuery too as it's quite simple with Prototype.
// Warning: this is Prototype, not jQuery ;-)
//...
onComplete: function(response) {
var refresh = response.getResponseHeader("Refresh");
var whatever = response.getResponseHeader("Whatever");
}
//...