Pass php array values as JavaScript array values - javascript

I have a PHP array like this.
Array
(
[0] => hal([[br,1],[cl,4]])
[1] => alk([[nc(1),1,2],[nc(1),3]])
)
How to pass to JavaScript like below.
var hal=[["br",1],[cl,4]];
var alk=[[nc(1),1,2],[nc(1),3]];
I write some code
<script>
var data = <?=json_encode($input);?>; //$input is name of the php array
var hal=[data[0].substring(5,data[0].lastIndexOf(']'))];
var alk=[data[1].substring(5,data[1].lastIndexOf(']'))];
document.write(hal[0]);
</script>
The output is [br,1],[cl,1] and my expected output is like the one below.Any ideas? Thank you.
document.write(hal[0]); => ["br",1]
document.write(hal[0][0]); => ["br"]

If you want multiple variables, you'll want to loop through the array; you can grab the names using a regular expression. If you're trying to turn this into valid data you can parse, like a JSON string, you're going to have to do an awful lot of work; likely wherever you're getting this string from would be a better place to look to. Have them pass you a valid JSON string instead.
<script>
<?php foreach($input as $v) {
preg_match("/(\w+)\((.*)\)/", $v, $matches);
$var = $matches[1];
$val = str_replace("'", "\\'", $matches[2]);
echo "var $var = '$val';\n";
} ?>
</script>

There's a package called Transform PHP Vars to JavaScript by Jeffrey Way that you can use to transfer your variable easily to your Javascript.
First, create an implementation of the Laracasts\Utilities\JavaScript\ViewBinder interface. This class is in charge of inserting the given JavaScript into your view/page.
<?php
class MyAppViewBinder implements Laracasts\Utilities\JavaScript\ViewBinder {
// $js will contain your JS-formatted variable initializations
public function bind($js)
{
// Do what you need to do to add this JavaScript to
// the appropriate place in your app.
}
}
Next, put it all together:
$binder = new MyAppViewBinder;
$javascript = new PHPToJavaScriptTransformer($binder, 'window'); // change window to your desired namespace
$javascript->put(['foo' => 'bar']);
Now, you can access window.foo from your JavaScript.

I found an answer for my problem.Here i pass value from php as string.Then that string convert it to an object.
<?php
$input="hal([[br,1],[cl,4]])";
preg_match('#^([^[]+)?([^)]+)#i',$input, $hal); //get string as '[[br,1],[cl,4]]'
?>
<script>
var hal1 = <?=json_encode($hal[2]);?>; //'[[br,1,2],[cl,1,2]]' pass to javaScript
function toJSObject(str){
str = str.replace(/([a-zA-Z]+)/g, '"$1"');
return (JSON.parse(str))
}
var hal = toJSObject(hal1); // pass to JS object [['br',1,2],['cl',1,2]]
document.write(hal);
</script>
And also get this as right.
document.write(hal[0]); => ["br",1]
document.write(hal[0][0]); => ["br"]

Related

object_to_array and encode - php to js opbject

I send Ajax call to AjaxHandler.php page, the AjaxHandler page call other function in Functions.php (other page).
On success i need to return object from AjaxHandler.php, the object need to have 2 params.
Here is the ajax call:
var month_number = document.getElementById("Month").innerHTML;
var year_number = document.getElementById("Year").innerHTML;
$.get("AjaxHandler.php", { "year": year_number, "month": month_number }, function (encodedata) {
var data = JSON.parse(encodedata);
$("#LinesPlace").html(data);
});
Here is the AjaxHandler.php code the need to handle that:
if(isset($_GET['year'],$_GET['month']))
{
$year = $_GET['year'];
$month = $_GET['month'];
$a = getExpenses($year, $month);
echo $a->pharama;
echo $a->pharamb;
$b = object_to_array($a);
echo $b;
return json_encode($b);
}
Now when i put that url:
http://xxxxxxxxx.com/AjaxHandler.php?year=2015&month=09
Its show me the echo of pharama and pharamb but when i try to convert the object to array and then decode it its just not working, i tryed alot but nothing.
Here is the object_to_array function:
//convert php object to array
function object_to_array($data){
if(is_array($data) || is_object($data))
{
$result = array();
foreach($data as $key => $value) {
$result[$key] = $this->object_to_array($value);
}
return $result;
}
return $data;
}
*I taked that function from this site from other question..
Please advice =]
Regards,
Rafael.
If you need to decode the JSON as an array or object, json_decode has a parameter specifically for that: http://php.net/json_decode
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
...
assoc
When TRUE, returned objects will be converted into associative arrays.
For example:
$json_as_object = json_decode($json, false);
$json_as_array = json_decode($json, true);
Attempting to manually convert an object into an array should be unnecessary.
You need to encode it very specifically with JSON_UNESCAPED_UNICODE like this:
$jsonObj = json_encode ( string $json, JSON_UNESCAPED_UNICODE);
I have this code in a standard function for this sort of thing
http://php.net/manual/en/function.json-last-error.php
PS. I think you are over checking it in your object to array function. I would probably choose something like: if(is_array($param)){ .. }
Rafael I cant comment need 50 rep or something:D You say: What you mean unnecessary? you mean i can return the object php as is?
Half of what if am saying: you know the things you put into the function obj_to_array() rigth? That what goes in and it ain't an object so why check it? Who will send it? Do you foresee a $_POST incomming all wrapped up as a nice object and ready to go? Like normally the form does a $_POST / $_GET and provides arrays by default as far as I know? And if you produce an obj elsewhere in your code why put use it as input for this function? Don't you know what you are doing somewhere else in your code? Sure you do and as long as you are concise and precise it will never suddenly be a object returned form $_POST or any function normally outputting arrays or integers etc. Check your output as you created it in the first place? Check your web inputs very well (1 time! and for js injections), then only check your types for validating ambiguous output / inputs of your own like an output that can produce an array or a true / false return value. Checking this output for a value of 1 for a TRUE value of the boolean can result in disappointment because:
if the value of $a is 1 in if($a) do something; then a 1 can be the TRUE value returned as the result of the function that produced the thing that we are checking or the result of count($a). If we then assume the array is length 1 because of a misinterpretation of the value of $a then this can give unintended results? You want to be sure that it is the array in $_array($a) that's doing the talking and not the array for example? Thats all to it I think? Or am I rambling (again)?

Retrieve data from PHP file using $.getJSON

I'm trying to set up a comments system on photos.
I understand how to use $.getJSON when the array is like this:
get.php:
$var = 5;
echo json_encode(array('var'=>$var));
main.php:
$.getJSON("get.php",function(data){
number = data.var; // number = 5
});
But I have a more complex thing.
My comments table has these 4 columns: id | photo_id | comment | date
For example let's say we're trying to retrieve the comment data from the photo with
photo_id == 1.
We don't know how many comments there might be.
In getcomments.php:
$photoid = 1;
$comment = mysqli_query($conn,"SELECT * FROM comments WHERE photo_id='$photoid'");
while($commentrow = $comment->fetch_assoc()) {
$comments[] = $commentrow;
}
Then you encode it:
echo json_encode($comments);
Which prints something like this (the photo has 2 comments):
[{"id":"1","photo_id":"1","comment":"text","date":"23858556"},{"id":"2","photo_id":"1","comment":"text","date":"23858561"}]
How do I declare variables for the comments array?
$.getJSON("getcomments.php",function(data){
// how do I declare variables for the comments array, especially since you don't know how many there might be?
});
Additionally, I have two json arrays that need to be echoed within the same PHP file. i.e. echo json_encode(array('img1'=>$img1link)) and echo json_encode($comments); need to be echoed within the same PHP file, but it made the code stop working altogether.
If you want to display the comments you need to loop over the array. You can use for loop or forEach function.
$.getJSON("getcomments.php",function(data){
data.forEach(function(comment) {
$('div').append('<span>' + comment.comment + '</span>');
});
});
To display two JSONs you need to combine them into one JSON object.
echo json_encode(array('img' => $img1link, 'comments' => $comments));
[{"id":"1","photo_id":"1","comment":"text","date":"23858556"},{"id":"2","photo_id":"1","comment":"text","date":"23858561"}]
Using this JSON, data is an array and you should manage it as an array. You can loop through it using simple loops (for, while...) or using new functional methods like forEach, map, filter....
Please try with this example:
$.getJSON("getcomments.php",function(data){
data.forEach(function(item, index, all) {
console.log(item.comment);
});
});
Declare an object, and push it to the array.
var commentsArr = [];
for (var i = 0; i < data.length; i++) {
var objToPush = {
id: data.id,
comment: data.comment,
date: data.date
}
commentsArr.push(objToPush);
}

php array to javascript format?

I have an array.
Array
(
[0] => Array
(
[title] => Badminton Men's Singles Gold Medal Kashyap Parupalli
[mp4] => http://www.tensports.com/media/video/kashyap.mp4
[webm] => http://www.tensports.com/media/video/kashyap_VP8.webm
[playThumb] => {filedir_2}Kashyap_medal.jpg
[videoPoster] =>{filedir_3}Kashyap_medal.jpg
)
[1] => Array
(
[title] => Boxing Men's Welter (69kg) Silver medal: Mandeep Jangra
[mp4] => http://www.tensports.com/media/video/MandeepJangraMedal.mp4
[webm] => http://www.tensports.com/media/video/MandeepJangraMedal_VP8.webm
[playThumb] => {filedir_2}Mandeep_Jangra_medal.jpg
[videoPoster] =>{filedir_3}Mandeep_Jangra_medal.jpg
)
)
I am trying to convert it in a object like below.
Javascript Format required :
videos = [
{
src : [
'http://www.tensports.com/media/video/kashyap_VP8.webm',
'http://www.tensports.com/media/video/kashyap.mp4'
],
poster : '{filedir_2}Kashyap_medal.jpg',
title : "Badminton Men's Singles Gold Medal Kashyap Parupalli"
},
{
src : [
'http://www.tensports.com/media/video/MandeepJangraMedal.mp4',
'http://www.tensports.com/media/video/MandeepJangraMedal_VP8.webm'
],
poster : '{filedir_2}Mandeep_Jangra_medal.jpg',
title : "Boxing Men's Welter (69kg) Silver medal: Mandeep Jangra"
}
];
what I have done :
var videoObject = $.parseJSON(<?php echo $js_VideoURL ?>);//where $js_VideoURL = json_encode($above-array);
$.each(videoObject, function(key, value) {
console.log('stuff : ' + key + ", " + value);
});
It's giving me error.I am uncertaing about getting the data in required format.Any help?
The format you're expecting in javascript is not compatible with the php array you've given.
Going from there I am assuming that is the problem, since you didn't give the exact error message you're encountering. From what I can gather you're missing a piece of PHP to put the video's in the correct format. To solve that you can do the following:
Note the comments in the code, they should explain what is going on.
PHP:
// $videos is assumed to be the array you've given in your question
$arr = [];
foreach ($videos as $video) {
// Create video object
$obj = new stdClass;
$obj->src = [
$video['webm'],
$video['mp4']
];
$obj->poster = $video['playThumb'];
$obj->title = $video['title'];
$arr[] = $obj;
}
// $arr is now the output you would need for processing
Javascript:
var videoObject = <?php echo $js_VideoURL ?>; //where $js_VideoURL = json_encode($arr);
$.each(videoObject, function(key, value) {
console.log('stuff : ' + key + ", " + value);
});
Edit:
Your first mistake is as Quentin mentioned that you're putting the json directly into javascript, which means it will be interpreted as a native javascript object. I missed that in my original answer.
It means you indeed do not need to use $.parseJSON to get the object you want. I changed my answer to reflect that.
Note:
Your code implies that you have Javascript snippets in your php / html templates. This is considered bad practice, and can be resolved with relative ease.
What you could do is put the json in a data attribute of the relevant html element on the page (escape the json before printing) then picking up the json string using jQuery on initialization with
var object = $element.data('json');
Using this (jQuery will automatically try parse the string as json) it will be ready for use.
The JSON format is a subset of JavaScript literal syntax
json_encode outputs JSON (which, if just dumped in JS, will be treated as a literal)
parseJSON takes a string of JSON and converts it to a data structure
Therefore: Don't use parseJSON as it will force the object you have into a string ("[Object object]") and then try to parse that as JSON.
Just:
var videoObject = <?php echo $js_VideoURL ?>;
Come on.. did you even check PHP docs, or even google json encode!?!?!
var videoObject = <?php echo json_encode($js_VideoURL); ?>;

Retrieving and using a json associative array

I use jquery and ajax to retrieve a dynamically made array made in php, like so:
$json = array();
while ($row = $stmt->fetch_assoc()) {
$json['item_'.$row['id']] = $row['name'];
}
header('Content-type: application/json; charset=utf-8');
echo json_encode($json);
exit;
If I test the php file in browser, it outputs:
{"item_3":"Simon","item_1":"Miriam","item_2":"Shareen"}
So far so good. But how do I use that array in jquery?
I have this jquery ajax:
$.getJSON( "json.php", function(data) {
console.log(data);
});
And testing that page in browser, it put this in console:
Object {item_3: "Simon", item_1: "Miriam", item_2: "Shareen"}
And that's ok right? Or should item_x also be in quotes?
Now, how do I USE that array in jquery?
If I try console.log(data[0]) it puts undefined
As i mentioned in comments, php associative arrays become javascript objects, which cant be accessed numericaly.
A solution would be to send an array of objects instead:
while ($row = $stmt->fetch_assoc()) {
$json[]= ['key'=>'item_'.$row['id'] , 'value' => $row['name']];
}
the in js:
data[0].key;
data[0].value;
EDIT obviously key is a misleading name in this example, better to call it something else:
$json[]= ['id'=>'item_'.$row['id'] , 'value' => $row['name']];
//js
data[0].id;
Try to use $.each() to iterate through that object,
$.each(data,function(key,val){
console.log(key,val);
});
DEMO
If you want to access it without iterating it then simply use bracket notation
data['item_3'] //Simon
Or directly access it like,
data.item_3 //Simon
Then convert it like an array as per your wish like this,
var obj = {"item_3":"Simon","item_1":"Miriam","item_2":"Shareen"};
var convertedArray = $.map(obj,function(val,key){
var obj = {}; obj[val] = key;
return obj;
});
DEMO

Database string value to PHP array to be used in Javascript

I need to store values into a Wordpress database and the use the value in a Google Chart.
The questions are:
1. What format do I use to store it into the database?
Currently I am using WP-TYPES and adding the array as follows to a Multi Line Box:
['Month','Value 1','Value 2'],['2004',1000,400],['2005',1170,460],['2006',660,1120],['2007',1030,540]
This is what it needs to output in the Javascript for the chart.
Convert the String to a array in PHP (Not doing it correctly)
I retrieve the data with:
$graphdata = types_render_field("graph-data", array("output" => "raw","separator"=>";"));
This gives me a string value.
Then I add it to an array:
$thechartcontent[$i] = [
"name" => get_the_title(),
"chartheaders" => array($graphdata),
];
In JavaScipt:
I set the PHP Array to Java
var chart1 = <?php echo json_encode($thechartcontent[0]); ?>;
Then I get the data from the array to a var:
var chartheaders1 = chart1['chartheaders'];
This is where I get stuck. The value that I get is a string. It needs to show exactly this:
['Month','Value 1','Value 2'],['2004',1000,400],['2005',1170,460],['2006',660,1120],['2007',1030,540]
for it to work.
Any help please.
Well, it will not be exacly like you want since it's JSON encoded in JSON format. This might be useful. Or you can convert object into array in JS.
I suspect that what you are outputting is an array containing a string, which is not what you want. You must split $graphdata into an array of arrays containing your data before adding it to $thechartcontent:
$graphdata = substr($graphdata, 1, strlen($graphdata) - 1); // trim the opening and closing brackets
$graphdata = explode('],[', $graphdata); // split $graphdata into an array of strings
foreach($graphdata as &$row) {
$row = explode(',', $row); // split the row into an array
}
$thechartcontent[$i] = array(
'name' => get_the_title(),
'chartheaders' => $graphdata
);
When you json encode the data, you should use the JSON_NUMERIC_CHECK constant, so your numbers don't get quoted as strings:
var chart1 = <?php echo json_encode($thechartcontent[0], JSON_NUMERIC_CHECK); ?>;

Categories