I have a javascript that creates a modal popup with jquery-confirm. It works on a single instance, but when there are multiple instances with the same onClick events classname they all trigger at once. The idea is a list of videos to delete with a confirmation button.
How can I have one script address dynamic list with unique class names? [i.e] class="video1" class="video2" or using ID or something else so that the confirmation code only triggers uniquely?
PHP and HTML (for example this could generate ten of the HTML line below):
$stuff = mysql_query(
"SELECT * FROM videolist where user_id = '$id' ORDER BY creation_date DESC"
);
while ($ratch = mysql_fetch_array($stuff)) {
$video_id= $ratch["id"];
$title= $ratch["title"];
?>
<a class="delete" href="delete.php?d=<? echo $video_id; ?>">
DELETE VIDEO!
</a>
<? } ?>
JAVASCRIPT:
$('a.delete').confirm({
buttons: {
confirm: function () {location.href = this.$target.attr('href');},
close: function () {}
}
});
First: I would put an id-attribute in the a-tags
<a class="delete" id="v1"></a>
<a class="delete" id="v2"></a>
<a class="delete" id="v3"></a>
Second: I would make an on click this id event
$('.delete').click({
alert($(this).attr("id"));
});
Third: send the id to the delete-script
Related
My HTML Code
<li class="nav-item px-2 py-2 dropdown" id="applicant_list">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Applicant List
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<?php
$db = new PDO("mysql:dbname=db_project; host = localhost", "root", "");
$find_mName = "SELECT mName
FROM `member`
INNER JOIN apply_chatroom
ON member.mId = apply_chatroom.mId
WHERE cId = '".$_GET['cId']."'";
$mName = $db->query($find_mName);
foreach ($mName as $mNames)
{?>
<li><a class="dropdown-item" id="apply_list" role="button"><?php echo $mNames['mName']; ?></a></li>
<?php } ?>
</ul>
</li>
My JS Code
<script>
$(document).ready(function(){
$('#apply_list').click(function(){
// I want to access the text inside anchor tag here, and assign it to a php variable
});
});
</script>
What I want to do is when clicking the button, I can get the text inside the anchor tag($mNames['mName']) in my JS code. Then assign it to a php variable, because I will also use php code to do some SQL query inside the JS code.
I assume you want to create a PHP array with your PDO query, loop through it to use the array values for list items in your HTML code and for javascript click events.
In the example beneath the array elements of $mName are written in the id and value tag of the list elements. The id tag must be unique to be called from javascript. That's why I added the counter of the loop there which is removed in the javascript function afterwards.
In your code snippet the where clause of your PDO query is just as unclear as the expression $mNames['mName']. That's why I left them out. If you should use the where clause use prepared statemants in your PDO query due to security reasons:
PHP code:
<?php
...
// PDP query to create an array $mName
$find_mName = "SELECT mName
FROM `member`
INNER JOIN apply_chatroom
ON member.mId = apply_chatroom.mId";
$stmt = $db->prepare($find_mName);
$stmt->execute();
$mName = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
$stmt = null;
// loop through to get all array values of $mName
for($x=0;$x<count( $mName);$x++)
{
// write array element in string
$nm = $mName[$x];
// write array values in id and value tag of li elements
?>
<li><a class="dropdown-item" id="<?php echo $nm."-".$x; ?>" onClick="getPHPValue(this.id)" role="button"><?php echo $nm; ?></a></li>
<?php } ?>
...
Javascript code:
<script>
function getPHPValue(id)
{
const myArray = id.split("-");
let phpPart = myArray[0];
alert(phpPart);
}
</script>
I am trying to build a simple 'blog' that myself or a moderator can remove by calling a delete function. However, I only want the delete button to show for administrators. I created a function to validate the user, that is working fine. However, I am not familiar enough with Javascript to know whether to use window.onload or onopen or onchange, or how to attach the function to my Foreach loop to run for each blog post I have. When I have 10 blog posts, it only shows for the first (or last) post.
I have tried adding the "onload / onopen / onchange" commands to the body, to the foreach loop, and to my tags to see if it responds differently.
<script>
function ShowDelete()
{
var x = document.getElementById("Delete");
if (userid === "1") {
x.style.display="block";
}
else {
x.style.display="none";
}
}
window.onload = ShowDelete;
</script>
<?php foreach ($entries as $entry) : ?>
<?php if ($userid == 1) { ?>
<input type="submit" id="btnDelete" value="Delete Post" />
<?php } ?>
<?php endforeach; ?>
Ok Thank you all so much for the responses, I simply input the decision statement inside the loop to determine whether to show or skip. Thanks a ton!!!
You are creating an HTML input and then hiding it. Best practice is not to create the element in the first place based on your userid.
<?php foreach ($entries as $entry) : ?>
/* Check for userid here and create delete element if condition is met */
<?php endforeach; ?>
No need to call a function multiple times to set the style. In your onload event, capture all of the <input/> elements by class name and set your display style. Note that the id attribute must be unique, so the class attribute should be used instead of id.
const userid = "0";
window.addEventListener('DOMContentLoaded', () => {
let inputs = document.getElementsByClassName("Delete");
Array.from(inputs).forEach(input => {
input.style.display = userid === "1" ? "block" : "none";
});
});
<input type="submit" class="Delete" value="Delete Post" />
<input type="submit" class="Delete" value="Delete Post" />
<input type="submit" class="Delete" value="Delete Post" />
It may also be of benefit to take a look at this post regarding load listeners.
I am printing some data using php on my webpage and giving "Edit" and "Delete" option next to it.
Now I have added a javascript confirmation page next to it using onclick.
Now when the user presses "OK" button, it executes the query as expected. But even when the user presses Cancel button, it still executes the query and deletes data.
if($total!=0)
{
while($result = mysqli_fetch_assoc($data)){
echo"<table><tr>
<td>".$result['address']."</td>
<td>".$result['telephone']."</td>
<td>".$result['phone']."</td>
<td>".$result['email']."</td>
<td><a href='contact_edit.php?id=$result[id]&address=$result[address]&telephone=$result[telephone]&phone=$result[phone]&email=$result[email]'>EDIT</td>
<td><a href='contact_delete.php?id=$result[id]' onclick='checkdelete()'>DELETE</a></td>
</tr></table>";
}
}
The javascript code:
<script>
function checkdelete()
{
confirm('ARE YOU SURE YOU WANNA DELETE?');
}
</script>
Should I wrap it in an if-else statement?
in php:
echo "...
...
<td>
<a href='#' onclick='checkdelete(\"contact_delete.php?id=".$result[id]."\")'>
DELETE
</a>
</td>
... ";
in js:
<script>
function checkdelete(url)
{
if( confirm('ARE YOU SURE YOU WANNA DELETE?') ){
window.location.replace(url);
}
}
</script>
I'm using JQuery to provide my users with a re-arrangeable list of items. Like this:
Image of List
Here's the simple HTML:
<ul class="sortable">
<li>Item 1<i class="sorthandle"></i></li>
<li>Item 2<i class="sorthandle"></i></li>
</ul>
The drag-and-drop feature works great. The next step is saving the user's sort preference to the database. I plan to add a "priority" column to my database, which will hold an integer representing the user's preferred sort order. My query will then Order by 'priority' ASC.
I'm thinking I need to generate an array of the sort order currently displayed on the drag-and-drop screen, then save those values to the database records. But as a JavaScript newbie, I need some help.
My JavaScript
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
$(".sortable").sortable({
connectWith: ".sortable",
handle: '.handle'
}).disableSelection();
});
</script>
Generating the drag-and-drop list via PHP:
while ($row = mysqli_fetch_array($result)){
$playlistname = $row['name'];
$id = $row['id'];
echo "<li>$playlistname<i class='handle fa fa-bars'></i></li>";
}
First of all, JavaScript will need the IDs, not just the name. You can simply put them in a data attribute (I also got rid of the unnecessary variable assignments and built the string with concatenation)
echo '<li data-id="' . $row['id'] . '">' . $row['name'] . '<i class="handle fa fa-bars"></i></li>';
You can then extract this data attribute in JavaScript and create an array. You might want to think about when you save the settings. The easiest way would be to provide a button. You could also do it on the sortable update event (e.g. after "dropping" the element). But that is risky and might overload your server.
To trigger an AJAX POST on button click, put this code within $(function() {. It binds a lambda function on the click event of the DOM element with the ID save, f.ex. <button id="save">save order</button>
// bind a callback to the button click
$('#save').on('click', function () {
// array where we store the IDs
var ids = [];
// loop through the <li> and extract data-id
$('.sortable li').each(function() {
ids.push($(this).data('id'));
});
// AJAX POST the array to a PHP script
$.post('/savescript.php', {'ids[]': ids});
});
you can then access the data in $_POST['ids'].
I was able to accomplish this without writing any more JavaScript. PHP worked just fine!
PHP - Getting Values
<?php
$sql = "SELECT name, id FROM playlists WHERE userid = 'XX' AND active = 1 ORDER BY priority ASC";
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$result = mysqli_query($conn,$sql);
?>
<form action="" method="POST">
<div class="container">
<ul class="sortable">
<?php
while ($row = mysqli_fetch_array($result)){ /* FETCH ARRAY */
$playlistname = $row['name'];
$id = $row['id'];
echo "<li>$playlistname<i class='handle fa fa-bars'><input type='hidden' name='sort[]' value='$id' /></i></li>";
}
?>
</ul>
</div>
<center><button name="submit" id="sortsavebutton" type="SUBMIT" value="submit" action="POST">Save</button></center><br>
</form>
Processing on Save/Submission
if (isset($_POST['submit'])){
$rearrange = $_POST['sort'];
$count = count($rearrange);
$sort = 0;
for($i=0;$i<$count;$i++){
if(!empty($rearrange[$i])){
$id = mysqli_real_escape_string($conn,$rearrange[$i]); /* ESCAPE STRINGS */
$priority = $sort++;
$stmt = $conn->prepare("UPDATE playlists SET priority=? WHERE id = ?");
$stmt->bind_param("ii", $priority, $id);
$stmt->execute();
}
}
}
I've got a table that lists values inputted by a user, with 2 buttons on the side to remove or to mark completed. On the page the table is visable, there are 3 tabs, we will call these Tab1, Tab2, and Tab3
Each tab has a table (As described above) with information about a specific type of entry.
These buttons are simple <a href> links, so when clicked they reload the page. This is a problem because the users view is refreshed and it takes the tabs back to the default tab, and is also an inconvenience when trying to mark several entries.
I would like to make these buttons send Ajax requests to another page to process the data. The only problem is, I am not really sure how to make the ajax call.
This is what I have right now
My buttons
echo "<td class='td-actions'>";
echo " <a href='?complete=".$row['uniqueID']."' class='btn btn-success btn-small'>
<i class='btn-fa fa-only fa fa-check'> </i>
</a>
<a href='?remove=".$row['uniqueID']."' class='btn btn-danger btn-small'>
<i class='btn-fa fa-only fa fa-remove'> </i>
</a>";
echo "</td>";
There is one called Complete, and one called Remove.
When either of these are pressed, it currently reloads the page which triggers a few php if statements.
if(isSet($_GET['remove'])) {
$sql = "DELETE from rl_logged where uniqueID='".$_GET['remove']."';";
$ret = $db->exec($sql);
echo "<meta http-equiv='refresh' content='0;index.php' />";
}
if(isSet($_GET['complete'])) {
$sql = "UPDATE rl_logged set complete=1 where uniqueID='".$_GET['complete']."';";
$ret = $db->exec($sql);
echo "<meta http-equiv='refresh' content='0;index.php' />";
}
These are relatively simple functions. My problem is that I do not know javascript very well.
Any help would be much appreciated.
the javascript that I have come up with is this
$(document).ready(function() {
$('#markComplete').click(function() {
var input = input = $(this).text()
$.ajax({ // create an AJAX call...
data: {
onionID: input,
},
type: 'POST', // GET or POST from the form
url: 'pages/ajax/markCompleteRL.php', // the file to call from the form
success: function(response) { // on success..
refreshAllTabsWithFade();
}
});
});
});
using this button
<div name='markComplete' id='markComplete' class='btn btn-success btn-small'>
<i class='btn-fa fa-only fa fa-check'></i>".$row['uniqueID']."
</div>
But, while inspecting with firebug, this seemed to work ONCE, but now the button doesn't do anything.
I tried again this morning, the button presses and the first time it sends this post, then the button doesn't do it again - even on page reload.
I was able to get it to work with the following:
javascript:
$('.markComplete').submit( function( event ) {
event.preventDefault();
event.stopImmediatePropagation();
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // serialize the form
type: "POST", // GET or POST from the form
url: "pages/ajax/repairlogMarks.php", // the file to call from the form
success: function(response) { // on success..
refreshAllTabs();
}
});
return false;
});
button:
<form class="markComplete">
<input type="text" style="display:none;" class="form-control" name="uniqueid" value='<?=$row['uniqueID'];?>'>
<input type="text" style="display:none;" class="form-control" name="markcomp" value='1'>
<button type="submit" class="btn btn-success">
<i class="btn-fa fa-only fa fa-check"></i>
</button>
</form>
Basically, I made the button into a form which I knew how to create an ajax request for.
--
Update to make it work for multiple buttons that do the same function for different unique ID's.
Well for since you're sending the ajax call using "POST", it seems to me that if(isSet($_GET['complete'])) would evaluate to false. Also if your button is generated dynamically using php then change your click handler to the following:
$('document').on('click', '#markComplete', function (){
// Your code here
})
If you have more than one "Mark Complete" button; you need to use classes rather than ID to bind the event.
<button id="test">
Test 1
</button>
<button id="test">
Test 2
</button>
<script>
$('#test').click(function (e) {
console.log('test', e.target);
});
</script>
In this example, only the first button works. jQuery will only return the first element when you specify an ID.
If you use classes to bind the event; both buttons will work:
<button class="test">
Test 1
</button>
<button class="test">
Test 2
</button>
<script>
$('.test').click(function (e) {
console.log('test', e.target);
});
</script>
i think you have an error in your javascript at this line...
var input = input = $(this).text()
try to replace by this..
var input = $(this).text();