I'm trying to get an html content to an external url using ajax request and load it to specific div element but I'm having error by doing the cross domain ajax request
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at
http://www.myowndomain.com/embed.php?c=5576b014b210a. (Reason:
CORS header 'Access-Control-Allow-Origin' missing).
This is the sample code that must be pasted in any blogs, forum or website of a users (any domain):
<script type="text/javascript" src="http://myowndomain.com/embed.js"></script><script type="text/javascript">embed.init(["5576b014b210a", "myembeded"]);embed.myCollage();</script><div id="myembeded"></div>
then here's the code for embed.js resided in my domain
var embed = embed || (function(){
var _args = {};
return {
init : function(param) {
_args = param;
},
myCollage : function() {
embed.load_home(_args[0],_args[1]);
},
load_home:function (id,elementId) {
var request = embed.createCORSRequest("get", "http://myowndomain.com/embed.php?c="+id);
if (request){
request.onload = function(){
document.getElementById(elementId).innerHTML = request.responseText;
};
request.send();
}
},
createCORSRequest:function (method, url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr){
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined"){
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
};
}());
and for the embed.php resided in my domain
if(isset($_GET['c'])){
echo file_get_contents('http://myowndomain.com/embed/?u='.$_GET['c']);
}
This is a feature implemented into browsers to prevent you from performing requests that aren't on your local domain.
If the other site has an API that allows that, then use their API. Otherwise you can't get the data. If it's your site, modify your web server to enable the requests by adding the header info.
This is all info that could have been gotten by just looking up the error yourself.
Already solved it. by adding this to my embed.js:
header("Access-Control-Allow-Origin: *");
Thanks for the idea.
Related
I am using WHMCS billing system. WHMCS have an own affiliate program, but it does work only on a subdomain. Since billing should be on a different server, just in case.
So we made a script for this one because users want to use the main link, instead of subdomain link. Because then you are using subdomain my.xeovo.com instead of xeovo.com you are going straight to billing, and have no choice to look at the main site.
JavaScript takes "r" from the link. This is how referral links looks like (/?r=1)
function ref() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value; });
return vars;
}
function file_get_contents( url ) {
var req = null;
try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {
try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {
try { req = new XMLHttpRequest(); } catch(e) {}
}
}
if (req == null) throw new Error('XMLHttpRequest not supported');
req.open("GET", url, false);
req.send(null);
return req.responseText;
}
function start() {
var id = ref()["r"];
var nl = file_get_contents("https://my.xeovo.com/aff.php?aff=" + id);
console.log("REF ID:" + id);
$.get("https://my.xeovo.com/aff.php?aff=" + id, function( data ) {
$( ".resss" ).html( data );
console.log('ok');
});
}
window.onload=function(){
start();
}
The script works totally fine, but we are getting a small problem in FireFox. We tested on Chrome/Opera/IE and everything was fine.
If you open https://www.xeovo.com in FireFox and click on certificate you are going to get this
here is screenshot
So any idea how we can fix this? Thanks.
If you check the browser console (Tools > Web Developer > Web Console), it gives the following error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://my.xeovo.com/aff.php?aff=undefined. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
According to this SO answer, it is a header to prevent others from using your resources, that answer have the solution:
In my.xeovo.com add the following line to your .htaccess:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
You might need to read more about this header to refine it to custom files, instead of everything.
I have a method WCF, which returns a JSON:
enter image description here
the client has a script that should take the data from the wcf service
Script:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
$(document).ready(function () {
$('#btn').click(function () {
$.ajax({
url: 'http://192.168.200.100/Searching.BE.Service//WCFRESTService.svc/GetCategories',
method: 'get',
contentType: 'application/json;charset=utf-8',
dataType: 'json',
success:function(data)
{
alet(data.Announcing[0].Categories.id);
},
error: function (error)
{
alert(error);
}
})
var request = createCORSRequest("get", "http://192.168.200.100/Searching.BE.Service//WCFRESTService.svc/GetCategories");
request.send();
})
})
</script>
<input id="btn" type="button" />
After click button i have this error: Object object
and i have console message:
SCRIPT7002: XMLHttpRequest: Network error 0x80070005, Access Denied .
SEC7120: Source http: // localhost: 4945 is not found in the header Access-Control-Allow-Origin ..
How to solve these problems?
Well, because your web server is running locally (see the 192.168...) address, I can't test it, but your error messages tell me the following:
The first one indicates that you are trying to access an unavailable resource. Try visiting the url with your browser, and see if that gives a response. Also in, http://192.168.200.100/Searching.BE.Service//WCFRESTService.svc/GetCategories, the double slash might indicate it's the wrong url.
The second error is not complete, but are you maybe serving the web page from a different server than the api? Because a quick google search reveals that it has something to do with a cross-site request.
I have a page with an iframe (displaying a third party website) in it. On click of a button in my page, username which I feed in, should go and get set in that third party website, from my iframe. I have been trying this for a while and have read about 'Same Origin Policy' and thus have been trying to use 'CORS(Cross-Origin Resource Sharing)'. I don't know if whatever am trying is allowed, but this is what I have done till now.
I do not know how to proceed from here.
<iframe name="ifr" id="ifr" height="200" width="200" src="https://somethirdPartyWebsite.com"/> </iframe><br/>
<input type="submit" id="submit" onclick="validate()" />
<script type="text/javascript">
function validate(){
var request = createCORSRequest("get", "https://ala.kcpl.com/ala/mainLogin.cfm");
alert("request-->"+request);
if (request){
request.onload = function() {
alert("In onload...");
};
request.onreadystatechange = stateChanged();
request.send();
}
}
function createCORSRequest(method, url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr){
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined"){
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
function stateChanged(){
alert("State Changed..");
}
**OUTPUT : **In IE, am getting alert("request-->"), alert("State Changed"), alert("In load").
In Firefox, am getting alert("request-->"), alert("State Changed").
Question: What am I to conclude from this and how do I go forward and set the value in the text field of the third party website, which is present in the iframe ifr
I think I need to do something like
$("#ifr").contents().find('#inputUsername').val()="ValueToEnter".
Not familiar with UI coding, please don't frown :)
You can't. Same-origin policy doesn't allow this.
CORS should be set on the server-side, it's not something that you can configure client-side.
I Have been using pins to get the information of a pin from pinterest.
The following is the script being used:
<script type="text/javascript">
function getresponse1()
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "https://widgets.pinterest.com/v3/pidgets/pins/info/?pin_ids="+{Pin ID});
alert(xmlHttp.status);
var data=xmlHttp.responseText;
var jsonResponse = JSON.parse(data);
var pin_url="www.pinterest.com/pin/"+pin_id+"/";
var page_name=(jsonResponse["data"][0].pinner.full_name);
alert(page_name);
}
</script>
Whenever XMLHttpRequest() method is being invoked the status returned is always 0 and the xmlHttp.responseText is empty.
But when the link is opened in a browser the response is correct and has all the information of the pin.
EDIT:
Tried implementing cross domain too. But yet the status returns 0.
New Script:
<script type="text/javascript">
function getresponse1()
{
var xhr = new XMLHttpRequest();
var url="https://widgets.pinterest.com/v3/pidgets/pins/info/?pin_ids=308074430730714588";
if ("withCredentials" in xhr) {
xhr.open("GET", url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
alert(xhr.status);
var data=xhr.responseText;
}
</script>
Please let me know where i'm making mistake. Thanks in advance
Note: I'm using Chrome browser
This is an general issue, as you try to do an ajax request to a different site (cross domain).
This isn't an new issue at all, I think here it is well explained and this posts provide also some thoughts about possible solutions.
AJAX is asynchronous, so your data will only be available from some kind of callback.
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 400) {
var data = JSON.parse(request.responseText);
}
};
I am trying to read xml file on the internet.It works on IE but does not on Firefox/Chrome.
It gives the error below on Firefox;
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://xxxxx.com/YYYY.xml. This can be fixed by moving the resource to the same domain or enabling CORS.
Here is my code;
<html>
<head>
<script>
function loadXMLDoc(filename)
{
if (window.ActiveXObject)
{
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
else
{
xhttp = new XMLHttpRequest();
}
xhttp.open("GET", filename, false);
try {xhttp.responseType = "msxml-document"} catch(err) {} // Helping IE11
xhttp.send("");
return xhttp.responseXML;
}
function displayResult()
{
xml = loadXMLDoc("http://xxxxx.com/YYYY.xml");
...........
.........
}
</script>
</head>
<body onload="displayResult()">
<div id="example" />
</body>
</html>
It returns null on the line
xhttp.responseXML;
in the loadXMLDoc function.
After getting this error I googled the error and tried the code below which makes CORS request. But it also does now work.
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
// Helper method to parse the title tag from the response.
function getTitle(text) {
return text.match('<title>(.*)?</title>')[1];
}
// Make the actual CORS request.
function makeCorsRequest() {
// All HTML5 Rocks properties support CORS.
var url = 'http://xxxxx.com/YYYY.xml';
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
var title = getTitle(text);
alert('Response from CORS request to ' + url + ': ' + title);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send();
}
In makeCorsRequest() function, after createCORSRequest() function, xhr.responseText is "" and xhr.ResponseXML is null.In response handler, it gives xhr.onerror.
Could you help me about this error?
Thanks.
UPDATE:
I am trying to test my pages in my computer(localhost). On the IIS in my computer, I enabled the CORS with the web.config below
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
On the network tab of the developer tab of Firefox
http://imgur.com/CXzxHLj
You have to enable CORS on the server hosting http://xxxxx.com/YYYY.xml, not on the server hosting your HTML document (which is localhost in your example).
You can't give yourself permission to access another server.