How to pass values in a modal popup using jQuery - php

In a table I display several links whose value (user id) is extracted from a database. By clicking on the link appears a modal pop up in which I would like to pass the selected value.
Here is the table:
<table>
<tr>
<td>Username</td>
<td>Id</td>
</tr>
<?php
include ‘db_connection.php’;
$sql = "SELECT * FROM users";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
?>
<tr>
<td><?php echo $row[userID]?></td>
<td>
<div id='basic-modal'>
<a href="?id=<?php echo $row[userID]?>" class='basic'>Show</a>
</div>
</td>
</tr>
<?php } ?>
</table>
If I click on the link Show appears the modal pop up:
<div id="basic-modal-content">
<?php
if(isset($_GET[‘userID’])){
$userID = $_GET[‘userID’];
echo ‘UsuerID: ‘ .$userID;
}
?>
</div>
This is the script I used
jQuery(function ($) {
$('#basic-modal .basic').click(function (e) {
$('#basic-modal-content').modal();
return false;
});
});
Since I have little familiarity with the jQuery framework I would like to ask you how can I pass the selected value within the modal and then use it.

jquery allows you to use the .data() attribute
<div id='basic-modal'>
<a href="?id=<?php echo $row[userID]?>" data-mydata="<?php echo $row[userID]?>" class='basic'>Show</a>
</div>
and then u can retrieve data from 'data-mydata' attribute:
jQuery(function ($) {
$('#basic-modal .basic').click(function (e) {
$('#basic-modal-content')
.text($(this).data('mydata'))
.modal();
return false;
});
});

Related

How do I populate a second table based on the rowID from the first table in a modal on the same page?

I have two tables in a SQLite DB. The second table contains information about the first.
The first table is loaded in a modal table with buttons to a second modal table in which I would like to load information from the second SQlite table based on the rowID from the first.
I have attempted several things but none of them worked, I assume because JS only gets executed when loading the page, but I can't figure out a way to work around this.
I left comments about the things I tried in the code.
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<button type="button" class="btn btn-info" data-toggle="modal" data-target="#modal1">View</button>
<!-- begin modal1 -->
<div class="modal" id="modal1">
<div class="modal-dialog">
<div class="modal-content">
<table class="table table-bordered table-striped">
<thead>
<tr class="btn-primary">
<th>id.</th>
<th>text1</th>
</tr>
</thead>
<tbody>
<?php
$db = new PDO('sqlite:db.sqlite'); // I know this is unsafe, but it works and it's for a local page.
$qry1 = $db->prepare("SELECT * FROM table1");
$qry1->execute();
$i = 1;
while ($row = $qry1->fetch(PDO::FETCH_ASSOC)) {
$Query1ID[$i] = $row['id']; //If I know what row I'm selecting I could use it to find the correct variable in the next query, but I can only find this with JS and don't know how to combine these.
?>
<tr>
<td onclick="clicked(<?php echo $i; ?>)"><button type="button" class="btn btn-primary mybutton" data-toggle="modal" data-target="#modal2" data-row-val="<?php echo $row['id']; ?>"><?php echo $row['id']; ?></button></td>
<!-- with onclick I can find out what row I clicked and in combination with $Query1ID[$i] I should be able to get the correct variable in the new query. But I don't know how to combine them. -->
<td><?php echo $row['table1_text']; ?></td>
<?php
$i++;
}
?>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- end modal1 -->
<!-- begin modal2 -->
<div class="modal" id="modal2">
<div class="modal-dialog">
<div class="modal-content">
<table class="table table-bordered table-striped">
<thead>
<tr class="btn-primary">
<th>id.</th>
<th>Entries for <span id="rowvarfromJS">empty</span></th> <!-- I can call the variable but can not use it in the query. -->
</tr>
</thead>
<tbody>
<?php
$db = new PDO('sqlite:db.sqlite');
//function if clicked = 3 newID = $Query1ID[3] //something like this would solve my problem
$newID="$Query1ID[10]";
echo $newID;
echo "<script>var javascriptVar = '199';</script>";
echo "<script>if (nr == 2){alert('execute php?')}</script>";
$phpVar = "<script>document.writeln(javascriptVar);</script>";
echo "phpvar=$phpVar";
//$qry2 = $db->prepare("SELECT * FROM table2 WHERE fortable1ID = $newID"); //This works, if only I could use the JS var from the clicked function to find the correct variable.
//$qry2 = $db->prepare("SELECT * FROM table2 WHERE fortable1ID = $phpVar"); //This does not work even though $phphvar contains the correct value.
$qry2 = $db->prepare("SELECT * FROM table2 WHERE fortable1ID = '199'");
// I need this static 199 to be $row['id']; from the previous query.
// I have attempted using rowvarfromJS for that but that doesn't work.
// I can use AJAX and complete the query on another page, but I do not know how to use JS reply to generate a new table.
$qry2->execute();
$i2 = 1;
while ($row = $qry2->fetch(PDO::FETCH_ASSOC)) {
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['table2text']; ?></td>
<td><?php echo "$Query1ID[4]"; ?></td> <!-- I can use this variable in a query, but I do not know how to select the correct one.-->
</tr>
<?php
$i2++;
}
?>
</tbody>
</table>
</div>
</div>
</div>
<!-- end modal2 -->
<!-- javascript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
//This was an attempt to get the rowID with JS. It works, but I can't use the variable in the query.
$(function () {
$(".mybutton").click(function () {
var my_row_value = $(this).attr('data-row-val');
$("#modal2").attr('data-row-value',my_row_value );
alert('My Row Value '+my_row_value ); //If I could only use this value in the query.
let rowvarfromJS = my_row_value;
document.getElementById("rowvarfromJS").innerHTML = rowvarfromJS;
})
});
//Gets clicked row number. If I know the clicked row number then I should be able to find the correct php variable for the next query, but I don't know how to do this.
function clicked (nr) {
let rcfromJS = nr;
console.log('Clicked from row: ' + rcfromJS);
}
//I have also attempted using AJAX to pass the JS variable to another PHP and get the result back, which works, but the result is in JS and I don't know how to create a table from that.
</script>
</body>
</html>
Most attempts are written as comments in the code. Aside from those I also tried using Ajax, but the problem with that is that I am using a JS variable to get a JS variable and I don't know how to use that to populate the modal table.
var data = {
'var1': "199",
'var2': "test."
};
$.ajax({
type: 'post',
url: 'executesecondquery.php',
data: data,
timeout: 50000
}).done(function(response) {
console.log(response); //can I use this response to populate the second table?
}).fail(function(error) {
// uh-oh.
});
executesecondquery.php
<?php
$db = new PDO('sqlite:db.sqlite');
$qry2 = $db->prepare("SELECT table2text FROM table2 WHERE fortable1ID = '$var1'");
$qry2->execute();
$i2 = 1;
while ($row = $qry2->fetch(PDO::FETCH_ASSOC)) {
echo $row['table2text'];
$i2++;
}
?>

Modal inside a loop

I'm new to php and I have this problem.
First I did display the inputed message using select and while loop in table. Then I want a functionality that can reply by getting the name or id of the selected row by clicking a button that shows a modal.
The problem is only the first row are showing the modal. The rest of the rows aren't displayed. I've already searched for the answers and found out that modal is using the same id to display.
I'm still a student and sorry for the messy codes.
`
INBOX
while (($row = mysqli_fetch_array($query))) {
$idd = $row['id'];
$content = $row['content'];
$content_msg = $row['content_msg'];
$to_msg = $row['to_msg'];
$date_created = $row['date_created'];
$from_msg = $row['from_msg'];
$query1 = mysqli_query($db, "SELECT profile_pic FROM users WHERE
first_name = '$from_msg' ")
or die (mysqli_error($db));
while ($rows = mysqli_fetch_array($query1)) {
$pic = $rows['profile_pic'];
echo "
<table id = 'tbl_inbox' border = '0'>
<tr>
<td rowspan = '9' width = '90px'>
<center> <img src = '$pic' width = '80px' height = '80px' id =
'inbox_pic'> </center>
</td>
<td class = 'td_name' colspan = '4'>
<b>$from_msg</b>
</td>
<td id = 'td_date'>
<b>$date_created</b>
</td>
</tr>
<tr>
<td rowspan = '3' colspan = '5' id = 'td_msg'>
$content_msg
</td>
</tr>
<tr>
</tr>
<tr>
</tr>
<tr>
<!-- This is the looped button
<td colspan = '5' id = 'td_action'> <button id ='reply$idd' name =
'btn' value = 'reply$idd'> $idd </button> </td>
</tr>
</table>
";
//
?>
<div id="myModal<?php echo $idd; ?>" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>This is modal ID <?php echo $idd; ?></h2>
</div>
<div class="modal-body">
<p>Some text in the Modal Body</p>
<p>Some other text...</p>
</div>
<div class="modal-footer">
<h3>Modal Footer</h3>
</div>
</div>
</div>
<script>
// Get the modal
var modal<?php echo $idd; ?> = document.getElementById('myModal<?
php echo $idd; ?>');
// Get the button that opens the modal
var btn<?php echo $idd; ?> = document.getElementById('reply<?php
echo $idd; ?>');
// When the user clicks the button, open the modal
btn<?php echo $idd; ?>.onclick = function() {
modal<?php echo $idd; ?>.style.display = "block";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal<?php echo $idd; ?>) {
modal<?php echo $idd; ?>.style.display = "none";
}
}
</script>
<?php
}}
?>
<script>
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
</script>
`
First things first.. Why are you creating a <table> everytime it runs the while loop?
But I think that the problem that your having is because of the way you try to toggle a Modal..
Every item is having one single Modal Toggle function but it's better to make a generic function like:
function toggleModal(id) {
document.queryselector(`#${id}`).classList.toggle('modal-active');
}
Then make a button like:
<button onclick="() => toggleModal(testModal1)">TEST</button>
To explain what this exactly does:
The only thing you're actually doing is toggling a class with display: unset so that it get's showed. So if it's already inside it's classes it will get removed from it, otherwise it gets added to the classes.
If this is not the case, try looking inside your console (F12) and watch for errors when pressing one of the not working buttons

AJAX: sending xmlhttp request in PHP loop but result is not dynamic

I have a table that is given based on the option selected in a . This table generates list of students based on class selected. I want a dynamic modals popup each time the SMS button on a student row is clicked it is suppose to show the related parent's name dynamically. It's actually doing this but the issue is it is not dynamic one i refresh the page the data for the first student button clicked is what shows as response for every other one. until i refresh again. I select another and it shows thesame for every other student
Though when i used develop tool(network) in browser the xmlrequest was sent sucessfully and the interesting thing is the passed "id" param for the selected student is correct. but it just showing the same one that's selected first in the modal popup after refresh
the code looks like this
`
function smsmodal(id){
var data= {"id" : id};
jQuery.ajax({
url : '/sms/include/smsmodal.php',
method : "post",
data : data,
success: function(data){
jQuery('body').append(data);
jQuery('#sms-modal').modal('toggle');
},
error: function(){
alert("Something went wrong")
}
});
}
`
And for the loop:
<?php
require_once '../../service/mysqlcon.php';
$parentID = $_POST['parentID'];
$selected = sanitize($_POST['selected']);
$studentquery = $conn->query("SELECT * FROM students WHERE class = '$parentID' ORDER BY lastname");
$count = mysqli_num_rows($studentquery);
$i = 1;
ob_start(); ?>
<?php
if($count < 1){
?>
<br><br>
<h4 class="text-warning text-center bg-warning" style="padding:20px">No student has been registered in this class.</h4>
<?php
}else{
?> ...... other html..
<div class="table-responsive">
<table class="table table-hover">
<thead><th><input type="checkbox"> Roll</th><th>Photo</th><th>Student Name</th><th>Address</th><th>Actions</th></thead>
<tbody>
<?php while($s = mysqli_fetch_assoc($studentquery)) :?>
<tr>
<td><input type="checkbox"> <?=$i;?></td>
<td> <img src="<?=$s['photo'];?>" alt="photo" class="img-responsive" id="photo"></td>
<td><?php echo $s['lastname'].' '.$s['firstname'];?></td>
<td><?=$s['address'];?></td>
<td><button class="btn btn-success btn-xs" type="button" onclick="smsmodal(<?=$s['id']; ?>)" style="width:80px"><span class="fa fa-mobile"></span> SMS</button> </td>
</tr>
<?php $i++;?>
<?php endwhile; ?>
</tbody>
</table>
</div>
<?php } ?>
<?php echo ob_get_clean(); ?>

Open only div what i want(jquery)

Title is maybe misleading, but i try you explain it.
My table of users
and When i click on the cross I want open only div with id for example as # in table(id=1, id=2...)
So here is my php code:
$select = "SELECT ... from ...";
$data = mysqli_query($connect, $select);
$count = 0;
echo "<table>
<tr>
<th>#</th>
<th>Name</th>
</tr>";
while ($query = mysqli_fetch_array($data)) {
$counter++;
echo "<tr>
<th>{$counter}</th>
<td>{$query["name"]}</td>
<td><a href='xxx.php?id={$query["id"]}'><i class='ion-edit'></i></a><i class='ion-close-round'></i>
<div class='modal'> //modal have of course display none!
<div class='mContent'>
<div class='mHeader'>
<h2>Modal Header</h2>
</div>
<div class='mMiddle'>
<a href='xxx.php?id={$query['id']}'>delete</a>
</div>
<div class='modal-footer'>
<h3>Modal Footer</h3>
</div>
</div>
</div></td></tr>";
}
echo "</table>\n";
Jquery:
$('.ion-close-round').on('click', function () {
$('.modal').css("display", "block");
});
this script "open" every modal of course, but i want open only modal with given id
Thanks for your help all
You can use $.next() to target the .modal that comes after .ion-close-round
$('.ion-close-round').on('click', function () {
$(this).next('.modal').css("display", "block");
});
The selector . is a class selector.
You want to use the ID selector which is #
The ID selector is stricter as only one element on an HTML page can have a given ID, so your ID is 'modal', it would only work on the first element with the ID of modal.

form hidden value not working?

I have a simple table that prints our the list of videos and plays them when you click on the row. I have a delete button to delete the corresponding video in the row. But for some reason when you click on any video it will only delete the last one in the list. I can look at the source on the page and the video_url seems to be correct. Any ideas?
Here is the majority of the code:
<?php
// Dont allow direct linking
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
//get current user
$user =& JFactory::getUser();
// get a reference to the database
$db = &JFactory::getDBO();
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
echo $problem;
}
return $data;
}
if (isset($_POST['delete_video'])) {
$video_url = check_input($_POST['video_url']); //value here is always just the last row in the table!!!
echo $video_url;
$query_delete_video = "DELETE FROM `#__videos` WHERE `video_url`='$video_url'";
$db->setQuery($query_delete_video);
$db->query();
}
//list all details of the camera including camera_name
$query_videos = "SELECT #__videos.video_url, #__videos.video_size, #__videos.video_datetime, #__videos.video_length, #__cameras.camera_name
FROM #__videos INNER JOIN #__cameras using (user_id, camera_id)
WHERE #__videos.user_id=".$user->id." ORDER BY #__videos.video_datetime DESC";
$db->setQuery($query_videos);
//get number of cameras so we can build the table accordingly
$db->query();
$num_videos = $db->getNumRows();
// We can use array names with loadAssocList.
$result_videos = $db->loadAssocList();
echo "<html>";
echo "<head>";
?>
<link href="recordings/recordings.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="flowplayer/example/flowplayer-3.2.6.min.js"> </script>
<?php
echo "</head>";
echo "<body>";
?>
<?php
if (!isset($result_videos))
{
//TODO check if query failed
}
else
{
if ($num_videos == 0)
{
?>
<div id="cc_table">
<table id="webcam-table">
<thead>
<tr>
<th>Camera Name</th>
<th>Camera Details</th>
<th>Video Options</th>
</tr>
</thead>
<td colspan=3><b><i><center>You currently have no videos created. Start monitoring today!</center></i></b></td>
</table>
</div>
<?php
}
else
{
?>
<div id="cc_table">
<form name="myform" action="<?php echo htmlentities($_SERVER['REQUEST_URI']); ?>" method="POST">
<table id="webcam-table">
<thead>
<tr>
<th>Camera Name</th>
<th>Camera Details</th>
<th>Video Options</th>
</tr>
</thead>
<tbody>
<?php
for($i=0;$i<$num_videos;$i++)
{
?>
<tr onclick="DoNav('<?php echo $result_videos[$i]["video_url"]; ?>');">
<td>
<?php echo $result_videos[$i]["camera_name"]; ?>
</td>
<td>
Date Created: <?php echo $result_videos[$i]["video_datetime"]; ?> <br>
Video Size: <?php echo $result_videos[$i]["video_size"]; ?> bytes <br>
Video Length: <?php echo $result_videos[$i]["video_length"]; ?> secs
</td>
<td>
<input type="submit" name="delete_video" value="Delete" onClick="return confirm('Are you sure you want to delete?')"/>
</td>
</tr>
<input type="hidden" name="video_url" value="<?php echo $result_videos[$i]["video_url"]; ?>" />
<?php
}
echo "</tbody>";
echo "</table>";
echo "</form>";
echo "</div>";
}
}
?>
<div id="player" style="display:block;width:320px;height:240px;background-image:url(recordings/landscape.jpg)"></div>
<script type="text/javascript">
function DoNav(theUrl)
{
//document.write(document.location.href = theUrl);
flowplayer("player", "flowplayer/flowplayer-3.2.7.swf", theUrl);
}
</script>
<?php
echo "</body>";
echo "</html>";
?>
Can you post the HTML? I suspect you've got multiple hidden input fields on the page, all with the same name. If that's the case, only the last one that loads on the page will register as a valid hidden input. A better way to do it would be to set a data attribute on the delete button, and then add a JS click event to that delete button. Something like this:
<button class="delete" data-video_url="youtube.com/abcd">Delete ABCD</button>
<button class="delete" data-video_url="vimeo.com/xyz">Delete XYZ</button>
and then when someone clicks on a .delete button, you send the data-video_url value to the PHP script via POST. A jQuery example might look like this:
$('.delete').click(function() {
var url = $(this).data('video_url');
$.post('/delete.php', { video_url: video_url }, function() {
// Do something on success
});
});
Another way to do it is to simply make each button its own form:
<form method="post" action="delete.php">
<input type="hidden" name="video_url" value="url_goes_here">
<button>Delete</button>
</form>
Hope that helps. Good luck.
The problem is that the name of the hidden field is not unique (for every iteration in the loop a new hidden field with the same name is created). How should the script know which row you want if all of them has the same name?
Your code does not seem to name the hidden values properly.
You should use $i to name the variable.
input type="hidden" name="video_url<?php echo $i; ?>"
then in handler you can do
<?php
if ($_POST) {
$kv = array();
foreach ($_POST as $key => $value) {
// check here which one begins with video_url
}
}
?>

Categories