Getting PHP session array values into Javascript - php

I have stored array values in PHP session.
Now I want to retreive this array and convert it to javascript aray.
This is how I set PHP session:
var listone = ["one", "two", "three"];
function setSession(listone){
$.get(
"setSession.php",
{listone:listone}
);
}
So if once these values are set and I refresh the page, I check if the session has been set. If set, I want to do something like this:
<?php
session_start();
if(isset($_SESSION['listone']))
{
?>
listone = Array('<?php echo json_encode($_SESSION['listone']) ?>');
<?php
}
?>
When I do this, the 'listone' array is showing me like this:
listone[0] = [
listone[1] = "
listone[2] = o
listone[3] = n
listone[4] = e
listone[5] = "
.... etc
I know I am doing something wrong.
Is it the way I am storing the array in PHP session?
or
Is it the way I am retrieving it back to JS?
Thanks for any pointers. I am willing to dig more if guided properly :)

You may be trying to do one of two things here- either something to do with AJAX, which is expecting a JS response, or you're trying to access a session variable directly in JS.
If you simply wish to switch a PHP variable into a JS readable array, you can do:
json_encode($_SESSION['myarray']);
This would need to be a response readable & interpreted elsewhere by a JS script (e.g. an AJAX response).
PHP session variables arent accessable through JS directly, however, you can construct JS within PHP, wrapping the two together so you use PHP to output JS populated with the data held within your PHP session variable. The key here is the order of the code, and how your JS is structured- i.e. you will probably want to reference a global JS variable so the values are accessible by your other JS- or call a function etc...
So, you could have:
session_start();
if(!isset($_SESSION['myarray'])){
$_SESSION['myarray']=array('one', 'two', 'three');
}
echo "<script type='text/javascript'>
var myJSvariable = new Array();";
foreach($_SESSION['myarray'] as $key=>$value){
echo "myJSvariable[".$key."]=".$value.";";
}
echo "</script>";

Try to change your php file to this or a similar one
<?php
session_start();
$result = array();
if(isset($_SESSION['listone'])) {
$result['listone'] = $_SESSION['listone'];
}
echo json_encode($result);
?>
json_encode translate your array into a json array and you don't need to create a new one.
Plus I would put the required variables into an hash array and return just the json_encode of that array in order to have a cleaner code.

Related

db table names as alias in php GET-paramter?

I am looking for a possibility to pass db table name and column name via php and GET parameter.
I have a data grid with following structure:
table_name1.column1, table_name2.column1, table_name2.column1.
There is a search function for the grid, where I need those parameters.
From the url "?table_name1.column1=22" I am getting through the $_GET only table_name1_column1=22
How would you solve that?
Encode the variable with base64 and decode before you use.
I know that's dirty.
But php variables doesn't support periods (dots)
This is a documented feature of PHP. Its basically because PHP cannot have variable names with dots in them.
$x.y = 1 // is an invalid variable name
MANUAL Convert dots to _ in GET & POST
You can use serialize function of php to pass the text "table_name1.column1" in url. But for that you need to do few coding to get the result. Below I have given code which you can use:
Page1.php
<?php
$test = serialize('table_name1.column1=11::table_name2.column2=22');
?>
<a href='Page2.php?qs=<?php echo $test?>'>test</a>
Use this $test to pass as query string. In above example, I am passing on anchor tag click.
Page2.php
use following code to Unserialize the query string and use the values.
<?php
$test2 = unserialize($_GET['qs']);
$ex = explode('::',$test2);
$new_arr = array();
foreach($ex as $val)
{
$ex2 = explode('=',$val);
$new_arr[$ex2[0]] = $ex2[1];
}
echo $new_arr['table_name1.column1']; //print 11
echo $new_arr['table_name2.column2']; //print 22
?>
Hope this will help you :)
You need to seperate each parameter with &.
So: ?table=table_name1&column=column1

Store value of php array variable to javascript array variable

i have some problem, how to store value of php array variable to javascript array variable because i want to manipulate data in javascript
here's my code
<?php
$coor= array('-7.175993,112.650729|-7.17616,112.651139|-7.176591,112.650968|-7.176413,112.650552|-7.176104,112.650437','-7.176331,112.649924|-7.17632,112.650053|-7.176629,112.650048|-7.176629,112.649914');
?>
And i want to store all the values from $coor to var allcoor = new Array(), what i've been trying is use json_encode
<script>
var allcoor=new Array();
allcoor = "<?php foreach ($cobadeh as $t){echo json_encode($t);} ?>";
//for some example of manipulation array variable javascript
mySplitResult = allcoor[0].split("|");
...
</script>
What I want is manipulation of javascript array variable, and that code didn't work, can anyone help?
You need to start out with a php array that mirrors the javascript array that you want. Then output the results of json_encode on that array.
For this I am assuming you want an array of arrays.
<?php
$coorStr = "-7.175993,112.650729|-7.17616,112.651139|-7.176591,112.650968|-7.176413,112.650552|-7.176104,112.650437','-7.176331,112.649924|-7.17632,112.650053|-7.176629,112.650048|-7.176629,112.649914";
$coor= explode("|",$coorStr);
$coor = array_map(function($a) { return explode(",", $a); }, $coor);
?>
allcoor = <?php echo json_encode($cobadeh); ?>;
The first explode command splits the string into an array of elements containing each of the coordinate pairs.
The array_map call splits each of element in an array.
Finally the json_encode formats the data correctly for a javascript assignment.
Since the variable is a php array and you want it as a javascript array
first you create an array in the php side
$coor='-7.175993,112.650729|-7.17616,112.651139|-7.176591,112.650968|-7.176413,112.650552|-7.176104,112.650437','-7.176331,112.649924|-7.17632,112.650053|-7.176629,112.650048|-7.176629,112.649914';
$corar = explode("|", $coor);
and then in the javascript side you can do
var allcoor = <?php echo json_encode($corar); ?>;

json encoding 2 dimension array

I have the following in php:
$query = mysql_query($sql);
$rows = mysql_num_rows($query);
$data['course_num']=$rows;
$data['course_data'] = array();
while ($fetch = mysql_fetch_assoc($query) )
{
$courseData = array(
'course_name'=>$fetch['course_name'],
'training_field'=>$fetch['training_field'],
'speciality_field'=>$fetch['speciality_field'],
'language'=>$fetch['language'],
'description'=>$fetch['description'],
'type'=>$fetch['type'],
);
array_push($data['course_data'],$courseData);
}
echo json_encode($data);
when I receive the result of this script in jquery (using post)
I log it using :
console.log(data['course_data']);
and the output is :
[Object { course_name="Introduction to C++", training_field="Engineering" , speciality_field="Software", more...}]
But I can't seem to figure out how to access the elements.
I tried
data['course_data'].course_name
data['course_data']['course_name']
Nothing worked. Any ideas
When you array_push($data['course_data'],$courseData); you are actually putting $courseData at $data['course_data'][0] and therefore you would access it in JavaScript as data['course_data'][0]['course_name'].
If you only intend to have one result, instead of array_push($data['course_data'],$courseData); you should just specify $data['course_data'] = $courseData. Otherwise, you should iterate over data['course_data'] like so:
for (i in data['course_data']) {
console.log(data['course_data'][i]['course_name']);
}
You should specify the index in the first array for instance
data['course_data'][0]['course_name'];
you could make it better if you had defined the first array just as variable not a variable within an array
$data['course_data'][0]['course_name']
should do the trick. If not please send the output of var_dump($data)
Assuming the PHP code is correct, you will receive a JSON data like:
{
"course_num":34,
"course_data":[
{
"course_name":"name_value",
....
},
....etc (other object based on SQL result)
]
}
So, if you want to access to the total number of result:
data.course_num
If you want to access to the first element of the list of result:
data.course_data[0]
If you want to access to the name of the first element of the list of result:
data.course_data[0].course_name
or
data.course_data[0]['course_name']
use jquery's parseJSON method to get all the goodies out of the json object...
http://api.jquery.com/jQuery.parseJSON/

How to get array from JSON?

I am trying to fetch data from MySQL table that have 2 columns, Temperature and Value. I want to store these values to JSON and then to pass to the client side script. My PHP code is:
database2json.php:
<?php
$con = mysql_connect("localhost", "root", "123456");
if (!$con) {
die('Could not connect:' . mysql_error());
}
mysql_select_db("klima", $con);
$result = mysql_query("select Dan, Temperatura from TEMPERATURA");
$niz = array();
while ($row = mysql_fetch_array($result)) {
$niz[$row['Dan']] = $row['Temperatura'];
}
mysql_close($con);
$obj = json_encode($niz);
echo $obj;
?>
When I run this file on server I get this:
{"1":"-1","2":"0","3":"0","4":"0","5":"4","6":"5","7":"3","8":"2","9":"2","10":"1","11":"-2","12":"-2","13":"0","14":"1","15":"-2","16":"-1","17":"-1","18":"-2","19":"-1","20":"3","21":"-1","22":"0","23":"1","24":"3","25":"1","26":"1","27":"-1","28":"-1","29":"4","30":"5","31":"5"}
That is what is expected.
Html is nothing special.
index.html:
<html>
<head>
<title>jQuery</title>
<script src="jquery.js" type="text/javascript"></script>
<script src="custom.js" type="text/javascript"></script>
</head>
<body>
<div id="id1"></div>
</body>
</html>
Now I call php from jQuery and to show these values.
custom.js:
$(document).ready(function(){
$.post('database2json.php', function(data){
$('#id1').html(data);
},
"json");
});
This also gives same output like php:
{"1":"-1","2":"0","3":"0","4":"0","5":"4","6":"5","7":"3","8":"2","9":"2","10":"1","11":"-2","12":"-2","13":"0","14":"1","15":"-2","16":"-1","17":"-1","18":"-2","19":"-1","20":"3","21":"-1","22":"0","23":"1","24":"3","25":"1","26":"1","27":"-1","28":"-1","29":"4","30":"5","31":"5"}
Now I dont know how to convert this into array of [Dan, Temperatura]. I need this array to forward to chart and plot data (I am not asking about plotting, just to get array).
How to achieve this?
Your output
{"1":"-1","2":"0","3":"0",...,"31":"5"}
Is a JavaScript object in its current form. You can simply access it as:
alert(data["1"]);
// -1
alert(data["31"]);
// 5
Note that the common syntax for object literals is dot notation: object.propertyname, but that will not work for numeric property names like your 1-31 indexes. So instead you use the bracketed property name as in data["1"].
If you really need it as an indexed array, you can convert it as:
var array = [];
for (key in data) {
array[key] = data[key];
}
// Now array is an Array with similar structure to the object data
Update
There is another possibility to get this data as a proper array directly from PHP. You can wrap the output in an additional array like this:
// Wrap the array in another array indexed as niz
$obj = json_encode(array("niz" => $niz));
echo $obj;
I have something like your code in my project. It is like this:
$final = array('msg' => $msg, 'result' => $result);
echo json_encode($final);
As you see, I made an array with 2 key and value. This code works fine for me. try to obey the method above to create your array and test it again. I hope you can solve your problem.
If I understand correctly, you want to convert PHP's JSON output to an actual array, right?
You can simply use eval() for that.
myArray = eval(data);
WARNING: Eval is considered unsafe and you should only use it for trusted sources. Make sure that there is absolutely no way for anything else than your PHP script to be evaluated.

Passing a multidimensional PHP array to javascript

I have an array($my_array) that looks something like:
array(2) {
[25]=>int(10)
[30]=>int(8)
}
I'd like to assign it to a javascript array, but am having difficulties doing it. Any suggestions?
Edit: At first, I thought I could just assign it like a string, but that isn't working:
var photo_limit = $my_array;
I tried also doing a var_dump into my js value.
I'm currently trying to use something like:
for($i=0;$i<count($my_array); $i++){
echo "a[$i]='".$a[$i]."';\n";
}
Thanks.
The best way is to use json_encode. See json_encode reference
Used like this:
<script>
var array = <?php echo json_encode($array)?>;
</script>
Note, hovewer, that you'll receive Javascript object, instead of array. At a glance the only difference is if you have string keys in your array, you'll be able to access them in JS like array.*string key*, i.e. using dot notation.
1: json_encode your PHP array.
2: Decode the JSON string in JavaScript using eval(alternative: jQuery.parseJSON)
<script>
var arr = eval('(<?php echo json_encode($thePhpArray); ?>)');
</script>

Categories