The requirement of my application is to navigate to a cross domain page upon logging out. As probably CORS is not set(error: no Access-Control-Allow-Origin header is present) in the cross domain app, hence response.sendRedirect(url) is not working from JAVA side. Now, realizing this cross domain barrier I did some research in UI side, explored many posts in internet and tried the following to navigate to a cross domain page from UI but with no avail. With Angularjs-
$http.jsonp('https://www.google.co.in/');
With JQuery by including jquery.ajax-cross-origin.min.js-
$.ajax({crossOrigin: true,url: 'https://www.google.co.in/'});
In both cases it is giving error: SyntaxError: expected expression, got '<'.
It looks like it is not expecting '<>' tags, but I am expecting it not to return any response (JSON or XML) but to redirect me to some other domain page (ex: https://www.google.co.in/). Can anybody help me resolving this by giving me an workable code which navigates me to a cross domain page (say: https://www.google.co.in/).
instead of $.ajax({crossOrigin: true,url: 'https://www.google.co.in/'}); you have to use window.location.href='https://www.google.co.in/'
window.location.assign('url')
window.location='url'
window.location.href='url'
all of these will work for you
I tested with my below code it is working:
<script>
$.ajax({
type:"POST",
url: 'a.php?id=1',
success:function(d){
if(d){
window.location.href="http://www.google.com";
}
}
});
</script>
Related
I don't know if this is a duplicate post or not, sorry if it is. I'm using jquery.getJSON to load a json on my server which works just fine. Although, if I try and load a json file on a different server it doesn't work. I know I don't have any code here (because there's not much point) but I just want to know if I'm using it wrong or if it isn't supposed to load external files. I'm using the iOS Safari browser if that effects anything.
EDIT: I've looked at the console (idk what the error thing really means, it's just red with an x by the url it's trying to get the json from) and it looks like it's not actually receiving the data. Plus, do remember I'm on iOS, not desktop so I couldn't look at the console in the "Develop tab :P
EDIT 2: Great! I think I got it working! http://skitty.xyz/getJSON/
You're most likely encountering a path issue; the purpose of $.getJSON is to acquire data via http GET request so yes, it is intended to work remotely. To diagnose your issue, make certain you can access the json file in your browser first: http://domain.com/my_data.json. If that works, use that as the URL you pass into $.getJSON:
$.getJSON( 'http://domain.com/my_data.json', function(data) {
// do something with your data
});
http://api.jquery.com/jquery.getjson/
jquery.getJSON uses ajax which is all about external resources. Here's a couple things to check for if it's not working on an external resource:
1: Is the path you specified correct? The usage is jquery.getJSON(path, callback). The path should be something you can just drop in your browser and see. If an incorrect path is your problem, you'll see a 404 in the console.
2: Is the resource http and your site https? Non-secure resources on secure pages will get blocked by browser security features. You'd see a error to this effect in the console.
3: Is CORS (Cross-origin resource sharing) enabled for your site on the external resource? Servers will sometimes use a whitelist of IPs and domains to determine what origins are allowed to make requests of it. You'd also see an error to this effect in the console.
There probably some other things to look for but this is where I'd start.
Also, by all means, use the debugging features of Safari to LQQK at the actual HTTP data-streams that are passing back-and-forth in response to what you're doing. (You might need to click on a preference to see the "Develop" menu, which will take you to "Show Web Inspector" and its Network tab.)
This approach will instantly answer many questions that a JavaScript-centered approach will not so-readily tell you. (And of course, you can look at the JavaScript console too ... and at the same time.) "The actual data streams, please." Safari will tell you "exactly what bytes" your app actually sent to the server, and "exactly what bytes" the server sent in return. "Priceless!™"
Are you saying you are using jquery ajax request to load some json data from a server?
check the "not working server" has the same end point as your server.
Check if the url you want to get data from is correct.
check if console logged any errors.
Also quote from http://api.jquery.com/jquery.getjson/
"Additional Notes:
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.
Script and JSONP requests are not subject to the same origin policy restrictions."
I looked for an answer to my problem everywhere but I didn't found what I want to know.
Here is what I want to do:
I have an url of an image, pdf or html page from the same domain and from other domains too. Is it possible to "download" them with AJAX?
But I don't want to have them physically on my server or anywhere else, I just want to use them directly on my website without having to upload them again (to save time).
I'm also having some troubles doing "XMLHttpRequest.getAllResponseHeaders()" when the content comes from an other domain. I tried with multiples url. I received nothing: "". Is it normal?
Thank you for your help ! :)
Unfortunately it is impossible to make AJAX requests for resources on domains external to the website's host domain, edit: unless they implement a workaround, like CORS or JSONP. I recommend doing some reading on Cross Origin Resource Sharing for more details.
As for resources on the same domain, you'd be storing those on your server anyway - you'd have to, in fact, because by its very nature it would be a part of your site. If you describe what you're trying to implement specifically (perhaps post a jsfiddle with your code), we could find a solution to your specific use case. Hope this helps.
[...] image, pdf or html page [...]
The types of these requests are very different. What you mean with 'download' is a little ambigious. If you're requesting a file via AJAX, this loads the value into a variable. It doesn't save the file to your computer.
[...] I received nothing: "" Is it normal? [...]
Yes, if the remote server isn't the same as you're currently on (also the same port) and also doesn't support CORS (cross-domain requests), the result will be blank.
If it's not possible to alter the remote server's cross-domain policies [and you have the permission to use their services], you could write a PHP script on your server that acts as a proxy. But don't forget to secure it to prevent mis-use. Also keep in mind that such a script can raise your traffic dramatically, so this should only be "Plan B".
You certainly can fetch images and html pages with AJAX and display them on your webpages.
The issues you are having with the xmlHttpRequest.GetAllResponseHeaders is most likely caused by the same origin policy. The browser prohibits you from interacting with the loaded data from another domain.
The server you are fetching the data from has to explicitly indicate that it allows your domain to fetch and display his resources by setting the Access-Control-Allow-Origin response header to that of your domain.
A way arround this is by using a proxy and setting the header yourself.
The following boilerplate code ( basically taken from the jquery api page ) loads your gravatar image ( delivered in png format ) from the stackoverflow website into a callback parameter. As others have noted, the same origin policy applies to ajax requests ( The sample code therefore can onlybe successfully run from the stackoverflow site context, eg. by opening a js console on this page ).
$.ajax({
method: "GET"
, url: "https://www.gravatar.com/avatar/d85e0ad5243245aabe2d34a3c9a296a9?s=32&d=identicon&r=PG&f=1"
, cache: false
, beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
}
})
.done(function( data ) {
if ( console && console.log ) {
console.log( "Length of data:", data.length );
console.log( "Sample of data:", data.slice( 0, 100 ) );
}
});
I am trying to get the contents of http://en.wikipedia.org through an ajax call. For this, I am using jQuery. Here is the code:
jQuery.ajax({
url:"http://en.wikipedia.org",
crossDomain: true,
dataType: "jsonp",
jsonpCallback: "myCallback"
});
function myCallBack(data){
console.log("ok");
}
The problem is that I get in Firebug this error:
SyntaxError: syntax error
<!DOCTYPE html>
So I would say that the html content is fetched, although the callback function is not run. At some point it encounters the specified tag, throws this error and stops running the script.
Do you have any idea where the problem might lie?
Is there any other way to get the contents of a html page? I do not want to use iframes, because that means I will not be able to use or modify its contents.
Its because you're Ajax function expects a json response from the provided url and it gives an html response, thats the reason you are getting a syntax error, the same error you will get from the Chrome debugger as well.
Updated:
What you're trying to do is called a Cross-Domain Request.
"For security reasons scripts aren't able to access content from other domains. Mozilla has a long article about HTTP access control, but the bottom line is that without the website themselves adding support for cross-domain requests, you're screwed."
Reference
Solution:
You can resolve this issue by having a backend script which will the external pages for you. Like a proxy server, which resides the same domain, so you wont have to face the Cross domain issues.
And you can load them, by
$.get(url, success: function(data) { // the url that will fetch the external html page for you, located on the same domain
console.log("ok");
});
Your issue your having here is that you are calling across domains. Allthough you seem to have realised this and are using jsonp for your request, the document you are trying to pull ie wikepedia is not a jsonp document. So as soon as the ajax finds the html tags it will throw an arror, as you have defined that you are expecting a jsonp response.
You cannot just pull other websites data across domain with javascript due to the cross domain issues, if you want to accomplish what you are doing here you will need to use a back end language to get the data.
Usefull link is http://json-p.org/
Hope that helps
I am building an AJAX application to query an OData endpoint. I've been doing some testing with the Netflix OData feed and found something I don't get:
When I make an .ajax() request to a url (e.g. http://odata.netflix.com/v1/Catalog/Titles) I get the error: "Origin null is not allowed by Access-Control-Allow-Origin". However when I put the same url into my browser the request goes through and I get a response.
What is the fundamental difference here that I'm not getting? How is the browser bypassing the Same Origin Policy?
I also used JSONP for Netflix's OData. It seems to work fine for my application. I have posted the code and explaination under my blog http://bit.ly/95HXLM
Some sample fragment below as well:
49. // Make JSONP call to Netflix
50. $.ajax({
51. dataType: "jsonp",
52. url: query,
53. jsonpCallback: "callback",
54. success: callback
55. });
56. });
57.
58. function callback(result) {
59. // unwrap result
60. var movies = result.d.results;
61.
62. $("#movieTemplateContainer").empty();
63. $("#movieTemplate").tmpl(movies).appendTo("#movieTemplateContainer");
64. }
The same origin policy applies to HTTP requests issued from within code loaded with pages from remote sites. That code is disallowed by the machine from issuing new requests for content from different domains, under the assumption that you, the user in control, were OK with fetching content from haxors.r.us, but you wouldn't want that site to issue HTTP requests to bankofamerica.com without your say-so. However, the browser should allow you, the user in control, to issue HTTP requests to anywhere. Indeed, with Humanity fading in the shadow of the Machine, I demand it. I demand it!
You can make requests to that URL from your server, and then pass along the response to your code on the client (after any sort of filtering or extraction your server code may choose to do). Alternatively, Netflix may support a JSONP API, which would allow your client-side code to issue GET requests as script fetches, with results to be interpreted as Javascript code.
Also it should be noted that this policy has nothing at all to do with jQuery itself. It's a basic security rule on the XMLHttpRequest mechanism.
This is bizarre, I was wondering if anyone could shed some light on why this happened.
Basically, I've been pulling my hair out trying to test JSONP out so I can implement a JSON web service that other sites can use. I'm doing development on localhost--specifically, Visual Studio 2008 and Visual Studio 2008's built-in web server.
So as a JSONP test run w/ jQuery, I implemented the following:
$().ready(function() {
debugger;
try {
$.getJSON("<%= new Uri(Request.Url, "/").ToString() %>XssTest?callback=?", function(data) {
alert(data.abc);
});
} catch (err) {
alert(err);
}
});
And on the server ..
<%= Request["callback"] %>({abc : 'def'})
So what ends up happening is I set a breakpoint on the server and I get the breakpoint both on the first "debugger;" statment in the client-side script as well as on the server. The JSONP URL is indeed being invoked after the page loads. That's working great.
The problem I was having was that the callback would never execute. I tested this in both IE8 as well as Firefox 3.5. Neither one would invoke the callback. The catch(err) was never reached, either. Nothing happened at all!
I'd been stuck on this for a week, and even tested with a manually keyed HTTP request in Telnet on the specified port to be sure that the server is returning the format...
callbackfn({abc : 'def'})
.. and it is.
Then it dawned on me, what if I change the hostname from localhost to localhost with a globalizer ('.'), i.e http://localhost.:41559/ instead of http://localhost:41559/ (yes, adding a dot to any hostname is legal, it is to DNS what global:: is to C# namespaces). And then it worked! Internet Explorer and Firefox 3.5 finally showed me an alert message when I just added a dot.
So this makes me wonder, what is going on here? Why would late script tag generation work with an Internet hostname and not with plain localhost? Or is that the right question?
Clearly this is implemented for security reasons, but what are they trying to secure?? And, by getting it to work with a dot, did I just expose a security hole in this security feature?
By the way, my hosts file, while altered for other hosts, has nothing special going on with localhost; the default 127.0.0.1 / ::1 are still in place with no overrides below.
FOLLOW-UP: I got past this for local development purposes by adding:
127.0.0.1 local.mysite.com
.. to my hosts file, then adding the following code to my global.asax:
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (Request.Headers["Host"].Split(':')[0] == "localhost")
{
Response.Redirect(
Request.Url.Scheme
+ "://"
+ "local.mysite.com"
+ ":" + Request.Url.Port.ToString()
+ Request.Url.PathAndQuery
, true);
}
}
I'm going to throw an answer out there; after some thought I've reached my own conclusions.
It could be that this is a security feature that's implemented to try to thwart an Internet web site from invoking JSONP services running on the client machine.
A web site could just go through a list of ports and keep invoking localhost on different ports and paths. 'Localhost' is one of few DNS hostnames that are dynamic in meaning depending on when and where it's queried, making the potential targets vulnerable. And yes, the fact that appending a dot (.) to 'localhost' ('localhost.') produces a working workaround does expose a security vulnerability, but does offer a [tentative] workaround for development puposes.
A better approach is to map the loopback IP to a new hostname entry in the hosts file so that it works locally, isn't prone to be "fixed" by a browser update, and doesn't work anywhere else but on the development workstation.
I'm experiencing a similar problem. Most of the solutions I've tried work with IE (7), but I'm having difficulty getting Firefox (3.5.2) to play ball.
I've installed HttpFox in order to see how my server's responses are being interpreted on the client, and I'm getting NS_ERROR_DOM_BAD_URI. My situation is a little different to yours though, as I'm trying to invoke a JSONP call back to the same site the hosting page came from, and then this call is responding with a 302 redirect to another site. (I'm using the redirect as a convenient way to get cookies from both domains returned to the browser.)
I'm using jQuery, and I originally tried doing a standard AJAX call via $.ajax(). I figured that as the initial request was to the same site as the hosting page, Firefox would just follow the 302 response to another domain. But no, it appeared to fall foul of XSS defenses. (Note that contrary to what Returning redirect as response to XHR request implies, jQuery does follow the 302 redirect for a standard dataType="json" call: a redirect to the same domain works fine; a redirect to another domain generates NS_ERROR_DOM_BAD_URI in the browser.) As an aside, I don't see why same-domain 302 redirects to other domains can't just be followed - after all, it's the hosting page's domain that is issuing the redirect, so why can't it be trusted? If you're worried about scripting injection attacks, then the JSONP route is open for abuse anyway...
jQuery's $.getJSON() with a ?callback=? suffix also fails in Firefox with the same error. As does using $.getScript() to roll my own JSONP <script> tag.
What does appear to work, is having a pre-existing <script id="jsonp" type="text/javascript"></script> in the HTML and then using $("jsonp").attr("src", url + "?callback=myCallback") to invoke the JSONP call. If I do that, then the cross-domain 302 redirect is followed and I get my JSON response passed to myCallback (which I've defined at the same time as the <script/> tag).
And, yes, I'm developing all this using Cassini with localhost:port URLs. Cassini won't respond to non-localhost URLs, so I can't easily try local.mysite.com to see if that has any affect on the solutions I've tried above. However, sticking a dot at the end of localhost appears to have fixed all my problems!
Now I can go back to a standard $.ajax({ ... dataType:"jsonp" ... }) call with localhost__.__:port instead of localhost:port and all is well. I find it interesting that modifying the src attribute of a script tag that pre-exists in the page's HTML does allow ordinary localhost URLs to be invoked - I guess following your thought process, this could be another security vulnerability.