Simple PHP array to Javascript array - javascript

I have an array in php lets call it:
$nums = array(10,25,52,32,35,23);
I want to send it to my javascript function like this:
var nums=[10,25,52,32,35,23];
How can i do this?
(My javascript file name is "nums.js")
Edit:
nums.js is a javascript code. It changes the values of table in the html. But the values only exist in php. So i have to send the values to javascript.

PHP >= 5.2
The json_encode function is for this purpose:
<?php echo 'var nums=' . json_encode(array(10,25,52,32,35,23)) . ';'; ?>
Docs: http://php.net/json_encode
PHP < 5.2
If you can't use json_encode, take a look at this post for a way to define an equivalent.

As long as your javascript file is being parsed by PHP before being sent to the client, then this should work:
<?php echo "var nums=[" . implode(',', $nums) . "];"; ?>

Just json_encode() the array and then output it as an array literal in javascript.
<?php
$nums = array(10,25,52,32,35,23);
$nums_json = json_encode($nums);
?>
<script type="text/javascript">
var nums = <?php echo $nums_json; ?>;
</script>

you can also use json_encode() but only possible from php 5.2
see more: http://us3.php.net/manual/fr/function.json-encode.php
or you can use this function:
function php2js ($var) {
    if (is_array($var)) {
        $res = "[";
        $array = array();
        foreach ($var as $a_var) {
            $array[] = php2js($a_var);
        }
        return "[" . join(",", $array) . "]";
    }
    elseif (is_bool($var)) {
        return $var ? "true" : "false";
    }
    elseif (is_int($var) || is_integer($var) || is_double($var) || is_float($var)) {
        return $var;
    }
    elseif (is_string($var)) {
        return "\"" . addslashes(stripslashes($var)) . "\"";
    }
    return FALSE;
}

Related

PHP modify fetched variable and return to frontend for JS

Im fetching Product Attributes from Woocommerce, and echo them out in a script tag as variable to use with javascript in frontend.
This might be a bad practice, feel free to enlighten me.
Example:
Product Attributes:
Total height: 43m
Total length: 55m
PHP queries "Total-height" as Attribute Name and "43m" as Attribute Value.
PHP replaces empty space with "-".
I can't define a javascript var with "-" in var name.
Example: var Total-height = "43m";
How could I fix this issue?
Here is my code.
Thanks in advance.
function product_attribute_dimensions(){
global $product;
foreach ($product->get_attributes() as $taxonomy => $attribute_obj ) {
// Get the attribute label
$attribute_label_name = wc_attribute_label($taxonomy);
$value = $product->get_attribute($taxonomy);
if ($value) {
$label = get_taxonomy($taxonomy)->labels->singular_name;
$profile_one = $value;
echo '<script>' . $attribute_label_name . ' = "' . $value . '";
</script>';
}
}
try using window["variable_name"]
do this:
echo '<script>window["' . $attrname . '"]=' . $attrval
then in your js:
let this_var = window[attrname]
It seems like the clearest shortest way to do this.
As I understand the generated string in the variable "$attribute_label_name" is the problem? Take a look at https://www.php.net/manual/de/function.str-replace.php
With this native PHP function you can search for a character (eg."-") and replace with something else (eg. "_")
echo '<script>' . str_replace("-", "_", $attribute_label_name) . ' = "' . $value . '";
But as you said, this might not be the best approach. I personally would add this kind of information into a "data-X" HTML attribute in some HTML element and would extract this in my JS. Similar to this:
<div id="some_element" class="could be hidden" data-total-height="<?= $value ?>"></div>
You could Query something like this with jQuery $("#some_element").attr("data-total-height")
function product_attribute_dimensions() {
global $product;
$product_atrributes = array();
foreach ($product->get_attributes() as $taxonomy => $attribute_obj) {
// Get the attribute label
$attribute_label_name = wc_attribute_label($taxonomy);
$attribute_label_name = str_replace(' ', '_', $attribute_label_name);
$value = $product->get_attribute($taxonomy);
if ($value) {
$product_atrributes[$attribute_label_name] = $value;
}
}
echo '<script type="text/javascript">var product_atrributes = ' . json_encode($product_atrributes) . ';</script>';
}
Now you can use in JS like product_atrributes.Total_height.value
This way the redundant script tag also can be avoided.

how to pass php array value to javascript without using JSON

I have a simple calculation from php database, which needs to be used in javascript, how to do it?
<script>
function check(){
var ramt=document.getElementByName('refundedamount[]');
var bal1=[];
<?php for each($balance1 as $val){
echo 'bal1.push('.$val.');';
} ?>
. . .
} </script>
<form onsubmit="return check()";
<?php
$balance1=array();
while($row=mysqli_fetch_assoc($result)){
$income=$row['totalincome'];
$exp=$row['totalexp'];
$balance=$income-$exp;
$balance1[]=$balance;
...... ?>
<input type="text" name="refundedamount[]"/>
</form>
How to use and read values of $balance1[] array into JAVASCRIPT. without using JSON. basically I want to cross check the value of php $balance1 array and input text array " refundedamount[]".
Without JSON, you can loop each value.
<?php
$balance1 = array( 1,2,3,4,5 );
?>
<script>
var balance1 = [];
<?php
foreach( $balance1 as $val ) {
echo 'balance1.push( ' . $val . ' );';
}
?>
console.log( balance1 );
</script>
Will result to
Array [ 1, 2, 3, 4, 5 ]
PHP side:
$arrayJSON = json_encode($balance1) to convert to JSON format.
JS side:
var array = JSON.parse("<?php echo $arrayJSON;?>");
Hope this help!
You can convert the php array into a javascript object then convert that object into an array, eg if it has numeric indices:
<script>
var obj = <?php echo json_encode($phpArray) ?>;
var arr = Object.keys(obj).map(function(k) { return obj[k] });
// Or if you're using ES6
var arr = Object.values(obj);
</script>

How do I grab JSON output with PHP

Ok, this is my first try with TwitchAPI. When I make the request, I get:
{"follows":[{"created_at":"2015-04-28T01:04:33Z","_links":{"self":"https://api.twitch.tv/kraken/users/chaoticaura/follows/channels/giygaslp"},"notifications":true,"user":{"_id":54441701,"name":"chaoticaura","created_at":"2014-01-05T01:06:19Z","updated_at":"2015-04-28T14:18:50Z","_links":{"self":"https://api.twitch.tv/kraken/users/chaoticaura"},"display_name":"ChaoticAura","logo":"http://static-cdn.jtvnw.net/jtv_user_pictures/chaoticaura-profile_image-3b6a888d174153f6-300x300.jpeg","bio":"Welcome to the House of Gaming/Crazy/Stupid ChaoticAura","type":"user"}},{"created_at":"2014-08-10T06:25:10Z","_links":{"self":"https://api.twitch.tv/kraken/users/phoenix089/follows/channels/giygaslp"},"notifications":true,"user":{"_id":31004257,"name":"phoenix089","created_at":"2012-06-03T01:41:37Z","updated_at":"2015-04-22T19:58:28Z","_links":{"self":"https://api.twitch.tv/kraken/users/phoenix089"},"display_name":"phoenix089","logo":null,"bio":null,"type":"user"}},{"created_at":"2014-05-10T17:41:05Z","_links":{"self":"https://api.twitch.tv/kraken/users/monanniverse/follows/channels/giygaslp"},"notifications":true,"user":{"_id":30041264,"name":"monanniverse","created_at":"2012-04-25T10:45:21Z","updated_at":"2015-04-17T18:58:05Z","_links":{"self":"https://api.twitch.tv/kraken/users/monanniverse"},"display_name":"Monanniverse","logo":null,"bio":null,"type":"user"}},{"created_at":"2013-04-25T01:10:57Z","_links":{"self":"https://api.twitch.tv/kraken/users/princess_sarahkat/follows/channels/giygaslp"},"notifications":true,"user":{"_id":27411850,"name":"princess_sarahkat","created_at":"2012-01-13T23:45:04Z","updated_at":"2014-08-01T17:49:47Z","_links":{"self":"https://api.twitch.tv/kraken/users/princess_sarahkat"},"display_name":"Princess_SarahKat","logo":"http://static-cdn.jtvnw.net/jtv_user_pictures/princess_sarahkat-profile_image-5b554c88c6eb89a9-300x300.png","bio":null,"type":"user"}},{"created_at":"2012-12-04T13:43:15Z","_links":{"self":"https://api.twitch.tv/kraken/users/thedaredevil717/follows/channels/giygaslp"},"notifications":true,"user":{"_id":38212339,"name":"thedaredevil717","created_at":"2012-12-04T13:41:17Z","updated_at":"2013-09-27T12:38:53Z","_links":{"self":"https://api.twitch.tv/kraken/users/thedaredevil717"},"display_name":"Thedaredevil717","logo":null,"bio":null,"type":"user"}}],"_total":5,"_links":{"self":"https://api.twitch.tv/kraken/channels/giygaslp/follows?direction=DESC&limit=25&offset=0","next":"https://api.twitch.tv/kraken/channels/giygaslp/follows?direction=DESC&limit=25&offset=25"}}
I'm told that this is a JSON Response. How do I take this information, and use it with variables in PHP?
I've made some attempts that failed, here is the code:
<html>
<?php $json=json_decode(file_get_contents( "https://api.twitch.tv/kraken/channels/giygaslp/follows?limit=1")); $currentFollower=0 ; $currentPage=0 ; $resultsPerPage=5 ; $tableHtml=<
<<TABLE <div id="page-number-%s" style="%s">
<table>
<tr>
<th>Username:</th>
<th>Follow Date:</th>
<th>Type:</th>
</tr>
%s
</table>
</div>
TABLE; $rowHtml =
<<<ROW <tr>
<td>%s
</td>
<td>%s</td>
<td>%s</td>
</tr>
ROW; $html = ""; $rows = ""; foreach ($json->follows as $follow) { if ($currentFollower % $resultsPerPage == 0 && $currentFollower> 0) { $style = $currentPage === 0 ? '' : 'display:none'; $html .= sprintf($tableHtml, $currentPage, $style, $rows); $rows
= ""; $currentPage++; } $rows .= sprintf( $rowHtml, $follow->user->_links->self, $follow->user->name . ' (' . $currentFollower . ')', $follow->user->created_at, $follow->user->type ); $currentFollower++; } $html .=
<<<BUTTONS <button onclick="previousPage()">previous</button>
<button onclick="nextPage()">next</button>
BUTTONS; $javascript =
<<<JS <script>
var currentPage = 0; function previousPage() { if(currentPage > 0) { document.getElementById('page-number-'+currentPage).style.display = 'none'; currentPage--; document.getElementById('page-number-'+currentPage).style.display = ''; } }; function nextPage()
{ if(currentPage
< {$currentPage} - 1) { document.getElementById( 'page-number-'+currentPage).style.display='none' ; currentPage++; document.getElementById( 'page-number-'+currentPage).style.display='' ; } }; </script>
JS; echo $javascript.$html; ?>
</html>
That doesn't work though... any ideas?
Edit:
Im using this at the moment for testing
<html>
<script>
<? php
$json = json_decode(file_get_contents("https://api.twitch.tv/kraken/channels/giygaslp/follows?limit=25"), true);
print $json['follows'];
var_dump($json['follows']) ?>
</script>
</html>
PHP's json_decode is a bit confusing. It returns an stdClass. Add the true option to get a regular PHP associative array.
$json = json_decode(file_get_contents( "http://myurl.com"), true);
var_dump($json['follows']); //var_dump is print for arrays
I've found that sometimes when using stdClasses, you have to use the key as a string:
$json->{'follows'}
Test your code at PhpFiddle
Look at this example Parsing JSON object in PHP using json_decode
and here is a way to parse it.
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
You can convert that JSON data to an array which you can easily use with PHP. To do this use PHP's json_decode() function.
$decodedJSON = json_decode($JSON, true);
It's important you pass in true as the second parameter otherwise you will not get an array back.
Now that you have an array you can access elements from that JSON data in that array. For example:
$decodedJSON[key]
In the above example, key can be any key that was in the JSON data we converted and it will return whatever value belongs to that key.

Array of Javascript in PHP

I was trying to get datas from the database and put them into the array in Javascript but Javascript is not working in PHP command area.
Here is the whole PHP codes;
<?php
mysql_connect("mysql.metropolia.fi","localhost","") or die("ERROR!!");
mysql_select_db("localhost") or die("COULDN'T FIND IT!!") or die("COULDN'T FIND DB");
$sql = mysql_query("SELECT * FROM METEKSAN_HABER_CUBUGU");
$haber = 'haber';
$list = array();
$i=0;
while($rows = mysql_fetch_assoc($sql)){
$list[] = $rows[$haber];
$i++;
}
echo $i;
echo '<script type="text/javascript">
var yazi=new Array();';
echo $i;
for ($k = 0 ; $k < $i ; $k++){
echo 'yazi['.$k.']="'.$list[$k].'';
}
echo '</script>';
?>
But when it comes to;
echo '<script type="text/javascript">
var yazi=new Array();';
this command line, the problem begins. Though I write 'echo $i;' after that command, I get nothing on the screen but I get the result if I write before that command. So, it means that everything works well before that command. What you think about the problem ? Why can't I starting the Javascript command ? Am I writing something wrong ?
Please give me a hand.
Thanks.
UPDATE;
I opened the web source and yeah it exactly seems there is a problem. So, I think it's better to ask that how can I write
<script type="text/javascript">
/*Example message arrays for the two demo scrollers*/
var yazi=new Array()
yazi[0]='METEKSAN Savunma, Yeni Dönemin Örnek Oyuncusu Olmaya Hazır'
yazi[1]='METEKSAN Savunma Bloomberg TVde'
</script>
this Javascript code in PHP ??
You can see my output at http://users.metropolia.fi/~buraku/Meteksan/index.php
try something like this
while($rows = mysql_fetch_assoc($sql)){
$list[] = ''.$rows[$haber].'';
}
$js_array = json_encode($list);
echo "<script>var yazi = ". $js_array . ";</script>";
It seems you are executing it currently in your browser? Then you should find your second output when opening page source, because your browser tries to executes the output as JS code. If you execute it on cli, everything should work as expected.
EDIT based on your comment:
Bullshit i wrote before, obviously. Viewing line 122 of your current html shows me a problem with your quotation marks. try the following:
for ($k = 0 ; $k < $i ; $k++){
echo 'yazi['.$k.']=\''.$list[$k].'\';';
}
In the end you should try to avoid using this kind of js rendering at all. The json_encode proposal of jeremy is the correct way to go.
You may have much more compact code:
....
$list = array()
while($rows = mysql_fetch_assoc($sql)) {
$list[] = $rows[$haber];
}
echo '<script type="text/javascript">' . "\n";
echo 'var yazi=';
echo json_encode($list,JSON_HEX_APOS | JSON_HEX_QUOT);
echo ";\n";
echo '</script>' . "\n";
What is this doing:
There's no need to count the added elements in $i, count($array) will give you the cutrrent number.. But it's not needed anyway.
Put some newlines behind the echo, better readable source
json_encode will format an JSON array from your php array, which can be directly used as source code.

HTML Escaping/Encoding in Javascript/PHP

I have multiple pages of html code saved into a database. I want a file to be able to flip through each of these pages without reloading.
I created a PHP file to pull all the pages into a database.
The page shows the first page and navigation buttons.
There is also javascript to put all the other pages into an array so I can quickly switch pages.
var pages = new Array();
<?php foreach ($coursePages as $page): ?>
pages[pageCount] = "<?php echo ($page['body']) ?>";
pageCount++;
<?php endforeach ?>
My problem is creating the javascript array. How can I escape the data from the echo properly so it can eventually change the page content using the following:
$(document).ready(function() {
$('.navNext, .navPrevious').click(function({
if ($(this).hasClass('navNext')) {
page++;
if (page > pageCount) {
page = 0;
}
} else {
page--;
if (page < 0) {
page = 0;
}
}
$('.page').html(pages[page]);
}))
});
Anytime you send values dynamically from PHP to JavaScript, you can simply use json_encode(). It will always produce valid JavaScript and handle all data types. Example:
<script>
var a = <?php echo json_encode($var)?>;
</script>
you can use this function to escape js values:
function js_escape_string($str)
{
$str = str_replace("\\", "\\\\", strval($str));
$str = str_replace("'", "\\'", $str);
$str = str_replace("\r", "\\r", $str);
$str = str_replace("\n", "\\n", $str);
$str = str_replace("\t", "\\t", $str);
$str = str_replace("</script>", "</'+'script>", $str);
return $str;
}
NOTE: use single quote ' around JS values, like:
<script>
var a = '<?php echo js_escape_string(....); ?>';
</script>

Categories