Fill a javascript array with php variable - javascript

I want to fill a javascript array with my php variable $jaar. But when I print it in the js file I don't get the right output.
php file
<?php
$jaar = "[";
$result = mysql_query("SELECT jaar FROM agenda");
while( $row=mysql_fetch_array($result, MYSQL_NUM) ) {
$jaar .= "\"" . $row[0] . "\"";
$jaar .= ",";
}
$jaar{ strlen($jaar)-1 } = ']';
echo "<script type='text/javascript'>var db_jaar = '" . $jaar ."'</script>";
?>
<script src="js/calender.js"></script>
js file
//Get the variable from the php file
alert(db_jaar);
//printed: ["2018","2018"]
//When I make the variable local
var db_jaar = ["2018","2018"];
alert(db_jaar);
//printed: 2018,2018 <-- This is what I want

Some changes required:
while( $row=mysql_fetch_array($result, MYSQL_NUM) ) {
// create $jaar[]
$jaar[] = $row[0];
}
// echo using json_encode
?><script type='text/javascript'>var db_jaar = <?php echo json_encode($jaar); ?>;</script>";<?php
Read more:
json_encode()

Related

How put PHP and HTML code iike text inside javascript var. (innerHTML)?

I would like put my code to javascript var like that :
function myFunction(){
var switch = document..(etc..)....style.backgroundcolour;
var somethink2 = 'red'; <----- I tell about it
switch = somethink2;
}
and after that my background colour will be switch after using function.
I can"t do that with PHP code (my code connection with sql database) becouse i have not got a " and '.
"dane" (in getElementByID()) in my code below is and i want put this PHP code inside this div.
Guys please help me :)
Regards!
function swap(){
var zawartosc =
<?php $a4="SELECT silnik FROM marki WHERE model = 'A4'";
$result2 = mysqli_query($connection,$a4);
echo "<br>";
echo "<table border='1'>"; // I WANT PUT THIS LIKE A TEXT
while ($row = mysqli_fetch_assoc($result2)) {
echo "<tr>";
foreach ($row as $field => $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
?>
document.getElementById("dane").innerHTML = zawartosc;
}
Something like this:
$a4="SELECT silnik FROM marki WHERE model = 'A4'";
$result2 = mysqli_query($connection,$a4);
$html = [];
$html[] = "<br>";
$html[] = "<table border='1'>"; // I WANT PUT THIS LIKE A TEXT
while ($row = mysqli_fetch_assoc($result2)) {
$html[] = "<tr>";
foreach ($row as $field => $value) {
$html[] = "<td>" . $value . "</td>";
}
$html[] = "</tr>";
}
$html[] = "</table>";
$html = json_encode($html); //'["<br>","<table border='1'>", ...]'
?>
document.getElementById("dane").innerHTML = <?php echo $html;?>.join("\n"); //no quotes needed
//document.getElementById("dane").innerHTML = ["<br>","<table border='1'>", ...].join("\n");
Or you can just handle it like a normal string, but it's not what I would prefer to do.
$html = implode($html);
?>
document.getElementById("dane").innerHTML = "<?php echo $html;?>"; //careful with quotes here
In other words, don't output from PHP directly, instead build an array. It's much cleaner as you can consolidate that into a single variable and then use it.
For example:
//timeout for demonstration purposes
setTimeout(function(){
document.getElementById("dane").innerHTML = [
"<br>",
"<table border='1'>",
"<tr>",
"<td>foo</td>",
"<td>bar</td>",
"</tr>",
"<tr>",
"<td>biz</td>",
"<td>baz</td>",
"</tr>",
"</table>"
].join("\n");
},500);
table{width:100px;}
<div id="dane"></div>
I like using join (it's like implode) for multi line strings in JS (even in my plugins). In this case it works well with json_encode.
Basically we convert that array of HTML into a JSON string, which becomes a real Array in JS, then we let JS do the imploding with join. Mainly because arrays don't require the use of a quote, so this avoids any issues if we have quotes in our html.
Consider this (using just strings):
<?php
//HEREDOC
$html = <<<HTML
<table border='1' style="color:red;" >
HTML;
?>
document.getElementById("dane").innerHTML = '<?php echo $html;?>';
document.getElementById("dane").innerHTML = "<?php echo $html;?>";
Which becomes this:
document.getElementById("dane").innerHTML = '<table border='1' style="color:red;">'; //syntax error
document.getElementById("dane").innerHTML = "<table border='1' style="color:red;">"; //syntax error
From what I see you can get away with " at the moment, but if you put them in your HTML, you'll probably be in trouble (if your just using strings). Using join avoids this
document.getElementById("dane").innerHTML = ["<table border='1' style=\"color:red;\">"].join("\n"); //json_encode knows how to escape " for json.
Hope it helps!

How to dynamically poputate title and meta tags with php and/or javascript

I'm trying to replace my title tag and meta description dynamically using parameters from a search query in PHP. They keep showing up blank, but if I echo the $title or $desc inside the original PHP (first set) of tags, it appears fine. There is no header.php file for reference.
<?php
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
list($chuck, $keep) = explode('?', $url);
$patterns = array();
$patterns[0] = 'foo';
$patterns[1] = 'bar';
$patterns[2] = '123';
$replacements = array();
$replacements[0] = 'good ';
$replacements[1] = 'bad ';
$replacements[2] = 'ugly ';
$mytitle = "my cool " . $keep . " title tag";
$mydesc = "my cool " . $keep . " meta " . $keep . " description";
$title = str_replace($patterns, $replacements, $mytitle);
$desc = str_replace($patterns, $replacements, $mydesc);
//echo $title . "</br>";
//echo $desc . "</br>";
?>
<title><?if (strpos($url, 'foo=') !== false) { echo $title . "</br>"; } else { some other title"; }?></title>
<meta name="description" content="<?php echo $desc; ?>">
Alternatively, would a javascript/php mashup like this work?
<script>
document.title = <?if (strpos($url, 'foo=') !== false) { echo $title . "</br>"; } else { some other title"; }?>;
</script>
You need to amend your title alteration code's else slightly to include echo "
<title><?if (strpos($url, 'foo=') !== false) { echo $title . "</br>"; } else { echo "some other title"; }?></title>
Other than throwing a parse error as is this seems to work fine for me.

PHP Javascript Array

Hi I'm a novice PHP developer to say the least and I'm pretty stuck.
I'm trying to get the below code working I know I need a foreach loop or similar but I'm way out of my depth, I'm really not sure how to get this working, I know to most of you this is basic stuff but I'm lost.
Basically this is a receipt when a tab is settled. It searches the MySql Database for the relevant items and should print them on the receipt.
I know the MySql Query is not linked to the output at the bottom but I don't know how to do it.
<html lang="en">
<head>
<title>Receipt</title>
</head>
<body>
<?php
$invoicenum = $_POST['invoicenum'];
$name = $_POST['name'];
$netrev=$invoicenum - 1;
?>
Items:
<?
$itemQuery = mysql_query("SELECT * FROM sales WHERE invoicenum = '$netrev' AND tabname = '$name'");
$result = array();
while($row = mysql_fetch_array($itemQuery))
{
$result[] = $row['itemname'];
}
echo json_encode($result);
$amounts = json_decode($result['amounts']);
$items = json_decode($result['items']);
$prices = json_decode($result['prices']);
?>
<br>
<?
for ($i = 0; $i < count($items); $i++)
{
echo $amounts[$i] . "x " . $items[$i] . " - " . $prices[$i] . "<br>";
}
?>
</body>
</html>
I've removed code that isn't relevant to this array, if you can help I'd be forever grateful.
no need of encode and decode.
$itemQuery = mysql_query("SELECT * FROM sales WHERE invoicenum = '$netrev' AND tabname = '$name'");
while($row = mysql_fetch_array($itemQuery))
{
echo $row['amounts'] . "x " . $row['items'] . " - " . $row['prices'] . "<br>";
}
?>
Forget all json_decode/encode after filling $result then:
First do:
$result[] = $row;
Then:
foreach ($result as $set){
echo $set['amount'] . "x " . $set['itemname'] . " - " . $set['price'] . "<br>";
#do var_dump($set); here for checking the keys
}

Javascript array for all the files in a directory

I need to assign the list of all files of a directory (site_img) to a javascript array but not getting any luck.Can any one pls help .
i:e In the below code I want to assign the value of filename to an javascript array in each iteration of the for loop.
<?php
foreach(glob('./site_img/*.*') as $filename){
echo $filename;
echo "<br>";
}
?>
With PHP, here is a snippet that I use on one of my sites:
<?
$fileList = '';
$homePath = "a5780630"; //Dev
$homePath = "a2092434"; //Live
if ($handle = opendir('/home/'. $homePath .'/public_html/images/gallery/')) {
/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..') {
$fileList = $fileList . ',' . $file;
}
}
closedir($handle);
}
?>
That will give you a comma delimited string of all the files. Then in JS:
<script language="javascript">
var listOfImages = "<?php echo $fileList; ?>"
listOfImages = listOfImages.split(",");
</script>

Getting value from file called by ajax request using json

This file is called by ajax request. And result coming here I want to place into two different in calling function.
<?php
//Some processing gives $text
$s=nl2br($text);
$data['x'] = $p;
$data['y'] = $q;
//Start from here
echo "<b>Positive count : $x with $p % </b>"; echo "</br>";
echo "<b>Negative count : $y with $q % </b>"; echo "</br>";
echo "</br>";
echo "Page content : ";
echo "</br>";
echo "</br>";
echo $s;
//End. This content should be place in <div1>. Want to send this as a json string
and
//Start from here
echo "First 5 post";
$result = mysqli_query($con,"select post from facebook_posts where p_id > (select MAX(p_id) - 5 from facebook_posts)");
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
echo $row['post'];
echo '<br/>';
}
//End. This content should be placed in <div2> Want to send this as a json string
If there is single variable then we can easily do it using :
$resultArray = array("resultOne" => $result1,"resultTwo" => $result2);
echo json_encode($resultArray);
at receiving end:
document.getElementById("myFirstDiv").innerHTML=xmlhttp.responseText.resultOne;
document.getElementById("mySecondDiv").innerHTML=xmlhttp.responseText.resultTwo;
But how above complex result could be place into to json variable?
You could use output buffering in PHP:
ob_start();
// Generate content for div 1...
$div1 = ob_get_clean();
ob_start();
// Generate content for div 2...
$div2 = ob_get_clean();
$result = array("div1" => $div1, "div2" => $div2);
echo json_encode($result);

Categories

Resources