Database string value to PHP array to be used in Javascript - 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); ?>;

Related

having issue to display then data in angularjs via json array

I try to display data in angularjs via json data array but can't figure out or fix the issue when i return the json data from my php file it give me result
["{name:'abc', age:19}","{name:'xyz', age:21}"]
but its not working because in Angular i need data in format something like this
[{name:'abc', age:19},{name:'xyz', age:21}]
now issue is i can't figure out how can i rearrange this array format i tried JSON.parse() but its not working
its my php code
if($xml->product) {
foreach ($xml->product as $node ){
$productName = $node->name;
$productID = $node->productID;
$productPrice = $node->price;
$productURL = $node->imageURL;
$productCat = $node->categories->category;
//$product = "{name: '".$productName."', productid: '".$productID."' }";
$product = array("name"=> "".$productName."", "productid"=> "".$productID."");
array_push($data1, $product);
}} else {
echo "error!"; } print json_encode($data1);
problem fixed actually i am passing string in array and then encode with json it give me this double quote issue. now what i fix is change string in array and passed by json it automatically convert these array in object :)
its fixed by changing string into array
$product = "{name: '".$productName."', productid: '".$productID."' }";
replace with this
$product = array("name"=> "".$productName."", "productid"=> "".$productID."");

How do you split a string of pipe separated values and return an array?

I have an array like the following:
array(1) {
[0]=>
string(160) "|ad|al|at|ax|ba|be|bg|by|ch|cz|de|dk|ee|es|eu|fi|fo|fr|gb|gg|gi|gr|hr|hu|ie|im|is|it|je|li|lt|lu|lv|mc|md|me|mk|mt|nl|no|pl|pt|ro|rs|ru|se|si|sj|sk|sm|tr|ua|va|"
}
I'm trying to find a way to strip the pipes and turn them each into an array.
Here's the code that will output the results.
<?php
if( in_array( 'gb', get_field('rights_management_control_by_continent_europe') ) or 'gb' == get_field('rights_management_control_by_continent') ) {
?>
STUFF HERE
<?php } ?>
And just out of curiosity, is this doable in JavaScript?
Use the PHP explode tag.
<?php
$arr = ["|ad|al|at|ax|ba|be|bg|by|ch|cz|de|dk|ee|es|eu|fi|fo|fr|gb|gg|gi|gr|hr|hu|ie|im|is|it|je|li|lt|lu|lv|mc|md|me|mk|mt|nl|no|pl|pt|ro|rs|ru|se|si|sj|sk|sm|tr|ua|va|"];
$pieces = explode("|", $arr[0]);
Each item separated by the pipe symbol would be a new item in the away, with ad being [1] as you start with a pipe.
[ and ] can start and close an array
In Javascript you can split string to array by using
s = "a|b|c"
arr = s.split('|')
//access your array
arr[0]
arr[1]
.....
So you have this array, I'll just put it in a variable $old_array:
$old_array = array(0=>"|ad|al|at|ax|ba|be|bg|by|ch|cz|de|dk|ee|es|eu|fi|fo|fr|gb|gg|gi|gr|hr|hu|ie|im|is|it|je|li|lt|lu|lv|mc|md|me|mk|mt|nl|no|pl|pt|ro|rs|ru|se|si|sj|sk|sm|tr|ua|va|");
To split the string on index 0 we use the explode function on the first element in the $old_array array:
$exploded_array = explode("|", $old_array[0]);
The variable $exploded_array will now hold an array with all the pairs of letters as separate elements:
["","ad","al","at","ax","ba","be",...]
In JavaScript it would look a little different but still similar:
var old_array = ["|ad|al|at|ax|ba|be|bg|by|ch|cz|de|dk|ee|es|eu|fi|fo|fr|gb|gg|gi|gr|hr|hu|ie|im|is|it|je|li|lt|lu|lv|mc|md|me|mk|mt|nl|no|pl|pt|ro|rs|ru|se|si|sj|sk|sm|tr|ua|va|"];
var split_array = old_array[0].split('|');
The split_array variable will contain all the pairs of letters as separate elements:
["","ad","al","at","ax","ba","be",...]

Pass php array values as JavaScript array values

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"]

Send multiple base64 to php

I want to send multiple base64 strings via jquery's $post(). The number of strings are not always the same. How can I do this and fetch it in php?
Is it a good option to have all strings in an array and add them in $post()?
var items = [
"data:image/png;base64,i.....",
"data:image/png;base64,i....",
"data:image/png;base64,i...."
] //the number od these strings varies on each post
$.post("../send.php",
{
for(i=0;i<21;i++){
'item'+i: items[i]
}
},
)
php:
if($_POST['item1']){
$item1 = $_POST['item1'];
}
I would go with the following steps:
1) Create a form with the input fields that contain all these base64 strings. (the form and all its fields can all be hidden in html)
2) In my form all the input text fields can have the same name like in this case
<input type="text" name="text1[]">
2) When I need to add a new string, I shall add an input field in that form by using jQuery.append()
3) in my jquery post i will set the data to
$.post('../send.php',$('#myFormId').serialize(),function(){
// what i want to do with the response
})
4) in my php page I can easily loop over
foreach($_POST['item1'] as $item){
// do what you want with data
}
that's it!
Try this
JS :
$.post("../send.php",{items:items}); //send to server
PHP:
$_POST['items'] // catch in server
I would create a regular array of strings, and then iterate to the array of strings and add them as properties of an object using a for loop. Here's an example.
var items = []; // Empty array.
items.push(item1, item2, item3); // Add Base64 strings.
var postdata = {}; // An object for our postdata.
// Iterate through the array and add items as properties to the object.
for (var _i = 0, _j = items.length; _i < _j; _i++) {
postdata['item_'+_i] = items[_i]; }
// POST the object to the PHP file.
$.post("../send.php", postdata);
Then, in PHP, you get $_POST['item_1'] until $_POST['item_n'] from jQuery. :)
UPDATE
You can process the postdata in PHP like below.
<?php
foreach($_POST as $k => $v) {
// Do things for each item POSTED.
// This will end after the last POSTed item is reached.
// $k is the 'key', as in what's inside the square brackets of $_POST[]
// $v is the 'value', as in $_POST[key] = "THIS STUFF";
}
?>
Hope that was helpful!

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

Categories