how to get value from php loop to div - javascript

i want to change div value when clicking php while loop.,
My php code
<?php $query = mysql_query("select * from tbl_sub_product where product_id='$id'");
while($row=mysql_fetch_array($query))
{ ?>
<div><a href="#" class="showElement" id="showElement" >
<?php echo $row['name']; ?><?php echo $row['id']; ?></a></div>
<?php } ?>
my query was
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
var $target = $('#target');
$(".showElement").click( function(e) {
e.preventDefault();
$target.append( $(this).text() );
});
});
</script>
i want the result in this div
<div id="target">user Id:<php echo $id ?>User Nmae:<?php echo $name ?>user designation :<?php echo $designation ?></div>
what changes i want to do my code for getting data in my second div

You're asking to take the mysql data from php and magically know what it is without querying again with AJAX or some other request.
There are many ways you can do this, but the simplest is to store the exact view of what you want in a child div below the a tag.
You need to change to prepared statements too.... If you don't want to fine just change the stmt stuff back to what you have and row will do what you want.
<style>
.hidden{
display: none;
}
</style>
<?php
$stmt = mysqli_prepare("select * from tbl_sub_product where product_id='$id'");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()){
?>
<div>
<a href="#" class="showElement" >
<?php echo $row['name']; ?> <?php echo $row['id']; ?>
</a>
<div class="hidden getTarget">
user id: <php echo $row['id']; ?>
User name: <?php echo $row['name']; ?>
user designation: <?php echo $row['designation']; ?>
</div>
</div>
<?php
}
?>
<script>
$(document).ready(function(){
var $target = $('#target');
$(".showElement").click( function(e) {
e.preventDefault();
$target.append( $(this).parent().find('.getTarget').text() );
});
});
</script>
Don't use ids in a loop. Unless you have a specific identifier to separate each one.
Don't copy and paste as well.. please read the code and understand it.

Related

How to Create Load More With PHP and PDO

i want to create load more to my site, but when i try to click load more it just load 2 items.
my index.php
<div class="postList">
<?php
// Include the database configuration file
include 'koneksi.php';
// Get records from the database
$query = $db->prepare("SELECT * FROM master_post, posting WHERE master_post.master_post_name = posting.master_post_name AND posting.sticky = 'Normal' ORDER BY posting.idpost DESC LIMIT 2");
$query->execute();
if($query->rowCount() > 0){
while($row = $query->fetch()){
$postID = $row['idpost'];
?>
<div class="list_item"><?php echo $row['file_name']; ?></div>
<?php } ?>
<div class="show_more_main" id="show_more_main<?php echo $postID; ?>">
<span id="<?php echo $postID; ?>" class="show_more" title="Load more posts">Show more</span>
<span class="loding" style="display: none;"><span class="loding_txt">Loading...</span></span>
</div>
<?php } ?>
</div>
my javascript
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.show_more',function(){
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type:'POST',
url:'ajax_more.php',
data:'id='+ID,
success:function(html){
$('#show_more_main'+ID).remove();
$('.postList').append(html);
}
});
});
});
</script>
my ajax_more.php
if(!empty($_POST["id"])){
// Include the database configuration file
include 'koneksi.php';
// Count all records except already displayed
$query = $db->prepare("SELECT COUNT(*) as num_rows FROM master_post, posting WHERE master_post.master_post_name = posting.master_post_name AND posting.sticky = 'Normal' AND posting.idpost < ".$_POST['id']." ORDER BY posting.idpost DESC");
$row = $query->fetch();
$totalRowCount = $row['num_rows'];
$showLimit = 2;
// Get records from the database
$query = $db->query("SELECT * FROM master_post, posting WHERE master_post.master_post_name = posting.master_post_name AND posting.sticky = 'Normal' AND posting.idpost < ".$_POST['id']." ORDER BY posting.idpost DESC LIMIT $showLimit");
if($query->rowCount() > 0){
while($row = $query->fetch()){
$postID = $row['idpost'];
?>
<div class="list_item"><?php echo $row['file_name']; ?></div>
<?php } ?>
<?php if($totalRowCount > $showLimit){ ?>
<div class="show_more_main" id="show_more_main<?php echo $postID; ?>">
<span id="<?php echo $postID; ?>" class="show_more" title="Load more posts">Show more</span>
<span class="loding" style="display: none;"><span class="loding_txt">Loading...</span></span>
</div>
<?php } ?>
<?php
}
}
I'm not sure where the mistake is. im using tutorial from this site https://www.codexworld.com/load-more-data-using-jquery-ajax-php-from-database/

php while but the result have to shows in javascript

I have the following code and what I'm trying to do is to show the mysql result in the message box with javascript, but when I click on the message box it shows me only one result for every button.
I want every button have his own message which is in database.
Does anybody have an idea on how I can do it?
<?
$query = "SELECT * FROM `Points`";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
?>
<div style="position:absolute; overflow:hidden; <?php echo $row[Pos]; ?> height:23px; z-index:0">
<button onClick="showMsgBox();" id="showBtn">Show MsgBox</button>
</div>
<script>
$("#showBtn").focus();
msgBoxImagePath = "images/";
function showMsgBox() {
$.msgBox({
title: "Ads",
content: "<? echo $row[Ctn]; ?>",
type: "alert"
});
}
</script>
<?}?>
In the database Pos is the position of the button and Ctn is the message.
Please help.
Try this ;)
<?php
$query = "SELECT * FROM `Points`";
$result = mysql_query($query);
/* all messages */
$messages = array();
$index = 0;
while($row = mysql_fetch_assoc($result)){
$messages[] = $row['Ctn'];
?>
<div style="position:absolute; overflow:hidden; <?php echo $row['Pos']; ?> height:23px; z-index:0">
<button onClick="showMsgBox(<? echo $index++; ?>);" id="showBtn">Show MsgBox</button>
</div>
<?php
}
?>
<script>
var messages = <?php echo json_encode($messages); ?>;
$("#showBtn").focus();
msgBoxImagePath = "images/";
function showMsgBox(index){
$.msgBox({
title: "Ads",
content: messages[index],
type: "alert"
});
}
</script>
Used <?php ... ?> tags you can change as per your need;
Firstly, you id should be unique, if your input is the loop make sure your id is also unique.
Please see code below this might work for you.
<?
$query = "SELECT * FROM 'Points'";
$result = mysql_query($query);
$queryCounter = 0;
$message = array();
while($row = mysql_fetch_assoc($result)){
$message[$queryCounter] = $row[Ctn];
?>
<div style="position:absolute; overflow:hidden; <?php echo $row[Pos]; ?> height:23px; z-index:0">
<button onClick="showMsgBox(<?php echo $queryCounter; ?>);" id="showBtn<?php echo $queryCounter; ?>">Show MsgBox</button>
</div>
<script>
$("#showBtn").focus();
msgBoxImagePath = "images/";
function showMsgBox(id) {
$.msgBox({
title: "Ads",
content: "<? echo $message[id]; ?>",
type: "alert"
});
}
</script>
<? $queryCounter ++; }?>
check out this code, i hope it will work for you, here i have used data-value html5 attribute to get the message when button is clicked.
<?php
$query = "SELECT * FROM `Points`";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
?>
<div style="position:absolute; overflow:hidden; <?php echo $row['Pos']; ?> height:23px; z-index:0" data-value="<?php echo $row['Ctn']; ?>" id="showMsgBoxContent_<?php echo $row['id'];?>" >
<button onClick="showMsgBox(<?php echo $row['id']; ?>);" id="showBtn_<?php echo $row['id']; ?>">Show MsgBox</button>
</div>
<?php
}
?>
<script>
msgBoxImagePath = "images/";
function showMsgBox(id)
{
$("#showBtn_"+id).focus();
var showContent = $('#showMsgBoxContent_'+id).getAttribute('data-value');
$.msgBox({
title: "Ads",
content: showContent,
type: "alert"
});
}
</script>

How to auto refresh div contents contain php variables?

I created a page named queries.php
<?php
require("connection.inc.php");
$query = "SELECT SUM(john), SUM(robert), COUNT(school) FROM election";
$result = mysql_db_query($db, $query, $connection) or
die("query error!");
$data = mysql_fetch_array($result);
$john = number_format($data[0], 0,',','.');
$robert = number_format($data[1], 0,',','.');
$school = $data[2];
$total = $john + $robert;
$remaining_school = 524 - $school;
$percentage_john = round(($john*100/$total),2);
$percentage_robert = round(($robert*100/$total),2);
?>
Then I display the data in display.php
The data displayed well and nothing error, I tried a couple of tricks to auto refresh the container using jquery but failed.
Here is my display.php page:
<?php
include("queries.php");
?>
<div id="totaljohn"> // <--- the div id taken from css layout
<h9>John: <?php echo $john; ?> <br> (<?php echo $percentage_john; ?> %)</h9>
</div>
<div id="totalrobert">
<h9>Robert: <?php echo $robert; ?><br> (<?php echo $percentage_robert; ?> %)</h9>
</div>
<div id="totalboth">
<h4>Total : <?php echo $total; ?> Suara</h4>
</div>
<div id="totalschool">
<h4>Total School attending : <?php echo $school; ?> Schools</h4>
</div>
<div id="remaining_schools">
<h4>Remaining Schools: <?php echo $remaining_school; ?> of 524 schools</h4>
</div>
Everything looks good. Is your database connected? Is your SQL correct? Are there records in the database returned for your query?

How to create for each div in a while loop an ID and alert it with JQuery

I have 2 paragraphs coming from the database it work there is no issues with it. But I have added a button that when I click it will alert the ID of this current div which the button is present.
Now this is my table:
+--------+--------------------+
| id | paragraph |
|--------+--------------------+
| 1 | this is text 1 |
| 2 | another text |
+-----------------------------+
My PHP and HTML code:
<?php
$query = mysql_query(SELECT * FROM tests);
while($row = mysql_fetch_assoc($query)){
$post_id = $row['id'];
$text = $row['paragraph'];
?>
<div id='text' class='<?php echo "$post_id";?>'>
<p><?php echo "$text";?></p>
<input type='button' value='Show id' id='show'>
</div>
<?php } ?>
And now probably 2 paragraphs are generated but when I click at show button it will show only the 1 id even if I click at the second one:
This is my JQuery code:
$('#show').click(function(){
var ids = $("#text").attr('class');
alert(ids);
});
id="" attribute values are supposed to be unique. do the other way around:
<div id="<?php echo $post_id; ?>" class='text'>
<p><?php echo $text; ?></p>
<input type='button' value='Show id' class='button'>
</div>
jquery
$('.button').click(function(){
var ids = $(this).parent('div').attr('id');
alert(ids);
});
Note: Stop using mysql_ functions, instead use mysqli_* or PDO
Sample:
<?php
$con = new mysqli('localhost', 'username', 'password', 'database');
$result = mysqli_query($con, 'SELECT * FROM tests');
while($row = $result->fetch_assoc()) {
$post_id = $row['id'];
$text = $row['paragraph'];
?>
<div id="post_<?php echo $post_id; ?>">
<p><?php echo $text; ?></p>
<button type="button" class="button">Show</button>
</div>
<?php } ?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$('.button').click(function(){
var ids = $(this).parent('div').attr('id');
alert(ids);
});
</script>
Very important point from Jeroen:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
Reference
this is hard to read
<?php
$query = mysql_query(SELECT * FROM tests);
while($row = mysql_fetch_assoc($query)){
$post_id = $row['id'];
$text = $row['paragraph'];
?>
<div id='text' class='<?php echo "$post_id";?>'>
<p><?php echo "$text";?></p>
<input type='button' value='Show id' id='show'>
</div>
<?php } ?>
Try something like this
<?php
$query = mysql_query('SELECT * FROM tests');
while(false !== ( $row = mysql_fetch_assoc($query))):
?>
<div class='text' id='post-<?php echo $row['id']; ?>'>
<p><?php echo $row['paragraph']; ?></p>
<input type='button' value='Show id' id='show'>
</div>
<?php endwhile; ?>
I don't see how the query worked without quotes. Just to explain you can use the alternative syntax for the while, so instead of
<?php while(. .. ){ ?>
<html></html>
<?php } ?>
do
<?php while(... ): ?>
<html></html>
<?php endwhile; ?>
When you have a lot of html ( this is a small example ) you can easily find the diffrence between endif; endwhile; or endforeach; then } } or }
Why don't you just pass the ID as a parameter?
<?php
$query = mysql_query("SELECT * FROM tests");
while($row = mysql_fetch_assoc($query)){
$post_id = $row['id'];
$text = $row['paragraph'];
?>
<div id='text' class='<?php echo "$post_id";?>'>
<p><?php echo "$text";?></p>
<input type='button' value='Show id' id='show' onclick="showId(<?php echo $post_id; ?>);">
</div>
<?php } ?>
Then your script could look like this:
function showId(theId){
alert(theId);
}
where it says:
class='<?php echo "$post_id";?>'
when you're echoing a php variable, you dont put quotes around it:
class='<?php echo $post_id;?>'.

Sequential jquery 'pages', third frame gives a reference error

I am quite new to javascript/jquery and having been playing around with the w3schools tutorials and the jquery documentation and made a page which will accept some user input and then via javascript print some output. I assumed i could modify this to work sequentially but when the second page should call the third page I get
ReferenceError: $gp is not defined
[Break On This Error]
$('#txtField2').load('getglycosites.php?q='+$gp+'r='+$('.glycotype').val());
I would appreciate if anyone has a trick to be able to use the $_get variable in the jquery script.
Code for pages:
first page (test.php):
<html>
<head>
<title>LeidenGlycoPeptide DataBase</title>
<script src="jquery-1.9.1.min.js"></script>
</head>
<script>
$(document).ready(function() {
$('.glycoprotein').change(function() {
$('#txtField').load('getglycopeptides.php?gp='+$('.glycoprotein').val());
});
});
</script>
<body>
<h1>Welcome to the LeidenGlycoPeptide DataBase</h1>
<?php
$link = mysql_connect("localhost","reader","") or die (mysql_error());
mysql_select_db('leidenGlycoPeptide') or die ();
$query = 'select protein from glycoPeptide';
$result = mysql_query($query);
mysql_close($link);
?>
<form>
<p>Select glycopeptide to search for (interactive dialog)</p>
<?php
echo"<select class=\"glycoprotein\">";
echo"<option value=\"\">select glycoprotein</option>";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
foreach ($line as $col_value) {
echo"<option value=\"$col_value\">$col_value</option>";
}
}
echo"</select>";
?>
</form>
<br>
<div id="txtField"></div>
</body>
</html>
Second Page (getglycopeptides.php):
<html>
<head>
<title>glyco</title>
<script src="jquery-1.9.1.min.js"></script>
</head>
<script>
$(document).ready(function() {
$('.glycotype').change(function() {
//NOTE $q/q are undefined
$('#txtField2').load('getglycosites.php?q='+$gp+'r='+$('.glycotype').val());
});
});
</script>
<body>
<?php
// The next variable is the one I would like to use inside the jquery
$gp=$_GET["gp"];
$link = mysql_connect("localhost","reader","") or die (mysql_error());
mysql_select_db("leidenGlycoPeptide",$link) or die();
$query = "select glycoType from run,glycoPeptide where run.id = glycoPeptide.id and glycoPeptide.protein like '".$gp."'";
$result = mysql_query($query);
?>
<form>
<?php
echo "<select class=\"glycotype\">";
echo "<option value=\"\">select glycosylation</option>";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
foreach ($row as $col_value)
{
echo"<option value=\"$col_value\">$col_value</option>";
}
}
echo "</select>";
mysql_close($link);
?>
</form>
<br>
<div id="txtField2"></div>
</body>
</html>
The third page (getglycosites.php):
<html>
<head>
<title>sites</title>
</head>
<body>
<?php
$gp=$_GET["gp"];
$r=$_GET["r"];
$link = mysql_connect("localhost","reader","") or die (mysql_error());
mysql_select_db("leidenGlycoPeptide",$link) or die();
$query = "select glycoSite from run,glycoPeptide where run.id = glycoPeptide.id and run.glycoType like '".$r."' and glycoPeptide.protein like '".$q."'";
//echo $query;
$result = mysql_query($query);
echo "<select name=\"site\" onchange=\"foo\">";
echo "<option value=\"\">select glycosite</option>";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
foreach ($row as $col_value)
{
echo"<option value=\"$col_value\">$col_value</option>";
}
}
echo "</select>";
mysql_close($link);
?>
</body>
</html>
PS: The third page is currently only supposed to show a new select field but once I get this working it will be a part in a large sequential sequence.
Thanks in advance
I was able to 'fix' this by adding the following line (to the jquery script):
var gp = '<?php echo htmlspecialchars($_GET['gp']); ?>';
Making the total script part of the third page:
<script>
var gp = '<?php echo htmlspecialchars($_GET['gp']); ?>';
$(document).ready(function() {
$('.glycotype').change(function() {
$('#txtField2').load('getglycosites.php?q='+gp+'&r='+$('.glycotype').val());
});
});
</script>

Categories