I'm planning to use googlecharts to chart data that is stored on in a local database - the googlecharts code will also be stored on a local server. I used XAMPP to create a local directory ('http://http://127.0.0.1/). Before jumping into the project, I am testing an example script (that I found from a google search) that takes data from a json file (which is called from a php script) and then feeds it to the googlecharts drawing functions. The 3 files are all stored in the folder 'C:\xampp\htdocs', as advised, but when I load the page in my browser (http://127.0.0.1/test_php_long.html) the page appears blank (on Chrome, IE and Firefox). When I run a googlecharts script with data hardcoded into the HTML it works fine. I have been looking online for several hours but have yet to find a solution that works.
This is the main html file ('test_php_long.html'):
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://www.maxcdn.com/one//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
//fetchjson.php is a php script that will fetch the JSON data e generated using above php code
url: "fetchjson.php",
dataType:"json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jsonData);
var chart = new google.visualization.LineChart(document.getElementById('chart_flow'));
chart.draw(data, {width: 1200, height: 300, lineWidth: 1, pointSize: 1.3, pointWidth: 3});
}
</script>
</head>
<body>
<div id="chart_flow"></div>
</body>
</html>
This is the php file ('fetchjson.php')
<html>
<head>
<title></title>
</head>
<body>
<?php
//Fill the ‘string’ variable with JSON data from file we used as json container populated by php //code: ‘flow.json’
$string = file_get_contents("flow.json");
//push JSON data out
echo $string;
?>
</body>
</html>
And this is the json file ('flow.json'):
{"cols":[{"id":"","label":"Time","pattern":"","type":"string"},{"id":"","label":"Cache Hits","pattern":"","type":"number"},{"id":"","label":"Non-Cache Hits","pattern":"","type":"number"}],"rows":[{"c":[{"v":"2014-01-21 00:00:00"},{"v":2},{"v":23}]},{"c":[{"v":"2014-01-21 01:00:00"},{"v":2},{"v":52}]},
...
,{"c":[{"v":"2014-01-23 01:00:00"},{"v":0},{"v":34}]},]}
Thanks!
Your problem might be related to the fact that your request is a cross-origin one, or at least being considered as once. There are two ways as far as I know to deal with this issue, either you allow cross origin requests, by adding the following lines at the top of your PHP script :
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
While this is potentially unsafe, and the * should be replaced by a list of trusted domains, it should solve your problem for now and shouldn't be much of a security threat since your app will be running in an intranet.
OR, you could also issue jsonp instead of json by wrapping your json object in a callback :
echo $_GET['callback'] . '(' . json_encode($something_to_be_encoded) . ')';
Don't forget that your url parameter passed to your ajax function should now be :
http://myawesomescript.php?callback=?
Related
I have a slight problem. I am connecting to a web service which provides JSON results and trying to parse the results. The code is working fine on my localhost (wamp server) but code doesn't run on any of the web hosting accounts I tried.
Here is the url providing JSON
http://mohamedbadr.com/webservice/list.php
And here is my file which is trying to fetch results:
http://contestlancer.com/web/getList.php
Here is the code of the Getlist file:
<!DOCTYPE HTML>
<html>
<head>
<title>Hotel Promotion List</title>
<script type="text/javascript" src="jquery.js"></script>
<link rel="stylesheet" type="text/css" href="style.css"/>
<script type="text/javascript">
function getList()
{
var i=0;
var ntable="<table><thead><tr><th>Image</th><th>Name</th><th>Rating</th><th>Highlights</th></tr></thead><tbody>";
$.getJSON("http://mohamedbadr.com/webservice/list.php", function(data){
$.each(data.promos, function(key, value) {
ntable+="<tr><td><a href='promotion.php?id="+value.promo.id+"'><img src='"+value.promo.image+"' height='100' width='150'/></a></td><td><a href='promotion.php?id="+value.promo.id+"'>"+value.promo.name+"</a></td><td> "+value.promo.stars+"</td><td> "+value.promo.highlights+"</td></tr>";
});
ntable+="</tbody></table>";
$("#content").html(ntable);
});
}
</script>
</head>
<body onLoad="getList()">
<div id="wrapper">
<div id="content"></div>
</div>
</body>
</html>
Most probably the url is not being opened what is the solution to this? Any help will be highly appreciated
It's not working because you are making a cross domain request. Domain A to Domain B.
Try adding this to http://mohamedbadr.com/webservice/list.php before any output is printed.
header('Access-Control-Allow-Origin: http://contestlancer.com');
As mentioned by Nadh, this is due to a cross-domain request. More info # HTTP Access Control. Understanding Same Origin Request.
Since you are using jQuery getJson(), you may alternatively try this approach
var url = "http://mohamedbadr.com/webservice/list.php";
$.getJSON(url + "?callback=?", null, function(data) {
... Success Logic here...
});
The ?callback=? at the end of the url, will convert your request to a JSONP. And if you remove it, this will be a plain Ajax call.
Understanding JSONP
-- Arvind.
I am using ajax for retrieving data from my remote server when i am posting the ajax url directly in the address bar of browser, i am getting the data but when i am doing ajax call to that url in javascript file , it is showing error.I am pasting my code here.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$.ajax({
url:"http://www.appitechture.com/api/index.php?action=getContactDetails&id=96",
type:'get',
datatype:'json',
success:function OnSuccess(data , status){
alert(data);
} ,
error: function OnError(request , status , error){
alert('error');
}
});
</script>
</head>
<body>
<div id="images"></div>
</body>
</html>
so please if any one knows its solution please tell me.
Thank's
puneet
Are you trying to do a crossdomain AJAX request? Bad idea, read this article http://en.wikipedia.org/wiki/Same_origin_policy
If it is not the same domain, you need to use JSONP (JSON with padding). This is due to Same Orgin Policy, as Bogdan Burim states.
jQuery.getJSON can help you with this in a easy way. It will include a script tag like this on your page.
<script type="text/javascript"
src="http://example.com/jsonp?callback=parseResponse">
</script>
You will also need to change the response of the remote server to include the callback var like this:
parseResponse({"bar": "foo", "foo2": "bar2"});
You can also have a look at easyXDM:
easyXDM is a Javascript library that enables you as a developer to
easily work around the limitation set in place by the Same Origin
Policy, in turn making it easy to communicate and expose javascript
API’s across domain boundaries.
Wikipedia have a nice article about JSONP.
I'm trying to get access to a Javascript API, I created, on other sites. The javascript is at https://ksc105.kscserver.com/query.js and it pulls ajax calls to https://ksc105.kscserver.com/suggestions.php (?action=getall). Of course using this on https://ksc105.kscserver.com/index.php works.
However I'm trying to use import that javascript into another domain site. I know cross-domain ajax calls do not work, but I supposed that if the ajax call is made from a javascript on that site that it was going to work. I supposed this based on Google's Map API. I'm pretty sure it uses ajax.
How do I get ajax to work like the Google Map API? Where any website can add my script and use its functions?
In firebug, I get the request to fire but I just get an empty return but it should not be returning empty. In IE9, I get the error "SCRIPT5: Access is denied." / "query.js, line 62 character 5".
If you go to https://ksc105.kscerver.com/index.php and type 3 or more characters in the box you should get "suggestions" much like Google Search. I need the same thing to work on any other website without a server proxy. You can use "Test" as it pulls a bunch of test data.
Try using AJAX callbacks. jQuery does this well but as a raw example, if you load some JSON with a callback function (From a <script> tag) it will run the function. This is how you can use the Twitter API across sites. I.E. if you call http://api.twitter.com/1/statuses/user_timeline.json?screen_name=twitter&count=20&callback=handletwitter and create a handletwitter function:
<script type="text/javascript">
function handletwitter(data){
console.log(data);
}
</script>
<script type="text/javascript" src="http://api.twitter.com/1/statuses/user_timeline.json?screen_name=twitter&count=20&callback=handletwitter"></script>
This is also known as JSONP
There's a smart solution to do so. You can have an iFrame of width and height 0, so it won't be visible. From within it, you can load data on main page using 'parent' property. Since you are allowed to load anything in an iFrame, this should be a good solution for you.
Consider the following example (will also work on different domain).
<html>
<head>
<script type="text/javascript">
function loadData(data)
{
var a = document.getElementById("H");
a.innerHTML = data;
}
</script>
</head>
<body>
<div id="H">hello</div>
<iframe src="sample.html" width="0px" height="0px">
</iframe>
</body>
</html>
Sample.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script>
<!--
parent.loadData("I am inside iFrame");
-->
</script>
</body>
</html>
i have a simple setup, with php pulling html content from a database. if i go to my template page, it loads the data and returns it to the browser via a simple php echo ... not rocket science.
now, i've written an html file using jquery and an ajax call. i load the html file in my browser and the javascript / ajax query works.
when i load the html into the database and print it out via the php / echo, the content is the exact same when i view the source, but the ajax query doesn't execute.
<html>
<head>
<title>random query - api - get</title>
<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
</head>
<body>
<pre>
executing the GET method
<script language="javascript" type="text/javascript">
$.ajax({
type: "GET",
url: "http://some-rand.om.api.com",
data: "011b38b8-011f-4b03-bb21-4c5bb26600b3",
success: function(msg){
alert( msg );
}
});
</script>
</pre>
</body>
</html>
Any comments / suggestions would be great. What I find bizarre, is i have no problem copying the source of http://jquery.com/ and pasting it into the db and doing the php / echo. this works fine. maybe an onLoad() would help...hm.
The issue is outlined in the following url:
XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin
When I load the javascript console in chrome I get this:
XMLHttpRequest cannot load http://some-rand.om.api.com/user?011b38b8-011f-4b03-bb21-4c5bb26600b3. Origin http://localhost is not allowed by Access-Control-Allow-Origin.
To resolve the problem, on the api vhost, in the code that serves the content accessed by the ajax query, i added this (it is also php):
header('Access-Control-Allow-Origin: http://some-rand.om.client.com');
Now when I access it, it's all good and loads as expected. So, infact, it wasn't related to it being stored in the database, php or javascript. It was related to cross site scripting.
Or, to be super lazy (probably not a great idea...):
header('Access-Control-Allow-Origin: ' . $_SERVER["HTTP_ORIGIN"]);
If in your description of the problem you are listing the whole of the code, then the JavaScript should be wrapped in a $(document).ready(function(){ ... });.
i.e.
$(document).ready(function(){
$.ajax({
type: "GET",
url: "http://some-rand.om.api.com",
data: "011b38b8-011f-4b03-bb21-4c5bb26600b3",
success: function(msg){alert( msg );}
});
});
This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
Closed 2 years ago.
How do I pass have a Javascript script request a PHP page and pass data to it? How do I then have the PHP script pass data back to the Javascript script?
client.js:
data = {tohex: 4919, sum: [1, 3, 5]};
// how would this script pass data to server.php and access the response?
server.php:
$tohex = ... ; // How would this be set to data.tohex?
$sum = ...; // How would this be set to data.sum?
// How would this be sent to client.js?
array(base_convert($tohex, 16), array_sum($sum))
Passing data from PHP is easy, you can generate JavaScript with it. The other way is a bit harder - you have to invoke the PHP script by a Javascript request.
An example (using traditional event registration model for simplicity):
<!-- headers etc. omitted -->
<script>
function callPHP(params) {
var httpc = new XMLHttpRequest(); // simplified for clarity
var url = "get_data.php";
httpc.open("POST", url, true); // sending as POST
httpc.onreadystatechange = function() { //Call a function when the state changes.
if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
alert(httpc.responseText); // some processing here, or whatever you want to do with the response
}
};
httpc.send(params);
}
</script>
call PHP script
<!-- rest of document omitted -->
Whatever get_data.php produces, that will appear in httpc.responseText. Error handling, event registration and cross-browser XMLHttpRequest compatibility are left as simple exercises to the reader ;)
See also Mozilla's documentation for further examples
I run into a similar issue the other day. Say, I want to pass data from client side to server and write the data into a log file. Here is my solution:
My simple client side code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<title>Test Page</title>
<script>
function passVal(){
var data = {
fn: "filename",
str: "this_is_a_dummy_test_string"
};
$.post("test.php", data);
}
passVal();
</script>
</head>
<body>
</body>
</html>
And php code on server side:
<?php
$fn = $_POST['fn'];
$str = $_POST['str'];
$file = fopen("/opt/lampp/htdocs/passVal/".$fn.".record","w");
echo fwrite($file,$str);
fclose($file);
?>
Hope this works for you and future readers!
I'd use JSON as the format and Ajax (really XMLHttpRequest) as the client->server mechanism.
Using cookies is a easy way. You can use jquery and a pluging as jquery.cookie or create your own.
Using Jquery + jquery.cookie, by example
<script>
var php_value = '<?php echo $php_variable; ?>';
var infobar_active = $.cookie('php_value');
var infobar_alert = any_process(infobar_active);
//set a cookie to readit via php
$.cookie('infobar_alerta', infobar_alerta );
</script>
<?php
var js_value = code to read a cookie
?>
I've found this usefull Server-Side and Hybrid Frameworks:
http://www.phplivex.com/
http://www.ashleyit.com/rs/
I've been using Ashley's RSJS Script to update values in HTML without any problem for a long time until I met JQuery (ajax, load, etc.)
There's a few ways, the most prominent being getting form data, or getting the query string. Here's one method using JavaScript. When you click on a link it will call the _vals('mytarget', 'theval') which will submit the form data. When your page posts back you can check if this form data has been set and then retrieve it from the form values.
<script language="javascript" type="text/javascript">
function _vals(target, value){
form1.all("target").value=target;
form1.all("value").value=value;
form1.submit();
}
</script>
Alternatively you can get it via the query string. PHP has your _GET and _SET global functions to achieve this making it much easier.
I'm sure there's probably more methods which are better, but these are just a few that spring to mind.
EDIT: Building on this from what others have said using the above method you would have an anchor tag like
<a onclick="_vals('name', 'val')" href="#">My Link</a>
And then in your PHP you can get form data using
$val = $_POST['value'];
So when you click on the link which uses JavaScript it will post form data and when the page posts back from this click you can then retrieve it from the PHP.
You can pass data from PHP to javascript but the only way to get data from javascript to PHP is via AJAX.
The reason for that is you can build a valid javascript through PHP but to get data to PHP you will need to get PHP running again, and since PHP only runs to process the output, you will need a page reload or an asynchronous query.
the other way to exchange data from php to javascript or vice versa is by using cookies, you can save cookies in php and read by your javascript, for this you don't have to use forms or ajax