Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a two-dimensional php array, $phpar, in which both dimensions are indexed (0,1,2,...), and all values are plain text. Within a JavaScript function, I want to convert this array into a two-dimensional JavaScript array. I know the following code doesn't work, but it illustrates what I want to do.
jsfunction() {
var jsarray = new Array();
jsarray = <?php json_encode($phpar); ?>;
}
If the returned value is something other than a regular js array, like a JSON string, I need some help parsing that into what I want, please.
I'm not exactly sure where your problem is...but the basic operation of json_encode simply looks like:
<script type="text/javascript">
var jsarray = <?php echo json_encode($phpar); ?>;
</script>
Frankly, I don't see why the other people are suggesting throwing a javascript-compatible object/array into a string, and worse the way they did it is wrong. If you want a JSON object string, this is the correct way of doing it:
<script type="text/javascript">
var jsarray_string = <?php echo json_encode(json_encode($phpar)); ?>;
// ^ ^------ php array to js array
// '------------------ php string to js string
</script>
By the way, javascript objects can be accessed like arrays. Example:
var myArray = {1: 'hi', 2: 'bye'};
alert(myArray[2]); // this works!
The only difference is that myArray is not really a javascript array, eg, myArray.constructor is not Array().
What are you actually trying accomplish here in terms of you application's functionality?
PHP is a backend language and JavaScript is a frontend language. If you need the frontend to retrieve an object from the backend to use in your JavaScript you should use Ajax as opposed to putting PHP code inside your JavaScript.
Your Ajax method will call the relevant PHP method using an MVC-style URL ('/mycontroller/mymethod'). The PHP method should use use associative array(s) since JSON objects are key-value pairs. You should json_encode the array before returning it.
Here's some sample PHP code:
<?php #foo.php
public function bar() {
$array = ('first-name' => 'John', 'last-name' => 'Doe');
return json_encode($array);
}
On the frontend, your JSON object will consist of the same key value pairs as your associative array:
var getBar = function() {
$.get('/foo/bar', function(data) {
var string = 'My name is ' + data.first-name + ' ' + data.last-name';
alert(string);
}, json);
};
Related
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to fetch array keys with jQuery?
php built-in function array_keys(), equivalent in jquery
is there any built in function in jquery similar to that of php array_keys(),.
please suggest
You will have to define your own function to get the same functionality. Try this:
function arrayKeys(input) {
var output = new Array();
var counter = 0;
for (i in input) {
output[counter++] = i;
}
return output;
}
arrayKeys({"one":1, "two":2, "three":3}); // returns ["one","two","three"]
No there isn't anything specific in jQuery for this. There is a javascript method but it is not widely supported yet Object.keys() so people don't use it for generic projects. Best thing i could think of is
var keys = $.map(your_object, function(value, key) {
return key;
});
You don't need jQuery or any other library for this -- it's a standard part of Javascript.
for(var key in myObject) {
alert(key);
}
That should be sufficient for you to loop through the object. But if you want to actually get the keys into their own array (ie turn it into a genuine clone of the php function), then it's fairly trivial to extend the above:
function array_keys(myObject) {
output = [];
for(var key in myObject) {
output.push(key);
}
return output;
}
Note, there are caveats with using the for(..in..) technique for objects that have properties or methods that you don't want to include (eg core system properties), but for a simple object that you've created yourself or from a JSON string, it's ideal.
(For more info on the caveats, see http://yuiblog.com/blog/2006/09/26/for-in-intrigue/)
Take a look at PHPJS, a project that aims to reproduce many PHP functions in vanilla JavaScript with minimal dependencies. In your case, you want array_keys.
In JavaScript there's no such thing like associative arrays. Objects (object literals) handle similar cases.
var keys = [], i = 0;
for( keys[ i++ ] in yourObject );
And now keys contains all yourObject property names (keys).
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.
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
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.
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.