PHP array to JS array with jQuery and json_encode - php

I just want to get my PHP array to a JS array, what am I doing wrong here?
PHP:
// get all the usernames
$login_arr = array();
$sql = "SELECT agent_login FROM agents";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
array_push($login_arr, $row["agent_login"]);
}
$js_login_arr = json_encode($login_arr);
print $js_login_arr; // ["paulyoung","stevefosset","scottvanderlee"]
JS:
var login_arr = "<?= $js_login_arr; ?>";
alert(login_arr); // acn't even get the string in??
var obj = jQuery.parseJSON(login_arr);

Remove the quotes from the embedded PHP in your javascript. The notation is an array literal, and doesn't need quoting (assuming the PHP comment after js_login_arr is the what is printed into the javascript).

An easy way to do it is through delimiting. Take your array (don't use assoc arrays unless you need the field names), implode it into a string delimited by some character that shouldn't be used, say % or something, then in JS just explode on that character and voila, you have your array. You don't need to always use formalisms like JSON or XML when a simple solution will do the trick.

If you want to make php array to JSON you have to do this if $phpArray is actually an array.
var jsJSON = echo json_encode($phpArray)
If you want just to echo and turn to JSON you have to give it like a string:
$phpArray = '{'.$key1.':'.$val1','.$key2':'.$val2.'}';
This will work for sure.

Related

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); ?>;

Passing PHP array to Javascript via GET

I'm trying to pass an array to Javascript after it has sent a GET request to PHP.
Sending and retrieving the data works perfectly but I couldn't find anything about passing the data back as an array like this:
<?php
$result = mysql_query('blablabla');
//converting $result to an array?
echo $result_as_javascript_array;
?>
<script>
$('result').innerHTML = httpGet.responseText
</script>
Convert the data you get from MySQL to JSON. First build a "normal" PHP array as you would normally do, then pass it through the json_encode() function and return it.
On the client you have to parse the JSON string into a JS array or object. See this SO question for details: Parse JSON in JavaScript?
And please use something else for accessing MySQL. The extension you are using is basically obsolete: http://si1.php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated
you should use json_encode, which works fine, when directly assigning output to a javascript variable
<?php
$result = mysql_query('blablabla');
//first convert result to an associative array
$myarray = array();
while($fetch = mysql_fetch_assoc($result)){
$myarray[]=$fetch;
}
//converting $result to an array?
echo "<script>";
echo "var myArray = ".json_encode($myarray).";";
echo "</script>";
?>
<script>
//now you can use myArray global javascript variable
$('result').innerHTML = myArray.join(",");
</script>
You are looking for json_encode.
Use json_encode like this:
<?php
$result = mysql_query('blablabla');
//converting $result to an array?
echo json_encode($result);
?>
You probably won't want to put the response text right into the innerHTML of your element though unless you are wanting to display the json text in the element.
$arr = array();
while ($row = mysql_fetch_array($result)) {
$arr[] = $row;
}
echo $arr;
However, mysql_ is deprecated, use mysqli instead.
If you want to pass it as JSON, use this:
echo json_encode($arr);

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>

How to pass an array of objects from javascript to PHP

If I have, in javascript, something like:
entriesObj1 = new Object();
entriesObj1.entryId = "abc";
entriesObj1.mediaType = 2;
entriesObj2 = new Object();
entriesObj2.entryId = "def";
entriesObj2.mediaType = 1;
var entries = new Array();
entries[0] = entriesObj1;
entries[1] = entriesObj2;
What is the best method to pass it to php through an HTTP POST?
I've tried a jQuery plugin to convert the array to JSON. I've tried to create multiple hidden fields named "entries[]", each one with the JSON string. Somehow, I can't seem to decode my data with PHP's json_decode.
EDIT:
I tried changing the JSON plugin used to the one #Michal indicated and the results I get are the same:
Javascript
[
{"disciplina":"sdfsdfsdfsd","titulo":"sdfsdfsdf","componentes":"Bloco Completo"},
{"disciplina":"sdfsdfsdfsd","titulo":"sdfsdfsdf","componentes":"Bloco Completo"}
]
PHP Vardump:
string(756) "
[
{\"disciplina\":\"sdfsdfsdfsd\",\"titulo\":\"sdfsdfsdf\",\"componentes\":\"Bloco Completo\"},
{\"disciplina\":\"sdfsdfsdfsd\",\"titulo\":\"sdfsdfsdf\",\"componentes\":\"Bloco Completo\"}
]
"
When I use PHP's json_decode, I get NULL.
var_dump(json_decode($_REQUEST['entries']));
Output:
NULL
You need to convert JSON to a string (use JSON stringifier (https://github.com/douglascrockford/JSON-js) and POST the string (as a field value) to the PHP script which does json_decode()
Concat it using some characters like _ or %% then pass it to PHP.
In PHP file:
$ar = array();
$ar = explode('special_char',string pass from js);
echo "pre";print_r($ar);
echo "/pre";
well, the trouble seemed to be with the quotes that were being passed in the post, so i just replaced the quotes with open strings to my $_REQUEST.

How to read php array of string in javascript

var longitudeArray = new Array(<?php $result = count($longitudeArray);
if ($result > 1){
echo implode(',', $longitudeArray);
} else {
echo $longitudeArray[0];
}
?>);
$longitudeArray contain array of number like: $longitudeArray = array(23.54545, 2323.32);
Above script create following javascript array:
var longitudeArray = new Array(12.32444,21.34343,23.5454);
but if i passes string in $longitudeArray like:
$longitudeArray = array('one', 'two');
instead of integer value in $longitudeArray then my javascript array is not creating properly or its not working.
Try
var longitudeArray=<?=json_encode($longitudeArray)?>;
If you pass an array of strings to your code, you will end up without quotes around them in your generated javascript code. You need to add some quotes somehow, something like:
var longitudeArray = new Array("<?php echo implode('","', $longitudeArray);?>");
#Shad, very useful and efficient approach. In the same manner, if one is trying to convert a PHP array to pass back to a JavaScript function (EG: an AJAX callback), that would be accomplished as such:
$some_php_array = array( 'indexA' => 'nice', 'indexB' => 'move' );
json_encode($some_php_array);
Where the PHP data would look as follows in JavaScript:
{"indexA":"nice","indexB":"move"}

Categories