Output value in javascript from php loop - javascript

I'm not sure how to search this, but I have an array in php numbered 1 to 20. I have a foreach loop to output the values and have the user be able to click on the numbers. After clicking the number, the page would then output the number clicked.
HTML:
<div id="chapters" onclick="getChapter()">
$array = range(1,20);
foreach($array as $chapter) {
?>
<p class="getChapter" id="currChapter">Chapter <?php echo $chapter;?></p>
<?php
}
?>
</div>
Javascript
function getChapter() {
chapter = document.getElementById("currChapter").id;
document.write(chapter);
}
I'm not able to output the number that the user clicks on.
I have tried putting
id=<?php $chapter?>
, but that does not work as well as replacing id with value and name.

I would recommend passing the $chapter as parameter of a function "Onclick" event :
<div id="chapters">
<?php
$array = range(1,20);
foreach($array as $chapter) {
?>
<p class="getChapter" onClick="getChapter(<?php echo $chapter;?>)">Chapter <?php echo $chapter;?></p>
<?php
}
?>
and the Javascript:
function getChapter(chapterNumber) {
alert(chapterNumber);
}

I don't really understand what you want to do, seems you explanation just a example, but may be this will help. You can call function getChapter with parameter ( onClick="getChapter(<?php echo $chapter;?>) ) :
$array = range(1,20);
foreach($array as $chapter) {
?>
<p class="getChapter" id="currChapter" onClick="getChapter(<?php echo $chapter;?>)">Chapter <?php echo $chapter;?></p>
<?php
}
function getChapter(chapter) {
document.write(chapter);
}

Related

Split a comma delimited string into an array and display on html page

basically I'm making a page where the information from mySQL database will be displayed. I have a column named topics in the database where the string (VARCHAR) goes like this:
Marketing, Business, Law, Medicine, ...
I'm trying to break up this string after a comma and display them in a single line one by one like this:
<h6>Marketing</h6>
<h6>Business</h6>
<h6>Law</h6>
<h6>Medicine</h6>
<h6>...</h6>
I already have a loop for other rows and I'm not sure if it's possible to make a loop in the loop, I'm not even sure if what i'm trying to achieve is possible but I belive it is. Here goes my full PHP code:
<?php
include_once '../handlers/db_conn.php';
$sql = $conn->prepare("SELECT * FROM esc WHERE hosting_country = ?");
$sql->bind_param("s", $hosting_country);
$hosting_country = 'Poland';
$sql->execute();
$result = $sql->get_result();
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
} else {
echo '<p class="not_found">Nothing Found</p>';
}
while($escrow = $result->fetch_assoc()) {
?>
<div class="col-lg-6 col-md-12 col-sm-12 col-12">
<div class="sec1_col1">
<h2><?php echo $escrow['project_name'] ?></h2>
<i class="fi fi-br-world"></i>
<h3><?php echo $escrow['hosting_country'] ?></h3>
<i class="fi fi-sr-calendar-lines"></i>
<h3><?php echo $escrow['start_date'] ?> - <?php echo $escrow['end_date'] ?></h3>
<h4 class="objectives"><?php echo $escrow['objectives'] ?></h4>
<h5>Topics</h5>
<h6><?php echo $escrow['topics'] ?></h6>
<hr>
Read more
</div>
</div>
<?php
}
?>
I'm wondering if it's possible to create another loop in this loop for element, separate this string after a comma and display one by one in tag? Any help would be greatly appreciated. Thanks.
EDIT
This is what I'm trying to achieve:
Quite simple (and yes, you may have as many nested loops inside your code as you want):
Use explode to split your string, then loop over it.
<!-- inside your loop... -->
<h5>Topics</h5>
<?php foreach(explode(", ", $escrow["topics"]) as $topic) { ?>
<h6><?= $topic ?></h6>
<?php } ?>
You can do so with a simple explode by comma, trim (to remove spaces) and join (could be empty, but a newline is nicer).
$topics = 'Marketing, Business, Law, Medicine';
echo join(PHP_EOL, array_map(fn($topic) => '<h6>'. trim($topic) . '</h6>', explode(',' , $topics)));
Output
<h6>Marketing</h6>
<h6>Business</h6>
<h6>Law</h6>
<h6>Medicine</h6>
You could split into an array and then map the array into containing tags:
function h6($n)
{
return "<h6>$n</h6>";
}
$in = "Medicine,Arts,Law";
$components = preg_split("/,/", $in);
$html = implode(array_map('h6', $components));
echo($html);
Use the following code to explode
<!DOCTYPE html>
<html>
<body>
<?php
$str = "Hello,World!,Beautiful,Day!";
$arr = explode (",", $str);//;('Hello','World!','Beautiful','Day!');
foreach ($arr as $item) {
echo "<h6>".$item."</h6>";
}
?>
</body>
</html>

Script works on every post but not the last post

My script removes the http:// and www from urls displayed in a post's content but for some reason it either affects all the posts but the last one or just the first post of the page depending on where I place the script.
For instance if it's in the loop it will affect all the posts but the last but if it's outside the loop it only affects the first post.
I'm looking for a solution so that it takes affect on all urls being displayed on a page. Any help would be much appreciated.
<?php
if (have_posts()) :
while (have_posts()) : the_post(); ?>
<Script>
$(document).ready(function removeFunction() {
let post_id = '<?php global $post; echo $post->ID; ?>';
var str = document.getElementById("link" + post_id).innerHTML;
var res = str.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0];
document.getElementById("link" + post_id).innerHTML = res;
});
</Script>
<p><?php the_content(); ?></p>
<!-- This is where the URL's are EX: <a id="link[return_post_id]" href="http://example.com/">http://example.com/</a> -->
<?php endwhile;
else :
echo '<p>No content found</p>';
endif;
?>
1.You tagged jQuery there so put jQuery code outside of loop.
2.It has to iterate over all <p> and do what you are doing.
3.Change <p><?php the_content(); ?></p> to <p data-id="<?php global $post; echo $post->ID; ?>"><?php the_content(); ?></p> (inside while loop)
4.After above steps followed, change jQuery code like below:
<Script>
$(document).ready(function() {
$('p').each(function(){
let post_id = $(this).data('id');
var str = $(this).html();
var res = str.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0];
$(this).html(res);
});
});
</Script>
there is a problem and this is on mixture of php and javascript.
Your php code Generate JS Within a Loop, in each loop it will create a function named removeFunction() and your browser interpreter mixed up things. it will replace the last one.
There Are 2 Solution for Your problem:
First is to make These Functions Distinct like This:
$(document).ready(function removeFunction<?php echo $post->ID; ?>() {
this will make function names as removeFunction1() removeFunction2() ...
The Second Sulotion is to Define The function outside The loop and in the php loop just call the function like this:
while (have_posts()) : the_post(); ?>
<script>
removeFunction(<?php global $post; echo $post->ID; ?>);
and your function definition would be like this:
removeFunction(post_id){

display php array in javascript [duplicate]

This question already has answers here:
Pass a PHP string to a JavaScript variable (and escape newlines) [duplicate]
(14 answers)
Closed 5 years ago.
I like to display php array in javascript, but in specific element with id.
below is my code which shows what I want to do.
<?php function ogolne_informacje(){
global $mypod;?>
<strong><?php echo 'Pokój: '?></strong><?php echo $mypod->display('room')."<br />";?>
<strong><?php echo 'Email: '?></strong><?php echo $mypod->display('user_email')."<br />";?>
<strong><?php echo 'Telefon: '?></strong><?php echo $mypod->display('phone')."<br />"; }?>
<?php $i =0;
while ( $mypod->fetch() ) :{
ob_start();
ogolne_informacje();
$output[$i] = ob_get_clean();
$i++;
} endwhile;?>
<div id="test"></div>
<script>
var out = <?php echo $output; ?>;
$(document).ready(function () {
$('#test').html(out.toString());
});
</script>
How can I do that?
Thanks!
You can't loop like that, you need to loop the PHP array and push into javascript array:
<script type="text/javascript" language="javascript">
var pausecontent = new Array();
<?php while ( $mypod->fetch() ) :{
ob_start();
ogolne_informacje();
?>
pausecontent.push('<?php echo ob_get_clean(); ?>');
<?php } ?>
</script>

How to get a value of an attribute inside a loop using jQuery

I have this code from my HTML form.
<?php foreach ($charges as $c): ?>
<br><input type="checkbox" id="charge<?php echo $c->id; ?>" cash="<?php echo $c->amount; ?>"> <?php echo $c->description; ?>
<?php } ?>
when I tick a textbox I want the value for that element pops up.
So far, only the value for the first occurrence pops up.
This is the jQuery code. I know I'm missing something, but i dont know
function triggerChange1(){
$("#ch1").trigger("change");
}
$("#charge1").change(function() {
var v = $(this).attr('cash');
alert(v);
});
if($("#charge1").prop('checked')){
triggerChange1();
}
Firstly you should use a class attribute to group elements together. You should also use data-* attributes to assign any custom meta data to an element as creating your own non-standard attributes will render the page invalid and lead to potential UI and JS issues:
<?php foreach ($charges as $c): ?>
<br><input type="checkbox" class="charge" id="charge<?php echo $c->id; ?>" data-cash="<?php echo $c->amount; ?>"> <?php echo $c->description; ?>
<?php } ?>
Then you can have a single click handler to get the value from the element which raised the event:
$('.charge').change(function() {
var v = $(this).data('cash');
alert(v);
});
// raise the event on checked elements on load:
$('.charge:checked').change();
EDIT: As rightfully stated in Rory's answer you should prefix your custom attributes with data-
What you need is a class.
<?php foreach ($charges as $c): ?>
<br><input type="checkbox" class="charge" id="charge<?php echo $c->id; ?>" data-cash="<?php echo $c->amount; ?>"> <?php echo $c->description; ?>
<?php } ?>
$(".charge").change(function() {
var v = $(this).data('cash');
alert(v);
});
You can see it working here: http://jsfiddle.net/0cude9jr/
function triggerChange1(){
$("#ch1").trigger("change");
}
$(document).ready(function() {
$("#charge1").change(function() {
var v = $(this).attr('cash');
alert(v);
});
if($("#charge1").prop('checked')){
triggerChange1();
}
}
And you should use value attribute and not cash attribute.
And then you can call var v = $(this).val();

Get all data from mysql display in div php javascript

Hello my problem is simple , i have a table news , i have a button bt1 , and a div to show the results , i want to display all rows from table when i click the button,i only get the first row , how can i display all results ?
<script>
function shownews(id) { <? php
include('db.php');
$query = mysql_query("SELECT * FROM news");
while ($row = mysql_fetch_array($query)) {
$a = $row['news_title'];
} ?>
var ab = <? php echo json_encode($a); ?> ;
id.innerHTML = ab;
}
</script>
<div id="results"></div>
<button id="btn1" onclick="shownews(results)">See news</button>
try
$a = array();
while ($row = mysql_fetch_array($query)) {
$a[] = $row['news_title'];
} ?>
// print array
print_r($a);
Your echo json_encode($a); is not in your while loop, so you only render 1 line.
Also if i understand what you're doing, you want your PHP to be executed only when you trigger your button click ? This is not the way to do it... php is a server language where javascript is executed only by your browser.
I didn't
Try this :
<script type="text/javascript">
function shownews(id) {
document.getElementById(id).innerHTML = document.getElementById('news').innerHTML ;
}
</script>
<div id="news" style="display:none ;">
<?php
include ('db.php');
$query=mysql_query("SELECT * FROM news");
while($row=mysql_fetch_array($query)){
echo $row['news_title'] . '<br />' ;
}
?>
</div>
<div id="results"></div>
<button id="btn1" onclick="shownews('results')">See news</button>
You are overwriting $a, hence you will only get the last row.
Change
while($row=mysql_fetch_array($query)){
$a=$row['news_title'];
}
to
$a = array();
while($row=mysql_fetch_array($query)){
array_push($a, $row['news_title']);
}
Edit: Royal_bg is correct - extra info:
Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function. http://us2.php.net/array_push
You execute all the while before writing anything. Try to change the closing bracket after writing the answer...
<script>
function shownews(id){
<?php
include ('db.php');
$query=mysql_query("SELECT * FROM news");
while($row=mysql_fetch_array($query)){
$a=$row['news_title'];
?>
var ab = <?php echo $a; ?>;
id.innerHTML += ab;
<?php
}
?>
}
</script>
<div id="results"></div>
<button id="btn1" onclick="shownews(results)">See news</button>
function shownews(id){
<?php
include ('db.php');
$query=mysql_query("SELECT * FROM news");
while($row=mysql_fetch_array($query)){
$a[]=$row['news_title'];
}
?>
id.innerHTML=<?php echo json_encode($a); ?>;
}

Categories