sending array from php to jquery - php

how do i pass an array from php to jquery
both are in same file , i just have an array named $array2 with data that will be used to make graph
below code is using chartdata but i want to use variable from my php script
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var chart;
var chartData = [{
student: 5,
marks: 0},
{
student: 8,
marks: 50},
{
student: 10,
marks: 100}];
AmCharts.ready(function() {
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.categoryField = "marks";
chart.startDuration = 1;
// AXES
// category
var categoryAxis = chart.categoryAxis;
categoryAxis.labelRotation = 90;
categoryAxis.gridPosition = "student";
// value
// in case you don't want to change default settings of value axis,
// you don't need to create it, as one value axis is created automatically.
// GRAPH
var graph = new AmCharts.AmGraph();
graph.valueField = "student";
graph.balloonText = "[[category]]: [[value]]";
graph.type = "column";
graph.lineAlpha = 0;
graph.fillAlphas = 8.4;
chart.addGraph(graph);
chart.write("chartdiv");
});
</script>

you can use json data to pass php to jquery.
in php
$php_data = json_encode($your_php_data_in_array);
assigning to jquery
var data = <?php echo $php_data ;?>
getting the value in jquery
var chart_data_arr = json_decode(data);
now you have the data in array in jquery.

The simplest (and not necessarily the most scure/efficient/modular/blah blah) possible way you can just dump it using json_encode
var chartData = [{
student: 5,
marks: 0},
{
student: 8,
marks: 50},
{
student: 10,
marks: 100}];
//Instead
var chartData=<?php echo json_encode($chartdata)?>
Alternately, you would pass it using a json action that will render the json at a certian link and use jquery to query this url and then generate the chart with that data.

To use php data in javascript use:-
var javascriptVariable = <?php echo json_encode($php_array); ?>;
So javascriptVariable would become an object/array as per your php data.

Try this :
<?php
$your_php_array = array(.....);
?>
var chartData = <?php json_encode($your_php_array)?>;
ref: http://php.net/manual/en/function.json-encode.php

Related

multiple highcharts on one page

I'm wishing to render multiple charts using mysql data, there will be more or less charts depending on a particular search. I've successfully created a single chart, and my php file echoes the required json format nicely.
Now, what I would like is to be able to loop over an array and draw new charts based on the array vales being parsed to the php which in turn provides different json data to be rendered.
by the way, my javasript is very limited so here goes my code and thoughts:
<script type="text/javascript">
$(function () {
var chart;
var venue = <?php echo json_encode($venue_name); ?>; /* parsed to php file */
var distances = <?php echo json_encode($data); ?>; /* array to be looped over */
$(document).ready(function() {
var options = {
....
series: []
....
};
//
$.each(distances, function() {
$.each(this, function(name, value) {
// do some ajax magic here:...
GET 'myphpfile.php?venue='+venue+'&'+distances
function drawNewChart(){
$('#mainSite').append('<div id="container" style="float:left; display:inline"></div>');
chart = new Highcharts.Chart(options);
});
});
</script>
What I have learnt is that I cannot loop an include php file which has the completed php and jquery...
this will create other charts. every time u want create new chart , u must give new name chart like i do chart2
paste this bellow and it will give you other chart.
<script type="text/javascript">
$(function () {
var chart2;
var venue2 = <?php echo json_encode($venue_name); ?>; /* <---use other variable here of $venue_name */
var distances2 = <?php echo json_encode($data); ?>; /* <---use other variable of $data */
$(document).ready(function() {
var options = {
....
series: []
....
};
//
$.each(distances2, function() {
$.each(this, function(name, value) {
// do some ajax magic here:...
GET 'myphpfile.php?venue2='+venue2+'&'+distances2
function drawNewChart(){
$('#mainSite').append('<div id="container" style="float:left; display:inline"></div>');
chart2 = new Highcharts.Chart(options);
});
});
</script>
Instead of using many variables, you can push your charts to array.
var charts = [];
charts.push(new Highcharts(options));
Then you can avoid of using index etc.

How To Pass PHP Variable To This Javascript Function?

Let's say I have this PHP variables :
$SelectedCountry = "USA";
$SelectedState = "Texas";
on the other hand, I have this javascript function to display all available countries and states :
function print_country(country_id){
// given the id of the <select> tag as function argument, it inserts <option> tags
var option_str = document.getElementById(country_id);
option_str.length=0;
option_str.options[0] = new Option('Where do you live now?','');
option_str.selectedIndex = 0;
for (var i=0; i<country_arr.length; i++) {
option_str.options[option_str.length] = new Option(country_arr[i],country_arr[i]);
}
}
function print_state(state_id, state_index){
var option_str = document.getElementById(state_id);
option_str.length=0; // Fixed by Julian Woods
option_str.options[0] = new Option('Select state','');
option_str.selectedIndex = 0;
var state_arr = s_a[state_index].split("|");
for (var i=0; i<state_arr.length; i++) {
option_str.options[option_str.length] = new Option(state_arr[i],state_arr[i]);
}
}
my question is... how to make 'USA' and 'Texas' becomes selected <option> which generated by those two javascript functions? thanks.
NOTE #1 : you can see the complete code of javascript here : http://sourceforge.net/projects/countries/files/
NOTE #2 : those function called by adding this line on my PHP :
<script type="text/javascript" src="scripts/countries.js"></script>
<script language="javascript">print_country("country");</script>
so basically I need your help how to pass that PHP variables so that it can be 'received' by javascript function INSIDE that countries.js file.
One way is to just echo out some JavaScript statements:
<script>
<?php
echo "
var SelectedCountry = '$SelectedCountry';
var SelectedState = '$SelectedState';
";
?>
</script>
Then just use them in your loops to check if the option needs to be selected or not.
If you're going to be doing a lot of this sort of thing, though, embedding PHP into JavaScript isn't really the best approach. Read up on AJAX and PHP's json_encode() function.
There are two answers:
1 Use AJAX cal and pass back JSON
$.ajax({
url: '/myScript.php',
success: function(data) {
//Do something
}
});
myScript.php
return json_encode($myVar);
2 Embed PHP into the JavaScript
<script>
var myPHPVariable = <?php echo $myVar; ?>
</script>

Returning PHP array to Javascript array

I am trying to return my SQL query array into a javascript array and then display the info one at a time. I have found a few helpful posts already on here but I still cannot get it to work. I am new to ajax and so please forgive any stupid mistakes. Below is the php followed by a description.
php: this is in an external file from index.php
<?php
include('connection.php');
$query = "SELECT * FROM photos";
$queryresult = mysql_query($query);
while ( $line = mysql_fetch_array($result) ) {
$path[] = $row[0];
}
$paths = json_encode($path);
header('Content-type: application/json');
echo $paths;
?>
This gets the results (they are file paths) array and json encodes them to pass to javascript. Connection.php is correct and it is working.
HTML/Javascript:
<html>
<head>
<script src="JavaScript/gjs.js" type="text/javascript"></script>
<script src="jquery/jquery-1.4.3.min.js" type="text/javascript"></script>
<script>
function imageload(){
var i = 1;
$.getJSON('phpfiles/getpiccode.php', function(data) {
var can = document.getElementById('canvas').getContext('2d');
$.each(data,function(idx, row){
var img = new Image();
img.onload = function(){
can.drawImage(img, 0, 0, 1280, 800);
}
img.src = row;
i++;
});
});
}
</script>
</head>
<body>
<div class="container">
<canvas id="canvas" class="canvas-one" width="1280" height="800">
<script>imageload();</script>This text is displayed if your browser does not support HTML5 Canvas</canvas>
</div>
</body>
</html>
I hope that makes sense. Thanks again!
Use json_encode() to encode it as JSON.
In recent browsers you can simply turn the string from that function into a JavaScript object using var obj = JSON.parse(yourstring); - but better use e.g. jQuery for AJAX and JSON parsing.
Update: Your JavaScript should looke like that to iterate over the data from your query:
$.getJSON('phpfiles/getpiccode.php', function(data) {
// get canvas object. it's the same for all images so only do it once
var can = document.getElementById('canvas').getContext('2d');
// iterate over the elements in data
$.each(data, function(idx, row) {
var img = new Image();
img.onload = function() {
can.drawImage(img, 0, 0, 1280, 800);
}
img.src = row;
});
});
However, it might not do what you want: It will draw all images pretty much at once at the same position.
Also replace <script>imageload() </script> (assuming that's the function containing your JavaScript) with <script type="text/javascript">imageload();</script> as that's the correct/proper syntax.
In your PHP code you'll have to replace return $paths; with echo $paths; unless you are using some framework which relies on your file returning something. Additionally it'd be good to send a JSON header: header('Content-type: application/json');
PS: SELECT * combined with MYSQL_NUM is a BadThing. It relies on the columns in the table having a certain order. If you just need one column use "SELECT columnName"; if you need all, use MYSQL_ASSOC to get an associative array.

How to access PHP session variables from jQuery function in a .js file?

How to access PHP session variables from jQuery function in a .js file?
In this code, I want to get "value" from a session variable
$(function() {
$("#progressbar").progressbar({
value: 37
});
});
You can produce the javascript file via PHP. Nothing says a javascript file must have a .js extention. For example in your HTML:
<script src='javascript.php'></script>
Then your script file:
<?php header("Content-type: application/javascript"); ?>
$(function() {
$( "#progressbar" ).progressbar({
value: <?php echo $_SESSION['value'] ?>
});
// ... more javascript ...
If this particular method isn't an option, you could put an AJAX request in your javascript file, and have the data returned as JSON from the server side script.
I was struggling with the same problem and stumbled upon this page. Another solution I came up with would be this :
In your html, echo the session variable (mine here is $_SESSION['origin']) to any element of your choosing :
<p id="sessionOrigin"><?=$_SESSION['origin'];?></p>
In your js, using jQuery you can access it like so :
$("#sessionOrigin").text();
EDIT: or even better, put it in a hidden input
<input type="hidden" name="theOrigin" value="<?=$_SESSION['origin'];?>"></input>
If you want to maintain a clearer separation of PHP and JS (it makes syntax highlighting and checking in IDEs easier) then you can create JQuery plugins for your code and then pass the $_SESSION['param'] as a variable.
So in page.php:
<script src="my_progress_bar.js"></script>
<script>
$(function () {
var percent = <?php echo $_SESSION['percent']; ?>;
$.my_progress_bar(percent);
});
</script>
Then in my_progress_bar.js:
(function ($) {
$.my_progress_bar = function(percent) {
$("#progressbar").progressbar({
value: percent
});
};
})(jQuery);
You can pass you session variables from your php script to JQUERY using JSON such as
JS:
jQuery("#rowed2").jqGrid({
url:'yourphp.php?q=3',
datatype: "json",
colNames:['Actions'],
colModel:[{
name:'Actions',
index:'Actions',
width:155,
sortable:false
}],
rowNum:30,
rowList:[50,100,150,200,300,400,500,600],
pager: '#prowed2',
sortname: 'id',
height: 660,
viewrecords: true,
sortorder: 'desc',
gridview:true,
editurl: 'yourphp.php',
caption: 'Caption',
gridComplete: function() {
var ids = jQuery("#rowed2").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var cl = ids[i];
be = "<input style='height:22px;width:50px;' `enter code here` type='button' value='Edit' onclick=\"jQuery('#rowed2').editRow('"+cl+"');\" />";
se = "<input style='height:22px;width:50px;' type='button' value='Save' onclick=\"jQuery('#rowed2').saveRow('"+cl+"');\" />";
ce = "<input style='height:22px;width:50px;' type='button' value='Cancel' onclick=\"jQuery('#rowed2').restoreRow('"+cl+"');\" />";
jQuery("#rowed2").jqGrid('setRowData', ids[i], {Actions:be+se+ce});
}
}
});
PHP
// start your session
session_start();
// get session from database or create you own
$session_username = $_SESSION['John'];
$session_email = $_SESSION['johndoe#jd.com'];
$response = new stdClass();
$response->session_username = $session_username;
$response->session_email = $session_email;
$i = 0;
while ($row = mysqli_fetch_array($result)) {
$response->rows[$i]['id'] = $row['ID'];
$response->rows[$i]['cell'] = array("", $row['rowvariable1'], $row['rowvariable2']);
$i++;
}
echo json_encode($response);
// this response (which contains your Session variables) is sent back to your JQUERY
You cant access PHP session variables/values in JS, one is server side (PHP), the other client side (JS).
What you can do is pass or return the SESSION value to your JS, by say, an AJAX call. In your JS, make a call to a PHP script which simply outputs for return to your JS the SESSION variable's value, then use your JS to handle this returned information.
Alternatively store the value in a COOKIE, which can be accessed by either framework..though this may not be the best approach in your situation.
OR you can generate some JS in your PHP which returns/sets the variable, i.e.:
<? php
echo "<script type='text/javascript'>
alert('".json_encode($_SESSION['msg'])."');
</script>";
?>
This is strictly not speaking using jQuery, but I have found this method easier than using jQuery. There are probably endless methods of achieving this and many clever ones here, but not all have worked for me. However the following method has always worked and I am passing it one in case it helps someone else.
Three javascript libraries are required, createCookie, readCookie and eraseCookie. These libraries are not mine but I began using them about 5 years ago and don't know their origin.
createCookie = function(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
readCookie = function (name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
eraseCookie = function (name) {
createCookie(name, "", -1);
}
To call them you need to create a small PHP function, normally as part of your support library, as follows:
<?php
function createjavaScriptCookie($sessionVarible) {
$s = "<script>";
$s = $s.'createCookie('. '"'. $sessionVarible
.'",'.'"'.$_SESSION[$sessionVarible].'"'. ',"1"'.')';
$s = $s."</script>";
echo $s;
}
?>
So to use all you now have to include within your index.php file is
$_SESSION["video_dir"] = "/video_dir/";
createjavaScriptCookie("video_dir");
Now in your javascript library.js you can recover the cookie with the following code:
var videoPath = readCookie("video_dir") +'/'+ video_ID + '.mp4';
I hope this helps.
Strangely importing directly from $_SESSION not working but have to do this to make it work :
<?php
$phpVar = $_SESSION['var'];
?>
<script>
var variableValue= '<?php echo $phpVar; ?>';
var imported = document.createElement('script');
imported.src = './your/path/to.js';
document.head.appendChild(imported);
</script>
and in to.js
$(document).ready(function(){
alert(variableValue);
// rest of js file

Passing PHP array into Javascript through JSON to update Google Chart

I have three PHP arrays that I've encoded with json... extra PHP code has been omitted because the arrays work properly.... Additionally, the HTML tags that call the google chart have been omitted for sake of brevity...
<?php
$encoded_line_volume = json_encode($LineVol) . "\n";
$encoded_loan_volume = json_encode($LoanVol) . "\n";
$encoded_cluster_name = json_encode($ClusterLine) . "\n";
?>
I would like to access these three arrays in Javascript to update my Google Chart dynamically.
<script type="text/javascript">
google.load("visualization", "1", {packages:["columnchart"]});
google.setOnLoadCallback(drawChart);
var linevol = new Array; // This would be the first array passed from PHP
var loanvol = new Array; // This would be the second array passed from PHP
var clusters = new Array; // This would be the third array passed from PHP
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Cluster');
data.addColumn('number', 'Loans');
data.addColumn('number', 'Lines');
/* create for loops to add as many columns as necessary */
var len = jsonarray.length;
data.addRows(len);
for(i=0; i<len; i++) {
data.setValue(i, 0, ' '+clusters[i]+''); /* x-axis */
data.setValue(i, 1, linevol[i]); /* Y-axis category #1*/
data.setValue(i, 2, loanvol[i]); /* Y-axis category #2*/
}
/*********************************end of loops***************************************/
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240, is3D: true, title: 'Prospect Population', legend: 'right'});
}
</script>
You probably want them to become Javascript variables. When your php executes, it creates code your web browser then interprets. So you want to define javascript strings using php. For example:
<script type="text/javascript">
var encoded_line_volume = <?php echo json_encode($LineVol) ?>;
var encoded_loan_volume = <?php echo json_encode($LoanVol) ?>;
var encoded_cluster_name = <?php echo json_encode($ClusterLine) ?>;
</script>
Then those variables are accessible to subsequent javascript.
This is how can you generate data dynamically from PHP, generate a JSON formatted output properly and read it from JavaScript (JQuery required) and load it to Google Visulization (Charts) API.
PHP (Server) Side:
function returnData() {
$data = Array ();
$data [] = Array ("Name", "Value");
$data [] = Array ("Apple", 5);
$data [] = Array ("Banana", 3);
header('content-type: application/json');
echo json_encode($data);
}
Javascript (Client) Side:
var jsonData = null;
var jsonDataResult = $.ajax({
url: dataURL,
dataType: "json",
async: false,
success: (
function(data) {
jsonData = data;
})
});
var data = new google.visualization.arrayToDataTable(jsonData);
This is one of the best examples I did which can help you : its tested and working nicely : Create two pages one called index.php and another one called get_json.php :
This is not exactly the codes you posted but exactly the same idea and it answers the quetion.
the codes for index.php
<html>
<head>
<title>King Musa Graph</title>
<!-- Load jQuery -->
<script language="javascript" type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js">
</script>
<!-- Load Google JSAPI -->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "get_json.php",
dataType: "json",
async: false
}).responseText;
var obj = jQuery.parseJSON(jsonData);
var data = google.visualization.arrayToDataTable(obj);
var options = {
title: 'King Musa'
};
var chart = new google.visualization.LineChart(
document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;">
</div>
</body>
</html>
codes for get_json.php
<?php
$data = Array ();
$data [] = Array ("Name", "Value");
$data [] = Array ("PHP", 78);
$data [] = Array ("JAVA", 1000);
$data [] = Array ("HTML", 129);
$table = json_encode($data);
// header('content-type: application/json');
echo $table ; // this line is important it should be not disabled
?>

Categories