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

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.

Related

AJAX callbacks without jquery [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How would I go about doing this? (AJAX)
Since the last time I asked this questions I failed horribly at being specific so I'm going to try again and be as as specific as possible.
First I have my data encoded in the json_encode function.
Looks like this for example:
{"test":"test value"}
What I want to do is make test into a javascript variable where it can hold the data of "test value". The json_encode data is on a page called index.php and the page that I want the variables to be defined in is called example.html. So what I want is in the javascript portion of the html is have a javascript variable called test and have it equal the string "test value".
Also I don't want jquery for this solution as I was restricted to not being able to do so. I can't use invisible forms and submit them.
Objects are associative arrays. They store key/values pairs. So All you have to do is:
var test = function(){}
test["hello"] = "world";
This will set hello as a variable and world as its value.
you can test this by doing
alert(test.hello);
Replace hello and world with the json key and value
var json = JSON.parse( {"test":"test value"} )
var testValue = json.test

Passing multiple values from MYSQL/PHP table to jQuery

Basically, I have working solution for this, but I'm wondering if it could (should?) be done better in some other way.
I have table I'm creating in PHP with values from MYSQL. Each item in table has multiple values. In each line there is single link and clicking on this link fires up jQuery function. In each link there is also VALUE attribute with values from multiple MYSQL fields and joined with &&:
PHP code is:
foreach ($this->_data as $l)
{
?>
...
<td>Link</td>
...
<?php
}
And jQuery function to fire up when clickin' on link is:
$(".clickMe").click(function() {
myData = $(this).attr('value').split('&&');
});
Script splits string in VALUE attribute on && and creates an array myData with values:
myData[0] => value passed from $l->_data1 in PHP
myData[1] => value passed from $l->_data2 in PHP
Is this the right way to do it?
It's fine, as long as you'll never have && in your data. You could use json_encode() in PHP and then decode this into an array in JavaScript. That would be a more standard solution.
I would recommend against using && which looks like a boolean AND. Instead I would probably use something like a pipe to separate them val1|val2.
I think you're better off passing the whole joined string in to PHP and splitting it out there. It saves you work on both ends having to put the two resultant values into the proper post or get variables to send to PHP.
Then on the PHP side, it's a little easier to validate the one value's format before splitting it, as you can use a single regex like:
// Validate both values at once: 1 or more digits, a pipe, and one or more digits
if (preg_match('/^(\d+)\|(\d+)$/', $_POST['jqueryinput'])) {
// explode() and use in PHP...
list($val1, $val2) = explode("|", $_POST['jqueryinput']);
}

Pass PHP Array to Javascript

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.

convert JSON object to query string and then back to an object

I know this has been asked a few times but please bear with me.
I have a google maps object which is rather complex (it contains various nodes, coordinates, etc) and I am trying to pass it as a query string.
I need a play javascript/jQuery solution.
I have tried the .param method which gives a jQuery error. The only thing that works is the "stringify" method which then creates a string that when appearing as a url looks a bit like this: %7B%5C"shape_1%5C"%3A%7B%5C"color%5C"%3A%5C"%237F0000%5C"%2C%5C"data%5C"%3A%7B%5C"b%5C"%3A%5B%7B%5C"Na%5C"%3A51.56727431757122%2C%5C"Oa%5C"%3A-0.10462402858888709%7D%2C....
php translates that as:
{\\"shape_1\\":{\\"color\\":\\"#7F0000\\",\\"data\\":{\\"b\\":[{\\"Na\\":51.56727431757122,\\"Oa\\":-0.10462402858888709},...
but having said that I don't want to use PHP, I am just showing you what it does in case it helps you see what stringify did to the object.
After I unescape with Javascript it looks a bit more normal like:
{\"shape_1\":{\"color\":\"#7F0000\",\"data\":{\"b\":[{\"Na\":51.56727431757122,\"Oa\":-0.10462402858888709},..
So as you can see, the unescaped sequence has these slashes everywhere.
When I try to evaluate that into a JSON object I get "Illegal token \". The parse method also fails. I just can't find any way to put this string back into the complex JSON object that it was.
I have looked online for various suggestions but they fail. I also don't understand why stringify injects all these slashes which simply shouldn't be there.
If anyone has an idea how to take that object, put it in a query string and then parse it back I would be very grateful.
Nick
Update:
The answer is this:
encodeURIComponent(JSON.stringify(myObject));
And then on the receiving end:
var a = querySt("data");
var b = decodeURIComponent(a);
var c = unescape(b);
var d = JSON.parse(c);
or all in one line
JSON.parse(unescape(decodeURIComponent(querySt("data"))));
Nick
See http://php.net/manual/de/security.magicquotes.php - you have to turn off magic quotes. They are old, deprecated stuff, they are insecure and break stuff.
Magic Quotes is a process that automagically escapes incoming data to the PHP script. It's preferred to code with magic quotes off and to instead escape the data at runtime, as needed.
Howto: http://www.php.net/manual/de/security.magicquotes.disabling.php
Try this to convert query string into json object
var queryStringToJSON = function (url) {
if (url === '')
return '';
var pairs = (url || location.search).slice(1).split('&');
var result = {};
for (var idx in pairs) {
var pair = pairs[idx].split('=');
if (!!pair[0])
result[pair[0].toLowerCase()] = decodeURIComponent(pair[1] || '');
}
return result;
}
You can use jQuery.param method to covert json object back to query string

Using FlashVars to pass variables to a SWF

I would like to pass over 50 items of variables from php to flash. Actually I want to pass array with foreach statement, looping through the array and assigning loop index to the variables and flash again accept the php values through looping. Is this possible?
If passing values through foreach or loop statement is impossible, I would like to break a new line in tag. how can I break a new line in FlashVars tag?
You can pass the values as a comma separated string (provided the values doesn't have commas, of course) - that way you can make them into an array in flash using string.split(",");
If you feel that this is pushing flashvars beyond its limit you might consider making an HTTP request back to your PHP page from within the SWF and send it whatever data you want.
with that many tags you might consider using a URLLoader or ExternalInterface call to get the information from a function or page, otherwise you can just push a list together something like this:
presuming $vararray is the array of vars you want to pass
PHP:
$flashvars = "";
$init = true;
for($i = 0; $i<count($vararray); $i+=1){
if($init == true){
$init=false;
}
else{
$flashvars.=&
}
$flashvars.="var$i=".$value;
}
then use the $flashvars string for the flashvars embed and run through the loaderInfo.Parameters array in flash
Or honestly just use XML - that's probably the best way to load in that many variables.

Categories