Pass PHP Array to Javascript - php

Am trying to pass an array of values from PHP function to Javascript. Not sure if I am doing it correctly.
PHP:
function toggleLayers(){
for($i=0;$i<$group_layer_row;$i++){
$toggleArray=mb_convert_encoding(mssql_result ($rs_group_layer, $i, 0),"UTF-8","SJIS")."_".mb_convert_encoding(mssql_result ($rs_group_layer, $i, 1),"UTF-8","SJIS");
return $toggleArray;
}
}
JS:
var myArray = [JSON.parse("<?php echo json_encode($toggleArray); ?>")];
for(var i=0;i < myArray.length; i++){
if($myArray.getVisibility()==true){
$myArray.getVisibility(false);
}
else{
$myArray.getVisibility(true);
}
}
SQL (for reference):
$con = mssql_connect("myServer", "myUsername", myPassword");
$sql = "SELECT * FROM m_group_layer WHERE group_id=\"".$_SESSION["group_id"]."\" ORDER BY display_order";
$rs_group_layer = mssql_query ($sql, $con);
$group_layer_row = mssql_num_rows($rs_group_layer);
I have been looking at some other similar questions, and the answers are either vague and/or there are a few thousand of them.
Would appreciate any help, also please try to explain as if you were writing a book called "Idiot's Guide to Passing PHP Arrays to JS"
Thanks for your help.
Edit:
Sorry, my question was very vague. Here's what I'm trying to do:
1.PHP Function gets all records from table into array(in this case they are map layers)
2.Javascript receives PHP array and loops through adding if clause to toggle layers.
Hope this makes it clearer.

It's simpler than you think.
Change this line:
var myArray = [JSON.parse("<?php echo json_encode($toggleArray); ?>")];
To just:
var myArray = <?php echo htmlspecialchars(json_encode($toggleArray), ENT_NOQUOTES); ?>;
json_encode produces a json string. Echoing the string into a javascript context is the equivalent of a javascript literal. The htmlspecialchars is just for the necessary html escaping and is not unique to echoing json.
NOTE however that you can only json_encode a php object or array, not any scalar types like ints or strings. This is a limitation of JSON itself. In your toggleLayers() function, you are returning a string, not an array.

A thing that would be very useful to understand:
You sumply can't "pass an array of values from PHP function to Javascript".
But rather you have to create the javascript code using PHP just like you are creating HTML.
Thus, 3 simple step to solve any problem with PHP -> client transfers:
Create a pure client-side code you wish. Make it work. Save it somewhere.
Create a PHP code to produce that client-side code.
Compare the codes. If doesn't match - correct the PHP code. Repeat until done.

Related

Json_encode for .post?

can anyone explain the purpose of json_encode when doing a .post query.
This is what i often see in other's coding.
.post php script
...
...
echo json_encode($a);
I mean if i want to do a return from a .post script and returning an array via .post. Wouldn't i just need to do the following?
.post php script
...
...
$a = array("foo", "bar", "hallo", "world");
$string=implode(',',$a) in my php script
return $string;
javascript
$.post('$url',function(data){
data_arr=data.split(',');
//After which just get the values in the array
alert(data_arr[0]); //ALERTS 'foo'
alert(data_arr[1]); //ALERTS 'bar'
});
If anyone can just help by clearing this up for me and let me see the light for using json in this purpose, that would be great.
Perhaps its also due to my inept knowledge of JSON as well.
Would greatly appreciate it if anyone can advise me on why is it better to use JSON encode in this case and how am i suppose to use it via a .post request instead of just echoing out the string and split it later.
Thanks.
Using json_encode ensures that your data is always valid.
It doesn't really matter for simple data that you have control over, though imagine if someday you have a comma inside one of the values. With JSON encoded strings, you don't have to worry about an arbitrary separator token.
Also, with JSON you can easily encode Objects/Arrays without needing to reinvent the wheel.
First of all, in my opinion and practise, JSON syntax is fairly similar to Javascript objects and it's great when dealing with more complex data types that have to be sent/requested and parsed later on.
For example:
If you're doing a post request and you're serializing all the form fields which you validate server side (using PHP) you're most likely going to need to use key => value pairs like textbox_name => value. It's more logical to do it that way, than to select values by numeric indexes (what if the form layout changes?)
Example code using commas:
<?php
$array = array('Tom', 'Hanks', 'Football');
$string = join(',',$array);
echo $string; //it's obvious - the output is Tom,Hanks,Football
?>
The javascript that receives the string
$.post(url,{},function(data){
var values = data.split(',')
$("#name").text(values[0]);
$("#surname").text(values[1]);
$("#interests").text(values[2]);
});
So it makes sense right? But wouldn't it more sense to do this instead:
<?php
header('Content-type: application/json');
$array = array('name' => 'Tom', 'surname' => 'Hanks', 'interests' => 'Football');
echo json_encode($array);
?>
And the javascript:
$.post(url,{},function(data){
for(index in data) {
$("#"+index).text(data[index]);
}
//or
$("#name").text(data.name);
$("#surname").text(data.surname);
$("#interests").text(data.interests);
});
The same goes with parsing response data with Javascript. Having an object is more logical than having a CSV string.
Obviously it depends on the use case, but in general JSON gives you a logical structure of stringified Objects/Arrays which can be translated back into objects and arrays and looped through or manipulated in any way.
Also JSON is now a standard. Everyone uses it which means that it's not for no reason.
In other words - JSON data makes more sense.

Best Way to pass vars from PHP to javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What's the best way to pass a PHP variable to Javascript?
I have to do a function that automatically take care of passing variables from PHP to JavaScript in a simple and safe.
Currently stored in a class variable array with the values ​​of the variables, and then the idea is to extract in Javascript, but many doubts assail me what the (technically) best way to do this.
Also passes through my head several problems, especially when complex move to Javascript arrays or strings with accents, special symbols or symbols as quote or single quote, including problems with the function json_decode when work with chains with line breaks and carriage returns. (You get invalid JSON, I've had to do a cleaning function in PHP to avoid passing variables with these characters, but sometimes I need be)
I searched the web a lot, and I have found many answers but none terminade convince and more with the above problems.
An example:
The PHP Method (too simple):
var JsVars;
public function saveJsVar($key, $value) {
$this->JsVars[$key] = $value; //Possible need to clean certain characters like /n /r
}
The "javascript part"
<script>
var SistemVars = SistemVars || {};
<?php foreach ($JSVARS as $k => $var) { ?>
SistemVars.<?=$k?> = '' || '<?php echo $var ?>'; // Dont work with arrays only plain
<?php } ?>
</script>
Another option:
<script>
var SistemVars = SistemVars || {};
SistemVars = <?=json_encode($JSVARS)?> // Object, with plain and array BUT problems with certain characters.
</script>
The idea its use PHP (saveJsVar) to save plain variables and arrays, and set the vars in SistemVars object en JavaScript to use it like alert(SistemVars.ParamOne);
with your experience, what do you think is the best way to do this?
The 2nd option is the better way to do it, as it saves using a foreach loop. also, json_encode is made for this purpose, so why not use it :) And just FYI, <?= ...?> short tags for PHP are not used anymore Are PHP short tags acceptable to use?
<script>
var SistemVars = SistemVars || {};
SistemVars = <?=json_encode($JSVARS)?> // Object, with plain and array BUT problems with certain characters.
</script>
I like using hidden input elements and use/access their values with jQuery.
Doing this will allow you to keep your js clean - with no PHP code inside.
If you want to export all of your JS code into external files - this is the way.

Is there a version of the PHP array that is pass-by-reference?

I'm asking this because I'm working with a recursive function that generates a large array tree and the pass-by-copy aspect of the arrays are completely screwing with my head. I've tried using ArrayObject, but that's really an object, isn't it? None of the array_keys type array functions work with it, and json_encode doesn't understand that it's an array.
I'd like a version of the PHP array that feels, smells and looks like the normal array, but is pass-by-reference. Is there anything like that in PHP?
Woah woah hold up people; I'm well aware of the & symbol but that's what I'm trying to avoid. As my question specifies (^) I'm looking for a version of the PHP array that is pass-by-reference by default
I'd like a version of the PHP array that feels, smells and looks like
the normal array, but is pass-by-reference. Is there anything like
that in PHP?
No, There is nothing like that in PHP.
Json encode should be able to pass objects. But if you for some reason NEED an array, you can't use objects and then cast it as array before encoding to json?
<?php
$object = (object)array("number"=>1);
function addToTen($object){
if($object->number<10){
$object->number++;
addToTen($object);
}
}
addToTen($object);
echo json_encode((array)$object);
//echoes {"number":10} with or without casting it as an array
?>
You could also wrap your array in an object of course, like this:
$object = new stdClass;
$object->a = array();
function fillUpArray($object){
if(count($object->a)<10){
$object->a[] = "someValue";
fillUpArray($object);
}
}
fillUpArray($object);
echo json_encode($object->a);
//echoes ["someValue","someValue","someValue","someValue","someValue","someValue","someValue","someValue","someValue","someValue"]
I must admit though I don't entirely get what you're trying to accomplish here :S
Yes, see the PHP manual page: http://php.net/manual/en/language.references.pass.php
Stop using &references altogether, in php they get cumbersome pretty quickly, (being, unlike C pointers, almost transparent, the only way to check you're actually using a reference is by assigning junk to it and check the effect this has on a tree) and you don't seem willing to handle that level of subtlety.
(Nor to wrap it with an ArrayObject, apparently)
Are you aware objects ARE references?
Object-wrap every aspect of your tree and your life will instantly get less miserable.
I am not aware of any such built-in functionality in PHP that you ask. Also, you are quite reluctant to use references. Hmmm...you could send a request to the PHP dev team to include such stuff in PHP v6, along with unicode that is supposed to come, that would us all happy :).
However, can you use a class and assign your initial array to one of the class variables and then process it and get it back after the recursion. Not sure if that would work, but anyway here it is:
<?php
class noReference {
public $myData;
public function __construct( $data ) {
$this->myData = $data; // this is your initial array.
}
// this function works on the myData array and changes it.
public function myRecursiveFunction() {
// your code here
$this->myRecursiveFunction(); // called as per your logic
// your code here
}
public function getData() {
return $this->myData;
}
public function __destruct() {
unset( $this->myData );
}
}
$data = array(/*WHATEVER_PLEASES_YOU*/);
$noref = new noReference( $data );
// this will be your recuresive function
$noref->myRecursiveFunction();
//your data here
$result = $noref->getData();
?>
Let me know if this works. Cheers!
you can force php to pass things by reference by adding an &-sign to the parameter. read the documentation for more information.

PHP Array to jQuery array with JSON. ($.post, parseJSON, json_encode)

I am trying to get a php file setup to return the results of a MySQL database query from a jQuery AJAX call. The returned results will be an array. I have a very basic start where I am just getting some basic data back and forth to and from the php file, but am stuck with some basic syntax issues:
The PHP code:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
The jQuery code:
$.post("dbFile.php", str, function(theResponse){
alert('the response: ' + theResponse);
var obj = $.parseJSON(theResponse);
alert(obj.a);
I can print out obj.a, obj.b, obj.c... no problem. The problem is I will be incrementing a counter as I increment through the MySQL results. So, the array does not use letters, it uses numbers:
$arr[$i] = mysqlresults ... $i++;
So, in the JavaScript/jQuery I have an object (not an array). I can print out obj.a for example, but I can not print out obj.2 (for example). In other words, if I replace the letters with numbers in the php array, I don't know how to print them out in JavaScript/jQuery. Can I change the object that parseJSON returns into an array somehow (so that I can cycle through it)?
Use the array access syntax:
alert(obj[42]);
You can use:
alert(obj['a']);
See this question for more info.

json multidimensional array and jquery?

I create this output with PHP:
foreach ($bk as $blink) {
$out["url"][] = $blink->url;
$out["anchor"][] = $blink->anchor;
}
$json = Zend_Json::encode($out);
echo ($json);
I want to receive and process the output with a $.ajax call.
Could you point me to a nice tutorial about multidimensional arrays with javascript/jquery or help me loop* through the json results? I got a bit confused with it.
I am trying to put those on a table, so I will be using <td>url-i</td><td>anchor-i</td> . This part, I figured out how. To put the correct values on url-i and anchor-i is the problem.
I would imagine the JSON output for that will be something like:
{'url': ['url1', 'url2', ... ],
'anchor': ['anchor1', 'anchor2', ... ]}
If that is the case, then they will be of equal length (and importantly equal indexes) and you can loop through one of the two using jQuery.each().
$.getJSON('jsonapp.php', function(data) {
$.each(data.url, function(index, url) {
var anchor = data.anchor[index];
$('#mytable').append('<tr><td>' + url + '</td><td>' + anchor +'</td></tr>');
});
});
I've not run that code, so it might have a few flaws, but that's the gist of it.
PHP can try to cast objects into arrays by itself, and for simple stuff, it usually works fine.
As for multidimensional arrays, Javascript isn't too different from most other higher-level programming/scripting languages when it comes to arrays. Really, any tutorial online on multidimensional arrays will do just fine. A multidimensional array is simply an array of arrays.
When you receive the string client-side, you just want to parse it. jQuery has its own method, but you can use JSON.parse. Afterwards, based on how you've set up your arrays, you'd want to do something like this.
<? $count = count($json_parsed['url']); for($i = 1; $i < $count; $i++) : ?>
<td><?=$json_parsed['url'][$i];?></td>
<td><?=$json_parsed['anchor'][$i];?></td>
<? endfor; ?>
This may be philosophically not the best way to do it though. If you have a whole bunch of objects and you want to make a table out of them, the best way would be to create an array of those objects as represented by associative arrays (sort of like hash tables in other programming languages). PHP natively tries to convert objects into associative arrays. I wouldn't be surprised if Zend_Json::encode does it automatically. If it does, you might want to pull simply:
echo Zend_Json::encode($bk);
If not, let me know, and we'll talk about how to do that.
You could have a look on any template frameworks, but for this exact case it seams useful to check one of those two: pure by beebole or jquery pure html templates.
Doing it by yourself might be tempting but why to reinvent the well - I know from my experience, that frameworks are about 2 times faster, then self made code.

Categories