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.
Related
I have this kind of problem, I have iframes with videos embedded into my pages of the website. Note, that iframes urls are from another domain. From time to time these urls can be broken, or stop working and instead of the video there is a message "This video has been removed from public access. ". Is there any way that I can delete those "failed" iframes from the pages by jquery or just javascript.
I was thinking I could be able to search for text inside iframes similar t
$("iframe").each(function() {
var val = $(this).is(':contains("video has been")');
console.log(val); // returns false
});
and then remove those, but it returns false, afa I understood from the http://en.wikipedia.org/wiki/Same-origin_policy.
Also, if it matters, I found out that the difference(without having the above text) between working and broken iframe, is that the last one does not contain object node.
Is there any method to handle this problem ?
Thanks
Due to Same Origin Policy, the browser will prevent all AJAX to different domains and direct access of iframes of different domain. However, there are ways to bypass this limit. One way is to let a server to fetch the data, then return back the data to the client. Here is one plugin for jQuery that does this. It uses YQL (Yahoo Query Language) as a proxy.
Just make a normal GET request with .ajax and the plugin will handle of the details for you:
$.ajax({
url: [url of the iframe],
type: "GET",
success: function(data){
$(data.responseText); //do something with it
}
});
http://jsfiddle.net/DerekL/HGHJ5/
Of course, if you don't trust Yahoo of handling the data, you can always host one yourself.
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 11 years ago.
Possible Duplicate:
"CSRF token missing or incorrect" while post parameter via AJAX in Django
I wanted to send login data by AJAX to authenticate user, but it wasn't possible because of CSRF. Could You tell me what to add to my code to make it woking?
my JavaScript file:
$("#login").live("click", function() {
var username = $(".login_username").val();
var password = $(".login_password").val();
$.ajax({
url: "/login",
type: "POST",
data: {
username: username,
password: password
},
cache: false,
success: function(tekst) {
alert(tekst);
}
});
});
There is a method explained here.
It consists of adding a X-CSRFToken header on each ajax request.
This is done by hooking in the jQuery.ajaxSend event, so everything is done automatically (you just have to copy and past their code, and run it once before the first ajax request you make).
I've been trying to solve the same problem, And as arnaud576875 says you have to Add the csrf token header on each ajax request just like the Django docs says https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax And execute that code before any Ajax request you make.
But there is something additional, you have to find a way to load the csrf token to the cookies of your app before trying to do any AJAX request, after a lot of painful hours researching I couldn't find an specific answer of how to do this, what I did found is that to ensure that your view sends the csrf token within a cookie you can use the ensure_csrf_token() to each view you want to receive the token https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#django.views.decorators.csrf.ensure_csrf_cookie this seems to work for a lot of people, but did not worked for me.
Another way is using the Legacy Method, adding the 'django.middleware.csrf.CsrfResponseMiddleware' to your MIDDLEWARE_CLASSES but I don't recommend this method because leaves several security risks.
https://docs.djangoproject.com/en/1.2/ref/contrib/csrf/#legacy-method
All this methods that I said before did not worked for me. The way that I'm allowing Ajax to do some requests is as the following, and if someone finds this a dangerous method please let me know:
Go to the first view that your user will hit, like the /home/ page.
Insert this before redirecting or parsing anything
request.META["CSRF_COOKIE_USED"] = True
And that's it, That is the way that works for me, but as I said before I'm not sure if this is the right method or the most secure one to accomplish the csrf protection.
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");
}
//...