Adding javascript onclick event to php array? - javascript

I recently started coding and I'm trying different things such as PHP and JavaScript. I'm sorry if this question has an easy solution. I couldn't find it anyway.
Context
I'm working on a project for school where we need to make a playlist with album specifics in HTML table. The page looks like this:
Playlist page
Question
I have three javascript onclick events. One of them looks like this.
<a id="songcolor" onclick="document.getElementById('audioone').src='songs/californication.mp3';
player = document.getElementById('audioone');
player.play();
">Play song 1 -</a></td>
When you click the anchor tag (play song 1, play song 2, play song 3) in the page I'm building a audio element starts playing. This is working as of now. But in the assignment requirement I need to get the code above out of PHP array and into HTML table using a for loop. How do you go about this?
What I've tried?
I've tried a couple of things.
I tried to add the onclick event into my PHP array and tried to loop it out using for loop. This didn't work. This is a snippet of the array i'm talking about:
array(1, "Californication", "3:45", )
This is the for loop i use for putting it in a table:
for ($row = 4; $row <= 7; $row++)
{
echo "<tr>";
for ($col = 0; $col <= 3; $col++)
{
echo "<td>" . $multiArray[$row][$col] . "</td>";
}
echo "</tr>";
}
echo "</table>";
?>
I tried storing the onclick event into JavaScript variable and using that variable into PHP array. This didn't work.
Again I'm new to all of this so please help me understand.

You should simplify the readability of your code using array elements that are more obvious to you and others using associative arrays. In your case, an array of associative arrays:
<?php
$media_array = array(
array('elementId' => 'audioone',
'source' => 'songs/californication.mp3'
),
array('elementId' => "audiotwo",
'source' => 'songs/californication.mp3'
),
array('elementId' => "audiothree",
'source' => 'songs/californication.mp3'
)
);
?>
<table>
<?php
$index = 1;
foreach ($media_array as $mediaKey => $mediaObject) {
?>
<tr>
<td>
<a id="songcolor<?php echo $index; ?>" onclick="document.getElementById('<?php echo $mediaObject['elementId']; ?>').src='<?php echo $mediaObject['source']; ?>'; player = document.getElementById('<?php echo $mediaObject['elementId']; ?>'); player.play();">Play song <?php echo $index; ?></a>
</td>
</tr>
<?php
$index++;
}
?>
</table>

Related

utilize PHP array as HTML selection

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 } ?>

Calculation in retrieved JSON API data

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

PHP - Append text into html element with certain id

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.

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.

Assist with javascript functions being contained within a loop (PHP)

I am working on a project where I have divisions stored in mysql database with the "division id" and the "division name";
what I want to have is so that i use php to do a "while" loop and go through all the divisions;
then for each division it creates a button which will trigger a javascript function…
I have done a lot of testing on this so I know certain parts are working…; here is my code:
<p id="id57512">How are you?</p>
<script>
var g_myobj = {};
</script>
<?php
$result_g1 = mysql_query("SELECT * FROM divisions");
while($row = mysql_fetch_array($result_g1, MYSQL_BOTH))
{
$div_id=$row[div_id];
$div_name=$row[div_name];
$button_id="b";
$button_id.=$div_id;
$function_id="f";
$function_id.=$div_id;
?>
<button id=<?php echo $button_id; ?>><?php echo $div_name; ?></button>
<script>
var f_id='<?php echo $function_id; ?>';
var b_id='<?php echo $button_id; ?>';
var div_id='<?php echo $div_id; ?>';
var newFieldName = f_id;
var newFieldValue = function() {document.getElementById("id57512").firstChild.nodeValue=gman_code1(div_id);};
g_myobj[newFieldName] = newFieldValue;
var gman_code1 = function(number) {
var result1 = number*2;
console.log(result1);
return result1;//add return statement
}
//define the behavior
document.getElementById(b_id).addEventListener("click", g_myobj[f_id] , false);
</script>
<?php
}
the function names need to be a variable; but I figured out how to do that by making it an object; and so can access the different functions that way…
I basically tested this all when it was not in a loop; where I manually had it do everything twice (even creating the functions in the object) and it all worked fine…
basically when you click on a button it is supposed to send a number to that "p" container and multiply it by 2
when I did it manually and not in loop i just had it create the object g_myobj first and then just started adding items to the object…
but now that i am doing this in a loop - I felt I could not have the statement that creates the empty object in the loop or it would just keep recreating it; so I went above the loop and had the object created there in its own "script" tags all by itself…
that part may be a problem with this, not sure at all…
another potential problem is that I am not sure if I can do all this in a loop like this
it is a "php loop" and so maybe this just all cannot be done in a loop like that…
What is going on is the first button works but none of the others do…
So, I am hoping someone can advise me on what I am doing wrong on this…
Thanks so much...
If all you are trying to do is send a number to <p> and multiply it by 2, see this one liner function. I assume you are trying to accomplish more than just the multiplying thing otherwise you probably would have just done a simple function like below...
Also, I'm sure you will get lots of comments on it, but you should not be using the mysql_ functions anymore. They are both deprecated and potentially unsafe. You should use mysqli or PDO prepared statements.
On your button, you should probably put quotes around the id="yadayada" instead of id=yadayada. jQuery may be a good option for your js to handle functions or what-have-you.
<p id="id57512">How are you?</p>
<?php
$result_g1 = mysql_query("SELECT * FROM divisions");
while($row = mysql_fetch_array($result_g1, MYSQL_BOTH)) {
$div_id = $row[div_id];
$div_name = $row[div_name];
$button_id = "b$div_id";
$function_id = "f$div_id"; ?>
<button id="<?php echo $button_id; ?>" onClick="MyRadFunction('<?php echo $div_id; ?>')">
<?php echo $div_name; ?></button>
<?php } ?>
<script>
function MyRadFunction(DivId) {
$("#id57512").html(DivId*2);
// var NewNum = $("#id57512").text();
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
When rendering your button, you should wrap the id in quotes, e.g.
<button id='<?php echo $button_id; ?>'><?php echo $div_name; ?></button>

Categories