Why XMLHttpRequest doesn't work with "www."? - javascript

I have following code:
var params = {
cache:false,
dataType:"json",
type:"GET",
url: "/order.php",
error: function(data){
dump(data);
},
success: function (data){
alert('ok');
},
data:{
js:1
}
};
$.ajax(params);
So if I run example.com it gets work perfect.
But if I run www.example.com I get an error via my function dump().
Google console shows an error:
XMLHttpRequest cannot load
=1345470451769">http://example.com/order.php?js=1&tariff=247&=1345470451769. Origin
http://www.example.com is not allowed by Access-Control-Allow-Origin
What does it mean?
So I don't need any permanent redirect from www.domain.com to domain.com.
Thanks in advance for any help.
update 1:
I added function:
function getBaseUrl()
{
var baseUrl = '';
baseUrl += location.protocol + '//';
baseUrl += location.hostname;
return baseUrl;
}
and change url: "/order.php" on url: getBaseUrl() + "/order.php"
got the same error.
Am I doing something wrong here?
Update 2:
I added this one to htaccess file:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin http://sample.com http://www.sample.com
</IfModule>
It seems my hosting doesn't support it, because I still get an error for www.

The error you've got there means that you can't make a XMLHttpRequest from one domain to another unless the target domain specifies in its response header that you're allowed to do this. It's a security measure enforced by the browser.
The entire domain has to match, so example.com can't make a XMLHttpRequest request to www.example.com and vice-versa.
You could just use some javascript to get the URL based on the current document location, or use relative paths instead.
Also make sure the webserver isn't doing a silent redirect from one domain to another as this may also cause permissions issues.
The alternative if you have access to the webserver is to add the appropriate cross domain headers to the response - http://www.w3.org/TR/cors/
Example:
Access-Control-Allow-Origin: http://www.example.com http://example.com
Edit: The domains in the above list need to be space separated, not comma.
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "http://sample.com http://www.sample.com"
</IfModule>

Subdomains are considered a different domain with the same origin policy. Use a relative path if you site functions with or without www.
If the server redirects, why is the current page not on www?
From a SEO standpoint, you probably want the server to do the redirects to one version of the url or the other.

Related

No 'Access-Control-Allow-Origin' header - Tried all possible solutions

I know this question has been asked a lot before, but I literally tried out everything but I'm still getting this error.
I'm trying to fetch json data through ajax in my index.php file.
I'm running my website through apache2 on an ubuntu server. I have no idea where to go from here.
Exact error:
Failed to load http://localhost:32348/getinfo: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
What I tried:
- Adding this to /etc/apache2/apache2.conf File
<ifModule mod_headers.c>
Header set Access-Control-Allow-Origin: *
</ifModule>
- Adding this to in between every <Directory> tag to /etc/apache2/apache2.conf File:
Header set Access-Control-Allow-Origin "*"
- Adding this to my index.php file:
<?php
header('Access-Control-Allow-Origin: *');
?>
- Changing 'json' to 'jsonp', setting crossDomain to true and adding headers to allow origin
function fetchLiveStats() {
$.ajax({
url: api + '/getinfo',
dataType: 'jsonp',
type: 'GET',
crossDomain: true,
headers: {'Access-Control-Allow-Origin': '*'},
success: function(response) {
console.log(response);
},
cache: 'false'
}).done(function(data){
pulseLiveUpdate();
lastStats = data;
currentPage.update();
}).always(function () {
setTimeout(function() {
fetchLiveStats();
}, refreshDelay);
});
}
You need to add the Access-Control-Allow-Origin header to the response from http://localhost:32348/getinfo.
What I tried: - Adding this to /etc/apache2/apache2.conf File
Everything else you've said about your question implies that Apache was hosting the website on port 80, not the one on port 32348. You're changing the wrong server.
A website can't give itself permission to access data that another website will give the owner of the browser.
Changing 'json' to 'jsonp'
Don't use JSONP. It is a dirty hack. (It also requires that http://localhost:32348/getinfo return JSONP, which is almost certainly doesn't).
setting crossDomain to true
That just tells jQuery to not add headers it adds to Same Origin requests in case there is an HTTP redirect to a different origin. This prevents it being a complex request that needs a preflight. Since you aren't requesting a same origin URL in the first place, this does nothing.
adding headers to allow origin
You can't put response headers on the request!
Trying to will turn it into a complex request that requires a preflight, and cause you event more problems.
You need to edit whatever code is responsible for serving http://localhost:32348/getinfo
Don't forget to empty your cache (ipconfig/flushdns) and your browser cache when you try a new update, otherwise, the modifications may not be considered...

No 'Access-control-allow-origin' header is present on the requested resource error with json and jquery

I use an API that is on a different server and i got an CORS error I think. The strange thing is that it first worked with no problem, then i got this error message
XMLHttpRequest cannot load http://www.thecocktaildb.com/api/json/v1/1/random.php? tagmode=any&type=POST&format=jsonp. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'myadress.com' is therefore not allowed acces
i added crossDomain: "true" and it worked for a day. Now it doesn't work again and i've searched and tried a lot of solutions i've found. But nothing works. What is the problem and how do i fix it? Tried jsonp instead of json with and without type:post and the &callback=? does nothing. I've even installed the CORS enable extension for chrome. But alwways the same error, I have no control over the API itself or the server hosting it. How can I fix this? Below is my code.
function random() {
$(document).ready(function () {
$.getJSON("http://www.thecocktaildb.com/api/json/v1/1/random.php", {
tagmode: "any",
type: "POST",
format: 'jsonp',
crossDomain: "true"
}, function (data) {
console.log(data);
var result = "";
$.each(data.drinks, function (index, value) {
result += "<p>" + value.idDrink + "<p>";
result += "<p>" + value.strDrink + "<p>";
});
$('#result').html(result);
console.log(result);
});
});
}
I think you can make some modification for bypass CORS error. but target environment can also block CORS request. When I used Paypal checkout, I encountered same problem. Paypal environment doesn't accept CORS request.
So that you can try to make this call over server side.
If I understood it right you are doing an AJAX call to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.
Regular web pages can use the XMLHttpRequest object to send and
receive data from remote servers, but they're limited by the same
origin policy. Extensions aren't so limited. An extension can talk to
remote servers outside of its origin, as long as it first requests
cross-origin permissions.
Solution :
For allowing access to specific domain only:
response.addHeader("Access-Control-Allow-Origin", "http://www.thecocktaildb.com");
Check this blog post.

JQuery / AJAX: Cross-Origin Request Blocked

I have the following script (simplfied) that grabs some data from a local php file:
$(document).ready(function(){
var current_date = "x=y";
$.ajax
({
url: 'work/get_cal.php',
type: 'post',
data : current_date,
async: false,
success: function(result)
{
alert('never gets this far');
}
});
});
However I get a cross domain error, even though everything is on the same server. Has anyone had this issue before?
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.mywebsite.co.uk/work/get_cal.php. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
Add following line to get_cal.php
header('Access-Control-Allow-Origin: *');
This will allow to make Cross-Origin Request.
From comments to the original question for future Googlers.
The code used absolute paths and ended up in different domain "level" when the page was accessed with www and the script was requesting without www. This caused CORS problem.
Same Origin Policy permits running scripts in a browser and allows making requests to pages on with the SAME URI Scheme, hostname and port number. This is implemented for security within most of the browsers.
I personally use Chrome with Web Security Disabled during testing. Use the --disable-web-security parameter to enable this in your Chrome.
I strongly advice creating a seperate shortcut for development & testing purposes and NOT to use this option for your regular browsing...
"C:\<path_to_chrome_folder>\chrome.exe" --user-data-dir="C:/Chrome dev session" --disable-web-security
--user-data-dir is used to store the session details and other browser data, thus keeping is separate from your regular browsing data.
--disable-web-security disables the security and thus the Same Origin Policy warning.
Hope this helps...!

JavaScript - 'No Access Control Allow Origin' header' despite one being present

I have a simple PHP file that performs a MySQL query and returns a result.
At the top of the PHP file, I have this code:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
?>
I know that this is working as if I were to inspect in Chrome, if I look at the request headers that come back in the 'Network' tab I can see the header was set successfully.
Now I make the call from my JavaScript file on another domain using jQuery:
var getMyResults = $.ajax({
url: "http://mydomain.uk/myphpfile.php",
data: {something: "someData"},
dataType: "JSON",
type: "GET"
});
Every single time I run this code from the JavaScript file I get the follow error:
XMLHttpRequest cannot load http://mydomain.uk/myphpfile.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myotherdomaincallingthefile.uk' is therefore not allowed access.
Why is this happening?
There is a redirect going on before you get to the final page, which sends the header, locate it; if it is in .htaccess you can add this to the .htaccess file:
<ifModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</ifModule>
or your other option is in your Ajax call to use the final URL, which would supply the headers without any redirects in the way.
After a few hours of investigation I found the issue with the help of t3chguy in the comments.
My AJAX request URL: "http://mydomain.uk/directory"
Correct, working cross origin AJAX: "http://mydomain.uk/directory/"
A single extra "/" fixed the issue.
Why?
With the help of http://redirectcheck.com/ I saw that without the '/' Apache was making a redirect which meant that the cross origin header wasn't present on that initial request, hence the error.

Why this won't fetch source code?

This code should fetch the HTML source of http://yahoo.com/(index.html), and show it in dialog.
$.ajax({ url: 'http://yahoo.com', success: function(data) {
alert(data);
}
});
However, it won't do anything...
What's wrong with my code?
By default, you're not allowed to make cross domain requests. This violate the Cross Origin policy.
To make it work the requested domain must emit headers that allow the requesting domain.
I've got a tutorial on how to set and use the CORS policy: http://fritsvancampen.wordpress.com/2013/02/03/cross-site-origin-requests-aka-cross-origin-resource-sharing/
but if you want to fetch data from Yahoo you need control over their domain .. and that's not gonna happen ;)
Ajax is not used for your purpose . you have to used like this
$content = file_get_contents('http://www.yahoo.com/');
print_r($content);
Or this could be helpful for you
http://toolspot.org/extract-website-data.php

Categories

Resources