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>
Related
Im trying to query a database from a php file then return the results (userLOC of each row) to the calling Jquery function.
Calling Jquery:
$.post(url, data, function (data)
{
alert(data);
})
relavent PHP:
$sql = "Select * from location";
$result = mysql_query($sql);
$stack = array();
while($row = mysql_fetch_array($result))
{
array_push($stack, $row["userLOC"]);
}
return $stack;
The problem is that I cant return it correctly, if I "echo $stack" it does not work it says Im trying to convert the array to string. If I "echo $stack[0]" it will give me the first result in the array correctly so I know the values are being stored correctly (as are $stack[1], etc.) but this only sends the one value back. And if I "return $stack" as pictured nothing is alerted because nothing is echoed. How would I go about getting the whole array back so that I could iterate through and use them on the jquery side?
In PHP
$foo = array();
echo $foo;
will produce the literal string Array as output.
You need to convert your array into a string. Since you're dealing with a Javascript target, use JSON as the perfect means of doing so:
$foo = array('a', 'b', 'c', 'd', 'e');
echo json_encode($foo);
Then in your JS code:
$.get(...., function (data) {
alert(data[1]); // spits out 'b'
});
Just remember to tell jquery that you're expecting JSON output.
You need to wrap (serialize) the data in a way that can be transported to the client via HTTP and used to get the original data.
Usual container formats are XML and JSON. JSON is well suited for usage in JavaScript, so use the PHP function json_encode() and echo the result.
Youll want to use JSON!
Client-side:
jQuery.post(url, data, function( data ) {
//Data is already converted from JSON
}, "json");
Server-side:
return json_encode($stack);
Explanation
Hope this helps!
echo json_encode($stack); can help you
at jquery side use jQuery.parseJSON()
You need to convert the array to a JSON object like this : return json_encode($stack);
Just convert your array it to a JSON object and return it back to your JavaScript:
return json_encode($stack);
As others have said, you may wish to wrap the output using something like json:
echo json_encode($stack);
However, if you aren't looking for an output with the complexity of JSON formatting, you could just use implode() to output a comma separated list:
echo implode(',',$stack);
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); ?>;
I'm making a jQuery .post() with the following arrays:
'cleanedLinkStructureArray[]': cleanedLinkStructureArray,
'cleanedPermaLinkArray[]': cleanedPermaLinkArray
The data inside these arrays:
cleanedPermaLinkArray looks like this: ["2012","10","30","hello-world"]
and cleanedLinkStructureArray like this: ["year","monthnum","day","postname"]
Javascript code:
var ajaxPost = $.post(
enableAJAX.ajaxurl,
{ action: 'ajaxRequest',
'ajaxRequestNonce' : enableAJAX.ajaxRequestNonce,
'cleanedLinkStructureArray[]': cleanedLinkStructureArray,
'cleanedPermaLinkArray[]': cleanedPermaLinkArray },
'json'
);
ajaxPost.done(function(responseText) {
alert(responseText);
console.log(responseText);
});
ajaxPost.fail(function() {
alert("Oops, I'm afraid we've broken something");
});
I don't understand how I catch the two arrays in PHP? and use the data from the arrays inside PHP? Preferably I would create new PHP array with them, where the values inside cleanedLinkStructureArray become the keys for the array and the values inside cleanedPermaLinkArray the values for that new array.
I guess it must be something with this, but I need someone more experienced to tell me what I need to do here.
$_POST['cleanedPermaLinkArray[]']
$_POST['cleanedLinkStructureArray[]'];
Any help would be appreciated.
Kind regards,
Marnix
Your arrays will be in
$_POST['cleanedPermaLinkArray']
$_POST['cleanedLinkStructureArray'];
you can do a simple var_dump($_POST) to see how the data is formed
First, in $.post, you do not need the square brackets, so this is one of your params:
'cleanedLinkStructureArray': cleanedLinkStructureArray,
Then in PHP, you have to first catch it like such:
$cleanedLinkStructureArray = $_POST["cleanedLinkStructureArray"];
Now, you can use the following:
foreach ($cleanedLinkStructureArray as $item) {
// Do something with $item
}
Another way is to pass all your params from $.post to php is setting them as json object.
This is all coming down from the server as JSON, right? Just use json_decode on the values and the'll be converted to arrays, natively inside of php.
$cleanedPermaLinkArray = json_decode($_POST['cleanedPermaLinkArray[]']);
echo cleanedPermaLinkArray[0]; // some value..
I've got a PHP array and echo that into javascript with json encode, i need to do it this way because it's going to be very dynamic. This is the code it echo's:
{"notempty":true}
And i use this to, convert it to javascript:
var myarray = eval('(' + json + ')');
For some reason it creates an object instead of an array and for that reason i cant use .length or a for loop.
Does someone know what im doing wrong here?
Thanks
You're trying to treat an Object like an Array, and an Object is not an Array, it is an Object.
Any time you see {} in JSON, that means "What is contained within these hallowed brackets is a dynamic object". When you see [], that means "Behold! I am an Array" (there are notable exceptions to this one: jQuery does some special work with to make itself look like an array).
So, in order to iterate through an Object, you'll want to use for... in.
// eval BAD unless you know your input has been sanitized!.
var myObj = JSON.parse('{"notempty":true}');
// personally, I use it in for... in loops. It clarifies that this is a string
// you may want to use hasOwnProperty here as sometimes other "keys" are inserted
for( var it in myObj ) console.log( "myObj["+it+"] = " + myObj[it] );
{} is an object, which contains one attribute named notempty. If you want an array, it'd have to be
[{"notempty":true}]
which is an array with a single element at index 0, which is an object with the single attribute 'notempty';.
By default, if you use encode an assoc array in php, it will become a js object when you decode. In order to have it be an array, you need to make it an array in php:
PHP:
$arr = "['notempty','notempty2','notempty3']";
Otherwise, you should convert it to an array in JS, but that seems to me a waste since looping through the object in javascript is so much easier:
Javascript:
var arr = new Array();
for(var i in obj) arr[i] = obj[i];
You can use jQuery to parse it into an array like this:
var p = [];
$.each(jsonData, function (key, val) {
p.push([val.propertyOne, val.propertyTwo]);
});
I am presuming of course that you want to parse JSON, not an array or any other string.
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.