I have problem with $(this).nextAll("#status").eq(0).text("Deleted").
I want to in the tag <span> put a text: "Deleted", but but does not insert it...
See the my code:
admin.php PHP:
$sql = "SELECT * FROM `upload_img`";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo "<div class='image' data-id='".$row['id']."'><br>";
echo "<span><strong>Image title</strong>: ".$row['image_title']."</span><br>";
echo "<span><strong>User of image</strong>: ".$row['user_name']."</span><br>";
echo "<span><strong>Image file name</strong>: ".$row['image']."</span><br>";
echo "<span id='status'></span>";
echo "<button class='delete' data-id='".$row['id']."'>Delete</button><hr>";
echo "</div>";
}
admin.js JS:
$(".delete").on("click", function() {
var id = $(this).data("id");
$(this).nextAll("#status").eq(0).text("Deleted"); //This is not work!
$.post("adminServer.php", { id: id }, function(data) {
data = JSON.parse(data);
alert(data);
});
});
I do not know why it does not work...
Thanks!
Firstly part of your problem is that id attributes must be unique within the DOM. As such, only the first one will be recognised. You need to change the HTML generated to use a class on the status element instead:
$sql = "SELECT * FROM `upload_img`";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo '<div class="image" data-id="'.$row['id'].'"><br>';
echo '<span><strong>Image title</strong>: '.$row['image_title'].'</span><br>';
echo '<span><strong>User of image</strong>: '.$row['user_name'].'</span><br>';
echo '<span><strong>Image file name</strong>: '.$row['image'].'</span><br>';
echo '<span class="status"></span>'; // change the id to class here
echo '<button class="delete" data-id="'.$row['id'].'">Delete</button><hr>';
echo '</div>';
}
Secondly your DOM traversal logic isn't quite right. nextAll() goes through successive siblings, yet the status you're looking for is a preceding sibling. You can either use prev() or get the closest() parent, then find() within that. The latter is far more robust should you ever change the order of HTML elements. Also note that eq(0) is redundant as there's only one status generated per .image container.
$(".delete").on("click", function() {
var id = $(this).data("id");
$(this).closest('div.image').find('.status').text("Deleted");
$.post("adminServer.php", { id: id }, function(data) {
data = JSON.parse(data);
console.log(data); // don't use alert() for debugging.
});
});
Check below code with sample data. Hope it helps.
$(this).siblings(".status").eq(0).text("Deleted");
It gets nearby sibling with id status and update with status "Deleted"
$(".delete").on("click", function() {
var id = $(this).data("id");
$(this).siblings(".status").eq(0).text("Deleted");
/*
$.post("adminServer.php", { id: id }, function(data) {
data = JSON.parse(data);
console.log(data); // don't use alert() for debugging.
});
*/
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='image' data-id='1'>
<br>
<span><strong>Image title</strong>: Test1</span><br>
<span><strong>User of image</strong>: Test1</span><br>
<span><strong>Image file name</strong>: Test1</span><br>
<span class='status'></span>
<button class='delete' data-id='1'>Delete</button><hr>
</div>
<div class='image' data-id='2'>
<br>
<span><strong>Image title</strong>: Test2</span><br>
<span><strong>User of image</strong>: Test2</span><br>
<span><strong>Image file name</strong>: Test2</span><br>
<span class='status'></span>
<button class='delete' data-id='2'>Delete</button><hr>
</div>
<div class='image' data-id='3'>
<br>
<span><strong>Image title</strong>: Test3</span><br>
<span><strong>User of image</strong>: Test3</span><br>
<span><strong>Image file name</strong>: Test3</span><br>
<span class='status'></span>
<button class='delete' data-id='3'>Delete</button><hr>
</div>
Related
This div act as a button. Whenever I click one, the page goes to the page name "teacherinfo.php". The "Sample" text is used as the name of the teacher. The problem is when I click the "Sample2" the Sample text appear on the "teacherinfo.php" page.
Here is the script for going to "teacherinfo.php":
<?php
while ($row = mysqli_fetch_array($query)) {
echo '<div class="announcementSlider" id="click">
<img src="pictures/blank photo.png" class="teacherpic"><br>
<span name="LastName">'.$row['LastName'].'</span><br>
<span>'.$row['Grade'].' - </span>
<span>'.$row['Section'].'</span>
</div>';
}
?>
<script type="text/javascript">
var a = document.getElementsByClassName("announcementSlider");
for (i=0; i<a.length; i++) {
a[i].onclick = function () {
location.href = "teacherinfo.php";
};
}
</script>
Code for displaying the text in "teacherinfo.php":
<div class="leftForm hide-on-med-and-down">
<img src="pictures/default-avatar-250x250.png">
<p class="name"><?php echo $name3; ?></p>
<p class="section"><?php echo $grade3; ?>-<?php echo $section; ?></p>
</div>
Code for retrieving data in database:
$sql3 = mysqli_query($db,"select * from teacherinfo");
$row3 = mysqli_fetch_array($sql3,MYSQLI_ASSOC);
$name3 = $row3['LastName'];
$grade3 = $row3['Grade'];
$section3 = $row3['Section'];
I want to use the "'.$row['LastName'].'" as a where clause in mysqli_query($db,"select * from teacherinfo"). How can I do that? or is there another solution to this issue?
First of all, I don't understand why you use javascript when you can use simple a tag with correct href:
<?php
while ($row = mysqli_fetch_array($query)) {
echo '<a class="announcementSlider" href="teacherinfo.php?id=' . $row['id'] . '">
<img src="pictures/blank photo.png" class="teacherpic"><br>
<span name="LastName">'.$row['LastName'].'</span><br>
<span>'.$row['Grade'].' - </span>
<span>'.$row['Section'].'</span>
</a>';
}
?>
Here, I suppose that every teacher in your mysql-table has some unique id field.
On teacherinfo.php you access id as $_GET['id'] and create a query like (here I skip security part, but $_GET['id'] can be forged and therefore contain some insecure data, you have to check it):
sql3 = mysqli_query($db,"select * from teacherinfo where id = " . $_GET['id']);
$row3 = mysqli_fetch_array($sql3,MYSQLI_ASSOC);
$name3 = $row3['LastName'];
$grade3 = $row3['Grade'];
$section3 = $row3['Section'];
I am pulling text from my database and inserting into a P TAG that has a class that serves as a handle for my listener, however when I click on the text, nothing happens the JavaScript does not react.
Website : http://fluentabc.com/edit.php
Here is a Picture :
HTML
<p class="sec_text" id="sec_1" data-reveal-id="myModal">
<?php
$query = mysqli_query($con,"SELECT * FROM site_edit WHERE site_sec='MainTitle'");
while($qt = mysqli_fetch_array($query)){
echo $MainTitle = $qt['site_txt']; // <-- I WANT TO CLICK ON THIS TEXT
}
?>
</p>
JS
$(document.body).on('click', '.sec_text' ,function(){
var txt = $(this).text();
var sec_id = $(this).parent().attr('id');
$("#curEditing").html("Your Editing : " + sec_id);
$("#sec_edit_name").val(sec_id);
tinyMCE.activeEditor.setContent(txt);
});
Just update your html code 100% working:
Your output should be like this:
<p class="sec_text" id="sec_1" data-reveal-id="myModal">Learn English Today!</p>
Update HTML:
<p class="sec_text" id="sec_1" data-reveal-id="myModal">
<?php
$query = mysqli_query($con,"SELECT * FROM site_edit WHERE site_sec='MainTitle'");
while($qt = mysqli_fetch_array($query)){
echo $MainTitle = strip_tags($qt['site_txt']); // <-- I WANT TO CLICK ON THIS TEXT
}
?>
</p>
<div>
<?php
$query = mysqli_query($con,"SELECT * FROM site_edit WHERE site_sec='MainTitle'");
while($qt = mysqli_fetch_array($query)){
echo '<p class="sec_text" id="sec_1" data-reveal-id="myModal"'>.$qt['site_txt'].'</p>'; // <-- I WANT TO CLICK ON THIS TEXT
}
?>
</div>
So I got most of my php and jquery working but I am currently stuggling on one thing which is how do I pass a db value in a while loop on button click to the jquery? At present nothing is being printed
<?php
...
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_assoc($result)){
print
"<div class='item col-xs-4 col-lg-4'>".
"<div class='row'>".
"<div class='col-xs-10'>".
"<p class='list-group-item-text'>".
"<input type='text' class='form-control' id='usr'>".
"<button id='button' class='btn btn-success'>Calculate</button>".
"</div>".
"</div>".
"</div>";
}
}
?>
<script type="text/javascript">
$(document).on("click", "#button", function(){
var name = '<?php echo($row['name']); ?>';
alert(name);
});
</script>
Say there are like seven of these boxes and the user clicks on the fourth one - how do I get that row name, like pass that to the jquery?
Ok, we need to change a few things. Every element in the HTML DOM needs a unique id. If more than one element has the same id, the machines get very confused. This is understandable, since you're saying hey pay attention to the button with the id #button! And it's like, which one? There are 7. We can add a unique id to each button during the loop by using the id from the current row the loop is fetching from the db. NB that in HTML, element ids cannot begin with a number. That's why I used button-45,etc.
We can also change the listener to listen to a class of buttons instead of a specific button - that way if any button on the page with the right class gets clicked, the listener hears it. Using jQuery you can also add data directly to the element, and retrieve is using .data(). I've provided two variables in the javascript so you can see the results of each approach.
<?php
...
if(mysqli_num_rows($result)){
$i = 0;
while($row = mysqli_fetch_assoc($result)){
print
"<div class='item col-xs-4 col-lg-4'>".
"<div class='row'>".
"<div class='col-xs-10'>".
"<p class='list-group-item-text'>".
"<input type='text' class='form-control' id='usr-".$row['id']."'>".
"<button id='button-".$row['id']."' data-id='".$row['id']."' class='btn btn-success btn_calc'>Calculate</button>".
"</div>".
"</div>".
"</div>";
}
$i++;
}
?>
<script type="text/javascript">
$(document).on("click", ".btn_calc", function(){
var id_only = $(this).data('id'); //this gets us the id
//you can log values to the console, then right-click and inspect to see the results:
console.log("id_only = ",id_only);
//this gets the text into a variable
var text = $('#usr-'+id_only).val();
console.log("text = ", text);
//alert(text);
});
</script>
try the following
if(mysqli_num_rows($result)){
$i = 0;
while($row = mysqli_fetch_assoc($result)){
print
"<div class='item col-xs-4 col-lg-4'>".
"<div class='row'>".
"<div class='col-xs-10'>".
"<p class='list-group-item-text'>".
"<input type='text' class='form-control' id='usr_" . $i . "'>".
"<button id='button_" . $i . "' class='btn btn-success'>Calculate</button>".
"</div>".
"</div>".
"</div>";
$i ++;
}
}
You're problem is that you are trying to pass data in STRING FORMAT.
In your script you pass the $row out of while loop so it doesn't pass anything useful for you. If you have more than one button you can't use ID ATTRIBUTE but you have to use CLASS. Set a data-id attribute so you can pass the value from the database and set an ID to the input so you can take its value also. Try this:
<?php
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_assoc($result)){
print
"<div class='item col-xs`-4 col-lg-4'>".
"<div class='row'>".
"<div class='col-xs-10'>".
"<p class='list-group-item-text'>".
"<input type='text' class='form-control' id='input-" . $row["id"] . "'>".
"<button data-id='". $row["id"] . "' class='mybutton btn btn-success'>Calculate</button>".
"</div>".
"</div>".
"</div>";
}
}
?>
<script type="text/javascript">
$(document).ready(function(){
$(".mybutton").on("click", function(){
var myid = $(this).attr('data-id');
var myinput = $('#input-'+myid).val();
alert("MY ID IS: " + myid);
alert("MY INPUT VALUE IS: " + myinput);
});
});
</script>
I have an ajax autocomplete where it returns the full name of the user. However, when there are instances where some names or values are the same, it doesn't return the correct value. Rather, it returns the first value in the dropdown. Even if it has 4 same occurences, it still returns the first value.
When I click Stannis Arryn Baratheon, it returns Stannis Targaryen Baratheon.
Here is my php code (sql/php code; ad.php):
<?php
include('config.php');
if($_POST)
{
if($_POST['search_keyword'])
{
$similar = mysql_real_escape_string($_POST['search_keyword']);
$result=mysqli_query($conn, "SELECT * FROM person WHERE (firstName like '" . $_POST["search_keyword"] . "%' OR lastName like '" . $_POST["search_keyword"] . "%') AND residentOrNot = 'Yes' ");
if (mysqli_num_rows($result) > 0) {
while($row=mysqli_fetch_array($result))
{
//$name = $row['fullname'];
//$copiedname = $row['fullname'];
//$b_name= '<strong>'.$similar.'</strong>';
//$final_name = str_ireplace($similar, $b_name, $name);
?>
<div class="show" align="left">
<span class="returnName"><?php echo $row["firstName"].' '.$row["middleName"].' '.$row["lastName"]; ?></span>
<span class="returnID" style="display:none"><?php echo $row['idPerson'];?></span>
</div>
<?php
}
}
else {
?>
<div class="show" align="left">
<span class="returnMessage">No matching records found.</span>
</div>
<?php
}
}
mysqli_close($conn);
}
?>
HTML input form:
<form method="post" action="try.php" name="try">
<div class='web'>
<input type="text" class="search_keyword" id="search_keyword_id" placeholder="Search" />
<input type="hidden" name="resID" id="resID"/>
<div id="result"></div>
<input type="submit" name="try" value="Submit">
</div>
AJAX/JS/JQUERY CODE (i think this is where the problem occurs):
<script type="text/javascript">
$(function(){
$(".search_keyword").keyup(function()
{
var search_keyword_value = $(this).val();
var dataString = 'search_keyword='+ search_keyword_value;
if(search_keyword_value!='')
{
$.ajax({
type: "POST",
url: "ad.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}
return false;
});
jQuery("#result").on("click", function(e)
{
/*var $clicked = $(e.target);
var $name = $clicked.find('.returnName').html();
var decoded = $("<div/>").html($name).text();
$('#search_keyword_id').val(decoded);
var $clicked = $(e.target);
var $id = $clicked.find('.returnID').html();
var id = $("<div/>").html($id).text();
$('#resID').val(id);
*/
$name = $('span.returnName',this).html();
$name = $("<div/>").html($name).text().toString();
$('#search_keyword_id').val($name);
$id = $('span.returnID',this).html();
$id = $("<div/>").html($id).text().toString();
$('#resID').val($id);
});
jQuery(document).on("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search_keyword")){
jQuery("#result").hide();
}
});
});
</script>
It really returns the first value even if I click the second or third or fourth value. Where did I go wrong in my code? Please help me. Thank you so much!
Your code is currently collecting all elements with class returnName in #result, and by calling .html() on that collection jQuery will only return the html of the first element found. The same goes for the your returnID search. This is why you are only getting the first returned entry.
Modify your #result click handler to only trigger for elements with class show, since that is the element that will contain your data.
jQuery("#result").on("click", ".show", function(e){
Then all you have to do is search for the elements with class returnName and returnID and call .text().
var showName = $('.returnName',this).text();
var showId = $('.returnID',this).text();
$('#search_keyword_id').val(showName);
$('#resID').val(showId);
So all together
jQuery("#result").on("click", ".show", function(e){
var showName = $('.returnName',this).text();
var showId = $('.returnID',this).text();
$('#search_keyword_id').val(showName);
$('#resID').val(showId);
});
Though note there are probably better ways of returning your data, and utilizing it rather than transporting it in html elements. For example use data-* attributes instead of using a separate span element to contain your id.
Another option is to use jQuery-UI's autocomplete that does most of the client side work for you and just return the raw data in JSON format from your php script.
In your php code, change this:
<div class="show" align="left">
<span class="returnName"><?php echo $row["firstName"].' '.$row["middleName"].' '.$row["lastName"]; ?></span>
<span class="returnID" style="display:none"><?php echo $row['idPerson'];?></span>
</div>
With this:
<div class="show" align="left">
<span class="returnName" data-id="<?php echo $row['idPerson'];?>"><?php echo $row["firstName"].' '.$row["middleName"].' '.$row["lastName"]; ?></span>
</div>
And your new jquery function:
jQuery("#result").on("click","'.returnName" function(e)
{
var choosenName = $(this).html();
var choosenId = $(this).data('id');
$('#search_keyword_id').val(choosenName );
$('#resID').val(choosenId );
});
I am a newbie in Jquery. I have a table in my webpage which shows the contents of a user table from the database.I have also created an edit button and Delete button for each row of data.I need the id of each edit and delete button for writing code for editing and deleting the records in the database as well as implementing this changes in the table in the webpage also.
$query = mysqli_query($con,"SELECT * FROM user_details");
while($row = mysqli_fetch_array($query))
{
echo "<tr>";
echo "<td>".$row['fname']."</td>";
echo "<td>".$row['mname']."</td>";
echo "<td>".$row['childname']."</td>";
echo "<td><input type='button' id = 'edit".$row['Id']."' value='Edit'></td>";
echo "<td><input type='button' id = 'delete".$row['Id']."' value='Delete'></td>";
echo "</tr>";
}
If I am using Jquery,how to get the IDof each button?Or If I write a onclick event using javascript for each button and passes the ID's as arguments,can I access via Jquery.Please help me
$("button").each(function(index, item) {
var itemId = $(item).attr('id');
});
But I would set the $row['id'] into a data-id attribute and then use:
$("button").each(function(index, item) {
var itemId = $(item).data('id');
});
Add common class name and use that as a selector to get id of the buttons like below
Try like this
$(document).on('click','.edit_btn',function(){
alert($(this).attr('id'));
});
$(document).on('click','.del_btn',function(){
alert($(this).attr('id'));
});
HTML
<input type='button' id ='edit' class="edit_btn" value='Edit'>
<input type='button' id ='delete' class="del_btn" value='Delete'>
DEMO
First of all, you need to escape your variables in HTML context using htmlspecialchars(). Second, you can use data attributes to easily identify the record that needs be edited or deleted.
?>
<tr>
<td><?= htmlspecialchars($row['fname'], ENT_QUOTES, 'UTF-8') ?></td>
<td><?= htmlspecialchars($row['mname'], ENT_QUOTES, 'UTF-8') ?></td>
<td><?= htmlspecialchars($row['childname'], ENT_QUOTES, 'UTF-8') ?></td>
<td><input type="button" class="edit" data-id="<?= $row['Id'] ?>" value="Edit"></td>
<td><input type="button" class="delete" data-id="<?= $row['Id'] ?>" value="Delete"></td>
</tr>
<?php
Then, you can use classes to identify the buttons instead:
$('.edit').on('click', function() {
var id = $(this).data('id');
// edit stuff
});
$('.delete').on('click', function() {
var id = $(this).data('id');
// delete stuff
});
You can use a data-* attribute to specify the ID and use a common class to call the click handler
echo "<td><input type='button' id = 'edit".$row['Id']."' data-id='".$row['Id']."' value='Edit' class='edit-record'></td>";
then in jQuery
jQuery(function ($) {
$(document).on('click', '.edit-record', function () {
//this is called when the edit button is clicked
var $this = $(this),
id = $this.data('id');
//now id has the value of current record's id
})
})
Use Attribute starts with selector, and Event Delegation
$(document).on("click" , "[id^='edit']" ,function() {
console.log(this.id);
});
$(document).on("click" , "[id^='delete']" , function() {
console.log(this.id);
});