What I got.
I got an PHP which performs a user LDAP query and stores the result in an array. Within the PHP I JSON_encode($myArray) the array and pass this to an JavaScript file with print_r($myArray). In JavaScript I fill a HTML selection with the myArray as source.
The PHP results looks like, which is fine:
["Mickey Mouse","Donald Duck","Minnie Mouse"]
Whats the problem?
Usually I would fill a source based selection like this, which works with JSON files but not in this case:
var fillUserSelection
for (var key in myArray) {
fillUserSelection += "<option>" + myArray[key] + "</option>"
}
document.getElementbyId("").innerHTML = fillUserSelection
I expected Mickey Mouse, Donald Duck and Minnie Mouse as options. Instead I receive each char as options. Like [,",M,i,c,k,e,y.. etc.
What I want.
I want only Mickey Mouse, Donald Duck and Minnie Mouse as options. What do I miss?
Try something like this.
var myArray = JSON.parse(<?php echo json_encode($phpArray) ?>);
Now your array will work.
<?php $myarray = array("Mickey Mouse","Donald Duck","Minnie Mouse"); ?>
<?php json_encode($myarray); ?>
<?php for ($i = 0; $i < count($myarray); $i++) {?>
<?php echo "$myarray[$i] <br/>"; ?>
<?php } ?>
Related
Here is my code I need how to add a percentage or number to each value in total field I have tried a lot but nothing works.
<?php
$json=file_get_contents("http://www.upliftinghumanity.net/edd-api/sales/?key=75caa8cb60362c89e6ac2b62730cd516&token=6547d40b82cecb81cb7b0ec928554a9e&number=-1");
$data = json_decode($json);
extract(json_decode($json, true));
if (count($data->sales)) {
// Open the table
echo "<table>";
// Cycle through the array
foreach ($data->sales as $idx => $sales)
{
// Output a row
echo "<tr>";
echo "<td>$sales->total</td>";
echo "<td>$sales->total+3 </td>";
echo "<td>$sales->gateway</td>";
echo "<td>$sales->email</td>";
echo "<td>$sales->transaction_id</td>";
echo "</tr>";
}
// Close the table
echo "</table>";
}
?>
result image
You can add it before echoing it out as a string for example $somevar = $sales->data+1; echo "blahh $somevar"; or echo "blahh {$somevar}";
#Ezekiel the problem is solved what you suggest. i was missing some basic stuff . Thanks –
Hi you can't perform php arithmetic operations which its been qouted as a string, you can probably use the "{$sales->data+3}" but it is always advisable to do thr calculation outside the string as this is only a pseudo code "{$sales->data+3}" and may not work even if you include the curly braces
I have a pre Element with id output and try to append multiple elements to it
<pre id="output"></pre>
Now in my PHP Code i run a for loop which simply outputs the counter variable (for the purpose of this example).
<?php
for ($i = 0; $i < 100; $i = $i + 1)
{
echo $i;
}
What is the best way to append these values to the pre element with id output by using PHP?
EDIT: I search for a solution which works if the for loop is not inside the pre tags. It should work no mather where in the code i call the for loop e.g. below the <pre> tags or above the <pre> tags, both should work.
Is this possible with PHP only?
Since the php is rendered on page load, you don't need to append it - just have it in the div and echo it into output directly
<pre id="output">
<?php
$numbers=range (1,100);
foreach ($numbers as $number) {
echo "$number <br/>";
}
?>
</pre>
Not entirely sure if you want to use PHP to append stuff to it, or javascript. Considering your use of tags in this question
But for PHP you should do it at render time like this:
<?php
$output = '';
for ($i = 0; $i < 100; $i++) {
$output .= '<div>' . $i . '</div>';
}
?>
<pre id="output"><?=$output?></pre>
In javascript you can use getElementById()
var output = document.getElementById('output');
for(var i = 0; i < 100; i++) {
output.appendChild(document.createElement('div'));
}
Here's a version that does appends the numbers to the #output, with the php outside of that div as requested by the OP. Still happens at runtime, but this time creates a string and then appends it to the <pre> element as requested. I prefer the first one that I did though, with the php inside the element, unless there is a definitive reason for not using it, I would suggest hat one first.
<pre id="output"></pre>
<?php
$numbers=range (1,100);
$str="";
foreach ($numbers as $number) {
$str .= $number . "<br/>";
}
echo "<script>$('#output').append('$str')</script>";
?>
<?php ob_start(); ?>
<html>
<head></head>
<body>
<pre id="output">###MARK_PRE###</pre>
</body>
</html>
<?php
$html = ob_get_contents();
ob_end_clean();
$loop_result = "";
$arr = ['apple', 'orange', 'bananas'];
foreach($arr as $value)
{
$loop_result .= "$value <br/>\n";
}
$html = trim(str_replace('###MARK_PRE###', $loop_result, $html));
echo $html;
This does the job. It works as you can see no matter if you place the for loop below or above your html.
If it is enough to have the loop above the html it gets much simpler. You should stick to the answer of PierreDuc in this case.
IF you really want to place the html above your php code, then you actually should better use a MVC-Framework like symfony.
I told you the quick and dirty way above.
I just want to note in the end that I actully don't see any reason of placing your php-logic above your html. Since only your html depends on the php and not the other way around what precise advantage do you promise yourself from placing the html above the php?
One last option: It would be even better if you separated your html and php-code entirely and use include. You would end up with two files:
template.html.php:
<html>
<head></head>
<body>
<pre id="output"><?= $pre_tag; ?></pre>
</body>
</html>
logic.php:
$arr = ['apple', 'orange', 'bananas'];
foreach($arr as $value)
{
$pre_tag.= "$value <br/>\n";
}
include('template.html.php');
But the clean and solid solution is to use a MVC-Framework.
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.
I've this problem at the var address line, i think to have write all correctly or not?
<?php for ($i = 1; $i <= count($data); $i++) { ?>
var address = "<?php echo $address[$i].','.$city[$i].','.$region[$i] ?>";
alert(address);
<?php } ?>
You're generating javascript with php and the error you get comes from the javascript part, not php. I guess that one of your variables like $address contains something that isn't valid in js strings, like a newline. The best practice is to use json_encode to encode values for use in javascript:
var address = <?php echo json_encode($address[$i].','.$city[$i].','.$region[$i]) ?>;
I'm trying to make a very simple autocomplete function on a private website using a trie in JavaScript. Problem is the examples I have seen and trying are just using a predefined list in a JavaScript array.
e.g. var arrayObjects = ["Dog","Cat","House","Mouse"];
What I want to do is retrieve MySQL results using PHP and put them into a JavaScript array.
This is what I have so far for the PHP (the JavaScript is fine just need to populate the array):
<?php
$mysqli = new mysqli('SERVER', 'U/NAME', 'P/WORD', 'DB');
if (!$mysqli)
{
die('Could not connect: ' . mysqli_error($mysqli));
}
if ($stmt = $mysqli->prepare("SELECT category.name FROM category")) {
$stmt->bind_result($name);
$OK = $stmt->execute();
}
while($stmt->fetch())
{
printf("%s, ", $name);
}
?>
Then I want to insert essentially each value using something like mysql_fetch_array ($name); (I know this is incorrect but just to show you guys what's going on in my head)
<script> -- this is the javascript part
(function() {
<?php while $stmt=mysql_fetch_array($name))
{
?>
var arrayObjects = [<?php stmt($name) ?>];
<?php }
?>
I can retrieve the results echoing out fine, I can manipulate the trie fine without MYSQL results, I just can't put them together.
In this case, what you're doing is looping through your result array, and each time you're printing out the line var arrayObjects = [<?php stmt($name) ?>];. However this doesn't convert between the PHP array you're getting as a result, and a javascript array.
Since you started doing it this way, you can do:
<?php
//bind to $name
if ($stmt = $mysqli->prepare("SELECT category.name FROM category")) {
$stmt->bind_result($name);
$OK = $stmt->execute();
}
//put all of the resulting names into a PHP array
$result_array = Array();
while($stmt->fetch()) {
$result_array[] = $name;
}
//convert the PHP array into JSON format, so it works with javascript
$json_array = json_encode($result_array);
?>
<script>
//now put it into the javascript
var arrayObjects = <?php echo $json_array; ?>
</script>
Use json_encode to turn your PHP array into a valid javascript object. For example, if you've got the results from your database in a php array called $array:
var obj = "<?php echo json_encode($array); ?>";
You can now use obj in your javascript code
For the auto-completion you can use the <datalist> tag. This is a relatively new feature in HTML5 (see support table) but the polyfill exists.
Fill the <option> tags in php when building the page and you a are done.