jQuery: Can't run $.get (http get) on Chrome - javascript

I want to use JavaScript to make a simple http get.
I used jQuery to perform my request. My code runs on IE8.0 but not in Chrome (ver 6.0).
My page has the following code: (to simplify, i made a simple request to a html page, but my needs is other)
<!DOCTYPE html PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<script type"text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<SCRIPT TYPE="text/javascript" >
function sendGet(){
$.get(
"http://www.google.pt",
function(data) {
alert('page content: ' + data);
});
}
</SCRIPT>
<head>
<title> Http Get Demonstration </title>
</head>
<body>
<p/>
<input type="button" value="Http Get" onclick="sendGet();" />
</body>
</html>
As i said, when i load this page on IE and press the button, i get the alert with the html code. But in Chrome the alert appears with empty text (null?). In Chrome Console from "Developer tools" i get the message: "XMLHttpRequest cannot load http://www.google.pt/. Origin null is not allowed by Access-Control-Allow-Origin."
Anyone can explain me what's the meaning of this message? And what i should change to my page run in Chrome?
Thanks

Due to same origin policy you cannot send AJAX requests to different domains than the one hosting your page. So unless your page is hosted on http://google.pt you cannot send an AJAX request to this domain. One possible workaround is to setup a server side script on your domain which will act as bridge between google.pt and the client or use JSONP if the distant domain supports it.

Although i can't remember if i changed any IE option, the Darin Dimitrov seems explain my problem.
I found some tricks can be used (beyond the Dimitrov answer):
use a PHP script:
http://jquery-howto.blogspot.com/2009/04/cross-domain-ajax-querying-with-jquery.html
configure IE by editing regedit (not recomended):
http://msdn.microsoft.com/en-us/library/dd565656(VS.85).aspx
(I belive there's some other way to disable cross domain protection without editing regedit. But i couldn't find it)

Are you opening the html file directly from a file (e.g. does the address bar say file://usr/path/to/the/file)?
We've found chrome won't let you 'ajax' in files from other domains when running under file://. However, in Safari it works fine.
Best solution for us is to use something like MAMP to run a local Apache server.

Related

What is a best way to test CORS issue on multiple browser?

I am enabling CORS with Spring security in My project but after implementing what is best way test it ? Because for IE 9+ versions i am not able test it properly so couldn't get confirmation my code is working or not. I developed one Javascript client and hitting ajax request but still it is not working as expected and without proper testing not able to figure out there is issue with Spring Security or test method. I also try https://www.test-cors.org/ but not working for me.
Anyone know this please share.
Thanks in advance.
I go the answer the best way to test CORS implementation is hitting API with separate JavaScript client which may be not in your project. That is the best way to test it. However modern browsers like Chrome and Firefox by default block the CORS requests so proper error will print on the browser's console. Browser's like IE will not block such request by default so make sure your server should enabled CORS requests.
I used below JavaScript code for testing.
<!DOCTYPE html>
<html>
<head>
<title>Hello CORS</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$.ajax({
url: "
Your URL"
}).then(function(data, status, jqxhr) {
});
</script>
</head>
<body>
</body>
</html>
Make sure about Jquery versions you are using which may give problem while testing in IE.
Use latest Jquery version.

same-origin policy with AJAX load widget

I am trying to include a widget in my webpage. The code for the widget is loaded dynamically with ajax (because it changes often and I need to update it from the server) and it looks like this ...
<a class="e-widget" href="https://gleam.io/0oIpw/contest-widget" rel="nofollow">This is a Widget!</a>
<script type="text/javascript" src="https://js.gleam.io/e.js" async="true"></script>
on load, I get the following errors in the console...
OPTIONS https://js.gleam.io/e.js 404 (Not Found)
XMLHttpRequest cannot load https://js.gleam.io/e.js. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:8443' is therefore not allowed access. The response had HTTP status code 404.
If I remove the ajax call that loads the data for the widget, and instead insert the widget directly, I do not get the same errors and the widget works fine.
I have read into this and figure that it is due to the Same-Origin-Policy (SOP), so I am now wondering the best way to circumvent the policy.
I have read the post Ways to circumvent the same-origin policy but unfortunately did not find it helpful in this case.
Since CORS is done on the server side (I think ? ) and JSONP is insecure, is the best option to create a proxy?
Thanks so much for the help. I have spent quite a few hours researching this and I am still confused.
Edited to add code for more info :
The information for the page is loaded via ajax when a command link is clicked as follows :
<h:commandLink action="#{redeemPerk.getDisplay(display.displayId)}" >
<h:graphicImage value="#{display.imgUrl}" styleClass="display-icon"/>
<f:ajax event="click" execute="#form" render="redeem-display-data-reveal" listener="#{redeemPerk.getDisplay(display.displayId)}" onevent="handleAjax"/>
</h:commandLink>
this renders the area that displays the widget, which looks like ...
<div class="reveal-modal-background hidden">
<h:form id="redeem-display-data-reveal">
<h:panelGroup rendered="#{display.type == 'WIDGET'}">
<a class="e-widget" href="https://gleam.io/0oIpw/contest-widget" rel="nofollow">This is a Widget!</a>
<script type="text/javascript" src="https://js.gleam.io/e.js" async="true"></script>
</h:form>
</div></h:panelGroup>
The second chunk of code is in a separate file from the first. To reiterate, if I remove the ajax call and load the data directly the widget works fine.
I am seeing two things in your output log that could be causing the issue.
First, it states that you received a 404 message from the request. Which means the JavaScript has probably not been uploaded properly.
Second, it says that the origin of the request came from localhost:8443. That leads me to believe that you are running the code locally instead of from the Internet.
In cases where you are trying to load a plugin from the internet, but your code is being tested locally you are still going to get an SOP error. To fix this problem you would need to upload all of the code that you do have to your web server. Once you have done that attempt to load the webpage from the Internet and not your local copy. That should fix that SOP error.

How to load javascript libraries securely

I apologize if this question is simplistic, beginning web developer here.
I have a page that I am serving securely as https. The page uses the following two libraries:
<script src="http://myjs.us/param.js"></script>
<script src="http://myjs.us/entify.js"></script>
I am getting errors of the following type:
[blocked] The page at ... was loaded over HTTPS, but ran insecure
content from 'http://myjs.us/param.js': this content should also be
loaded over HTTPS.
So I get why I am getting this error, it is because I am loading the javascript libraries from an unsecure source. My question is where can I get these from a secure source?
Thanks in advance.
The basic solution is to remove the protocol form the URL when you call the javascript, change
<script src="http://myjs.us/param.js"></script>
to this
<script src="//myjs.us/param.js"></script>
With this you ensure that the javascript will load with the same protocol of the entire page.
Be sure that the server supports https (myjs.us for you), otherwise you will get an error like failed to load resource..., In this case, maybe you want to use a CDN with https support, like cdnjs
You can omit the protocol in your URLs:
<script src="//myjs.us/param.js"></script>
<script src="//myjs.us/entify.js"></script>
The browser will default to the current protocol being used by the page, in this case https. Of course, if myjs.us doesn't support https then that would be another issue entirely, and one you can't really solve from your page.

Chrome - Unable to read sessions for cross domain requests

First I'm apologizing if the title of my question is not correct or not clear. But I will explain my issue below.
Lets say I have a web application called mywebapp.com and i have a page loadjs.php. Here, I have some JS code and the content time of the file is application/javascript.
loadjs.php (mywebapp.com)
header("content-type: application/javascript")
echo "alert('some message here');";
I will use the above file in a page (index.html) of another web app as a javascript source. let's say that it is anotherwebapp.com.
index.html (anotherwebapp.com)
<html>
<head>
<script type="text/javascript" src="//mywebapp.com/loadjs.php"></script>
</head>
<body>
Some contenct here..
</body>
</html>
When this runs, there should be javascript alert as I wrote in loadjs.php (mywebapp.com).
Note:
The above is working without any issue.
My Issue:
Lets assume now I want to display this alret only for the logged in users for mywebapp.com. That means, when a user who has logged in already in mywebapp.com will see an alert when they visit anotherwebapp.com in the same browser.
So my loadjs.php file will be as below.
header("content-type: application/javascript")
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in']==true)
echo "alert('some message here');";
Let's assume that $_SESSION['logged_in'] has been already set after the user login.
It was working properly in Firefox and and IE. But..
Chrome browser was not working properly.
So the reason is, chrome cannot read the session value as other browsers do.
Is there any special reason for this and is there any way to overcome this?
(Please note that the above coding sample is just an example to explain my issue.)
Looking forward to hear from you.
Session is handled server-side, so this is not a Chrome problem.
It could be a caching problem: the js file is first loaded without the alert (because the user is not logged in) but when the user logs in the js is loaded from cache and not downloaded again causing the alert to not display.
Chrome has a pretty "aggressive" caching policy, had some troubles like this before.
You should try to add a timestamp or some kind of dummy value like so that on every page reload you force the javascript file to be downloaded again
<head>
<script type="text/javascript" src="//mywebapp.com/loadjs.php?dummy=
<? echo time() ?>"></script>
</head>
I haven't been using php for quite some time so this might not work but you should get the idea
This is an interesting issue. I do not have an environment to test this right now, but the first thing I would like to do is to print the $_SESSION['logged_in'] while making a request using FF, then Chrome. If for Chrome the value is false, you have to debug why. It could be a crossdomain policy issue.
You can take a look at this: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS
Maybe you need to send this header from mywebapp.com:
Access-Control-Allow-Origin: http://anotherwebapp.com
Please also share if the js console of Chrome shows any error.
Update: the issue was due to chrome browser cookie settings dialed in to be restrictive. Go to chrome://settings/content and make sure Block third-party cookies and site data is not checked.
I had a similar issue.
The reason for your problem is:
The session ID is sent as a cookie, and since your request is cross-domain, it's considered a third party cookie by the browser. Several browsers will block third-party cookies.
The solution to your problem is
Generate the session ID on the client (in the browser), use Javascript sessionStorage to store the session ID then send the session ID with each request to the server.
Details in this article (related to XMLHttpRequest, but your issue is essentially the same): Javascript Cross-Domain Request With Session

Resource interpreted as Script but transferred with MIME type text/plain - for local file

I'm getting a "Resource interpreted as Script but transferred with MIME type text/plain" warning in Google Chrome when including a local script file.
I know the problem appears when loading a file from a server or through ajax which most often depends on wrong headers being set.
The weird thing is that I get this warning even though it is run from a local folder: file:///C:/test/foo.html
This happens only in Chrome with the most basic html there is:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="bar.js"></script>
</head>
<body>
</body>
</html>
bar.js is also as simple as it can get:
function hello() {}
I've tried adding a meta tag:
<meta http-equiv="content-script-type" content="text/javascript">
and tested with other doctypes but nothing seems to help.
This obviously isn't a real issue since the scripts still work fine, but I'm working on a large project and currently have around 150 scripts included. It therefore makes it difficult to see when an actual warning occurs in between them.
Everything works fine when I run the file on a server, locally or remote.
Any ideas on why chrome is annoying me with this?
I figured it out!
The Visual Studio installer must have added an errant line to the registry.
open up regedit and take a look at this registry key:
See that key? The Content Type key? change its value from text/plain to text/javascript.
Finally chrome can breathe easy again.
I should note that neither Content Type nor PercievedType are there by default on Windows 7, so you could probably safely delete them both, but the minimum you need to do is that edit.
Anyway I hope this fixes it for you too!
I tried fixing this problem using this method but it didn't work for me.
My problem was that IIS manager didn't have MIME types in HTTP Features.
I was able to turn it on by enabling Static Context via...
--> Control Panel
--> Programs
--> Turn Windows features on or off
--> Internet Information Services
--> World Wide Web Services
--> Common HTTP features
--> [X] Static Content.
After this, MIME types appeared and everything started working again.
The accepted answer is a great one! However, just to post an answer for those who encounter problem like me, who use a department/college computer sometimes, where I do not have the permission to change any key value in regedit.
Change
<script type="text/javascript" src="main.js"></script>
to
<script src="main.js"></script>
Although the error message still exist, the page loaded correctly.

Categories