I'm trying to get some data from this imdb api: http://www.deanclatworthy.com/imdb/#usage
However I'm getting errors using this code:
<hmtl>
<head>
<script type="text/javascript">
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlhttp = false;
}
}
}
xmlhttp.open("GET", "http://www.deanclatworthy.com/imdb/?q=The+Green+Mile", false);
xmlhttp.send();
var imdbData = xmlhttp.responseText;
//var imdbJSON = eval("(" + imdbData + ")");
alert(imdbData);
</script>
</head>
<body>
<body>
</body>
</html>
The error is this: Origin http://mysite.nl is not allowed by Access-Control-Allow-Origin.
test.html:23Uncaught Error: NETWORK_ERR: XMLHttpRequest Exception 101
Could someone post a working code on this request? Thank you.
You can't access other server's data like you can your's. It violates the same origin policy. For cross domain requests you could use jQuery and JSONP, see:
http://usejquery.com/posts/the-jquery-cross-domain-ajax-guide
http://remysharp.com/2007/10/08/what-is-jsonp/
If you don't use jQuery you can google "cross domain ajax" or something. Maybe these links give you some ideas
http://snook.ca/archives/javascript/cross_domain_aj
http://alvinabad.wordpress.com/2009/02/13/feb13/
As for the working code request. Well, now that you are aware of the same origin policy, maybe you'll get it to work yourself...
Related
I'm trying to fetch quotes history from yahoo api:
Yahoo Historical quotes
I encountered cross-origin error and I tried to resolve it by setting the correct xmlHttpRequest header. I have followed recommendation from other posts but no success.
I don't want to use Yahoo YQL, as it limits response to ~2 years quotes history.
Here is my code:
<!DOCTYPE html>
<html>
<body>
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// console.log(this.responseText);
console.log(this.getAllResponseHeaders())
}
};
xhttp.open("GET", "http://chart.finance.yahoo.com/table.csv?&a=0&b=1&c=2011&d=3&e=17&f=2017&s=YHOO", true);
xhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xhttp.setRequestHeader("Content-Type", "text/plain");
xhttp.setRequestHeader("cache-control" , "private");
xhttp.setRequestHeader("Access-Control-Allow-Methods" , "DELETE, HEAD, GET, OPTIONS, POST, PUT");
xhttp.setRequestHeader("Access-Control-Allow-Headers", "Content-Type, Content-Range, Content-Disposition, Content-Description");
xhttp.send();
}
</script>
</body>
</html>
i was trying to make asynchronous call to Yahoo's symbol suggest JSONP API, so there's cross domain problem, I have read this document and try to change it's url , the following are the codes i use
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;
}
function makeCorsRequest() {
// All HTML5 Rocks properties support CORS.
// var url = 'http://updates.html5rocks.com';
var url = 'http://autoc.finance.yahoo.com/autoc?query=google&callback=YAHOO.Finance.SymbolSuggest.ssCallback';
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
console.log(text);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send();
}
but the problem still not solved:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
does anyone know why? Also, I compared the code in document with regular ajax code, they are almost the same, how does CORS work?
thanks
For CORS to work, the server needs to set the Access-Control-Allow-Origin header. If you do not control the server, and the server hasn't set that header, then I'm afraid you're out of luck.
CORS replaces JSONP as the way to load cross-domain json content, but with JSONP the server also needs to implement it.
If the owner of the content doesn't want you to use it, the browser will reject it.
Edit: of course you can avoid the cross-browser issue by having your server get the content from the original server, and having the browser get it from your own server. More work, but it's not cross-browser anymore.
I have this JavaScript function which is getting a value from a select option in HTML:
<script type="text/javascript">
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var str=xmlhttp.responseText;
var splitstr=str.split('||');
document.getElementById("txtHint").innerHTML=splitstr[0];
document.getElementById("txtval").innerHTML=splitstr[1];
}
}
xmlhttp.open("GET","getdetails.php?q="+str,true);
xmlhttp.send();
}
</script>
Now, str is the JavaScript variable I want to take its value and put it into a PHP variable.
I am using this, but it is not working:
$grade = "<script language=javascript>document.write(str);</script>";
echo $grade;
What is the correct way to do this?
PHP runs on a web server, so it will only execute when the page loads. So the above statement will not work as it runs within the function which is called after page load.
To achieve what you want, you can send str to a php file via ajax call and store it in a session variable. & then whenever you need the variable call another ajax function which will retrieve the session value.
You can use jQuery to handle AJAX calls.
Make sure you include this line in your html page.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
Use the javascript to make your call to PHP and sent your str data.
function uploaddata(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
var fd = new FormData();
fd.append('data1', str);
try {
$.ajax({
url: 'dosomething.php',
data:fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
var response = $.parseJSON(data);
if (response.code !== '0'){
alert(response.description);
}
else {
alert(response.description);
};
},
error: function(jqXHR, error, errorThrown) {
alert(jqXHR.responseText);}
});
}
catch (ex) {
}
}
At server side create the dosomething.php will make the process you need.
<?php
// get your data at server side
str = $_POST['data1'];
// do processing
// return answer to browser
$ans = ['code' => '0', 'description' => 'Everything are ok'];
echo json_encode($ans);
return;
?>
At your javascript the success portion will be activated and you can use the code and description to build your logic.
I can sent data to server using HttpRequest from all browser apart from opera browser. I tired opera 11.61 too. But still i cant sent data to server from opera browser.My code is
xmlHttp=new XMLHttpRequest();
var url="http://localhost";
xmlHttp.open("POST",url,true);
var params = "lorem=ipsum&name=binny";
function timerMethod()
{
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.send(params);
}
Please help me in this issue
With Regards,
Muthu.S
This should work provided you call timerMethod() from elsewhere in the code as hallvors alluded to. For example:
xmlHttp=new XMLHttpRequest();
var url="http://localhost/stackoverflow/response.php";
xmlHttp.open("POST",url,true);
var params = "lorem=ipsum&name=binny";
function timerMethod()
{
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.send(params);
xmlHttp.onload = function(){
console.log( this.responseText );
}
}
timerMethod();
Currently FB.getLoginStatus is not at all firing after the facebook changes with new SDK and OAuth 2.0.
We used to get the response in FB.getLoginStatus and call our callback function that in turn was redirecting
the users to our facebook application.
Please help.
The code snippet -
FB.init({
appId: '<%=ConfigurationManager.AppSettings["APIKey"]%>', // App ID
//channelURL: 'xd_receiver.htm', // Channel File
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
oauth: true // enable OAuth 2.0
//xfbml: true // parse XFBML
});
update_user_is_connected();
function update_user_is_connected()
{
FB.getLoginStatus(function(response)
{
callback();
});
}
function callback() {
var fbURL = "http://apps.facebook.com/" + '<%=Suffix%>' + "/MyPage.aspx";
eval("parent.location='" + fbURL + "'");
}
Now FB.getLoginStatus is not working.
Regards,
KK
I've had the same issue and fixed it by adding true as a second parameter :
FB.getLoginStatus(function(response) {
callback();
},
true);
This disables the cache and forces reloading. See the docs
Just encountered this error whilst trying to check whether the user is already logged in with Facebook as soon as the page finished loading.
If you're trying to do this, you need to wait for facebook sdk to finish loading, Make your call to your checkLoginState() method inside window.fbAsyncInit after FB.init().
This code works very well with me to check login status and request login and fetch oauth info (Name, User Id, Token ... ) based on Java script SDK.
I have some recommendations which are that you have to make sure your application and channel file should be located within your domain which you have setup in your Facebook App settings.
Also make sure you have the div fb-root in your code:
<div id="fb-root"></div>
As shown below
Hope this may help ...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test Page</title>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxxxxxxx', // App ID
channelUrl : 'https://xxxxxxxxxxxxx/channel.html',
status : true,
cookie : true,
xfbml : true,
oauth : true
});
var token = "";
var userId = "";
FB.getLoginStatus(function(response) { // Get Login Status
if (response && response.authResponse) { // Check if User is Logged In
var token = response.authResponse.accessToken; // Get Token
var userId = response.authResponse.userID; // Get User ID
} else {
// alert("Not Auhtenticated");
FB.login(function(response) { // Promot User to Authenticate App
if (response && response.authResponse) {
var token = response.authResponse.accessToken;
var userId = response.authResponse.userID;
}
}, {scope: 'user_likes,friends_likes,publish_stream,read_friendlists,offline_access'}); // Scopes Example...
}
});
};
//Load asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=xxxxxxxxxxx";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
</body>
My problem was in the window.fbAsyncInit function.
FB.init({
appId : '321677491886687',
cookie : true,
xfbml : true,
version : '3.2'
});
I needed to change 3.2 to v3.2
Kamal,
I believe you can fix your problem by replacing
FB.getLoginStatus(function(response)
{
callback();
});
with
FB.Event.Subscribe('auth.login', callback());
Regards
Make sure all you URLs are correct, I had the same problem while running locally but had the site URL pointing to the production website, once I corrected this, getLoginStatus worked all right.