I have a MySQL database of a bible that I query via php. Right now i'm in the testing phase. Below is my test file where I display a specific Chapter of a Book in a modal. The problem is that I have no idea how to essentially 'display the next chapter (or previous chapter)' when a user clicks the left or right arrow buttons on the footer of the modal.
Currently the test file shows "Genesis 12". How can I allow the user to see Genesis 13 (inside the same modal) when the user clicks the right arrow button (at the bottom)?
<!DOCTYPE html>
<html>
<head>
<?php require "config.php"; ?>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link rel='stylesheet' type='text/css' href='http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.1.0/css/font-awesome.min.css'/>
<script>
$(document).ready(function() {
$('.btn').click(function() {
$("#myModal").modal('show');
});
});
</script>
<style>
p, span, div { font-family:"Helvetica Neue",Verdana,Helvetica,Arial,sans-serif;font-size:1.3rem;line-height:1.8;}
.selverse { border-bottom:1px dotted blue;}
</style>
</head>
<body>
<button type='button' class='btn btn-success'>Click</button>
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<?php
$book = "Genesis";
$chapter = "12";
$verse = "5";
$v_under = "<span style='text-decoration:underline;'>";
$v_end = "</span>";
echo "<h4 class='modal-title'>".$book." ".$chapter."</h4>";
echo "</div><div class='modal-body'>";
$result = $db->prepare("SELECT * FROM `asv` WHERE Book = :book AND Chapter = :chapter");
$result->BindParam(':book',$book);
$result->BindParam(':chapter',$chapter);
$result->execute();
$y = 0;
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$bookx = $row['Book'];
$chapterx = $row['Chapter'];
$versex = $row['Verse'];
$versetext=$row["VerseText"];
if ($versex == $verse) {
echo "<span style='color:rgb(57, 128, 57);font-weight:bold;'><sup style='padding-left:0.5em;'>".$versex."</sup></span><span class='selverse' id='v".$versex."'>".$versetext."</span>";
} else {
echo "<span style='color:rgb(57, 128, 57);font-weight:bold;'><sup style='padding-left:0.5em;'>".$versex."</sup></span><span id='v".$versex."'>".$versetext."</span>";
}
}
?>
</div>
<div class="modal-footer" style='text-align:center;'>
<a href='javascript:;'><i style='float:left;margin-left:1em;' class='fa fa-angle-left fa-2x'></i></a>
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
<a href='javascript:;'><i style='float:right;margin-right:1em;' class='fa fa-angle-right fa-2x'></i></a>
</div>
</div>
</div>
</div>
</body>
</html>
.. Any help will be greatly appreciated!!
You should look into AJAX to do something like that properly, what AJAX basically does is load content after the page has finished loading. So you can get rows out of your database without reloading the page. A very basic approach would be:
Change the href of the arrows to call the JavaScript function loadNew();
<div class="modal-footer" style='text-align:center;'>
<a href='javascript:loadNew('previous');'><i style='float:left;margin-left:1em;' class='fa fa-angle-left fa-2x'></i></a>
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
<a href='javascript:loadNew('next');'><i style='float:right;margin-right:1em;' class='fa fa-angle-right fa-2x'></i></a>
</div>
Add the loadNew function to your script tag:
<script>
$(document).ready(function() {
$('.btn').click(function() {
$("#myModal").modal('show');
});
});
function loadNew(type){
//We pass the type (previous or next row) and the current ID of the row as GET variables to the fetch.php script
$.get("http://yoursiteurl.com/fetch.php?type="+type, function(data){
$(".modal-header").html(data);
});
}
</script>
Now all that's left is to create the PHP file (fetch.php), that would be something like:
<?php
session_start();
if(!isset($_SESSION['book'])){
$_SESSION['book'] = "Genesis";
$_SESSION['chapter'] = 12;
$_SESSION['verse'] = 5;
}
if($_GET['type'] == 'next'){
//Select the next verse, you are probably going to want to add a check to see if the chapter is available, if not go to the first chapter or something like that
$_SESSION['chapter'] = $_SESSION['chapter'] + 1;
} else{
$_SESSION['chapter'] = $_SESSION['chapter'] - 1;
}
$book = $_SESSION['book'];
$chapter = $_SESSION['chapter'];
$verse = $_SESSION['verse'];
$v_under = "<span style='text-decoration:underline;'>";
$v_end = "</span>";
echo "<h4 class='modal-title'>".$book." ".$chapter."</h4>";
echo "</div><div class='modal-body'>";
$result = $db->prepare("SELECT * FROM `asv` WHERE Book = :book AND Chapter = :chapter");
$result->BindParam(':book',$book);
$result->BindParam(':chapter',$chapter);
$result->execute();
$y = 0;
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$bookx = $row['Book'];
$chapterx = $row['Chapter'];
$versex = $row['Verse'];
$versetext=$row["VerseText"];
if ($versex == $verse) {
echo "<span style='color:rgb(57, 128, 57);font-weight:bold;'><sup style='padding-left:0.5em;'>".$versex."</sup></span><span class='selverse' id='v".$versex."'>".$versetext."</span>";
} else {
echo "<span style='color:rgb(57, 128, 57);font-weight:bold;'><sup style='padding-left:0.5em;'>".$versex."</sup></span><span id='v".$versex."'>".$versetext."</span>";
}
}
?>
Then save the file and edit the path http://yoursiteurl.com/fetch.php to the correct one.
Related
I need to be able to update my sql table from open to close task.
I already wrote code for this but it is not working properly. On the modal it shows 2 'continue' buttons and right now the task table contains two tasks. Can somebody help me?
This is what the modal looks like:
and this is my code:
<?php
if (isset($_POST["closetask"])) {
$close_task_id = mysqli_real_escape_string($con, $_POST["close_task_id"]);
$sql = "UPDATE task SET task_status='closed' WHERE id_task='$close_task_id'";
$result = mysqli_query($con, $sql);
if ($result) {
$_SESSION['success'] = "Task closed";
$_SESSION['text'] = "Task has been closed successfully";
$_SESSION['icon'] = "success";
} else {
$_SESSION['success'] = "Error";
$_SESSION['text'] = "Unkown error, please try again";
$_SESSION['icon'] = "error";
}
}
?>
<?php
$query = "SELECT * FROM task ORDER BY id_task DESC";
$result = mysqli_query($con, $query);
?>
<!-- reject button -->
<form action="task-view.php" method="post" enctype="multipart/form-data">
<div id="rejectModal" class="modal fade" role="dialog" >
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Close this task?</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<div class="d-flex align-items-center justify-content-center form-group" >
<p class="align-items-center text-center" for="company">This button means closing the task. Are you sure you want to continue?</p>
</div>
</div>
<div class="modal-footer">
<?php
while ($row = mysqli_fetch_array($result)) {
if ($row['task_status'] == 'open'){
$check_task = '
<input type="text" name="close_task_id" class="form-control" value="' . $row["id_task"] . '" hidden>
<button class="btn btn-success" type="submit" name="closetask" class="btn btn-success">Continue</button>
</button>
';
}
echo '
<br>
' . $check_task . '
';
}
?>
</div>
</div>
</div>
</div>
</div>
</form>
<!-- end of reject button-->
<?php
if (isset($_SESSION['success']) && $_SESSION['success'] != '') {
?>
<script>
swal({
title: "<?php echo $_SESSION['success']; ?>",
text: "<?php echo $_SESSION['text']; ?>",
icon: "<?php echo $_SESSION['icon']; ?>",
button: "OK",
});
</script>
<?php
unset($_SESSION['success']);
}
?>
Well, after going through your code snippet,
I could see this query
$query = "SELECT * FROM task ORDER BY id_task DESC";
$result = mysqli_query($con, $query);
meaning this fetches all records in the task table, the two continue buttons you see are coming from the while loop
while ($row = mysqli_fetch_array($result)) {
....
}
it logically implies you have two records or rows in your database task table and all the records where retrieved from the table.
This is my second question on php. I'm trying to query mysql database and show it on my page.
Currently, I'm doing it on php page and the code is as below.
<?php
$host = "localhost";
$dbUserName = "myUserId";
$dbPassword = "MyPwd";
$dbname = "MyDBName";
try
{
$conn = new mysqli($host, $dbUserName, $dbPassword, $dbname);
}
catch(Exception $ex)
{
echo 'Error : ' . $ex->getMessage();
}
$SELECT = "SELECT * FROM OpenPositions";
$result = mysqli_query($conn, $SELECT);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="wrap">
<div class="welcome-two">
<div class="container">
<div class="welcome-detail">
<div class="row">
<div class="col">
<h2>Open <b>one</b></h2>
<div class="tabs">
<?php
while ($row = mysqli_fetch_assoc($result))
{ ?>
<div class="tab">
<input type="radio" id="rd<?php echo $row['JobId']; ?>" name="rd">
<label class="tab-label" for="rd<?php echo $row['JobId']; ?>"><?php echo $row['Title']; ?></label>
<div class="tab-content">
<?php echo $row['JobDescription']; ?><br/>
<p><button id="myBtn">Open Modal</button>
</p>
</div>
</div>
<?php
} ?>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
var accItem = document.getElementsByClassName('accordionItem');
var accHD = document.getElementsByClassName('accordionItemHeading');
for (i = 0; i < accHD.length; i++) {
accHD[i].addEventListener('click', toggleItem, false);
}
function toggleItem() {
var itemClass = this.parentNode.className;
for (i = 0; i < accItem.length; i++) {
accItem[i].className = 'accordionItem close';
}
if (itemClass == 'accordionItem close') {
this.parentNode.className = 'accordionItem open';
}
}
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</body>
</html>
Using this, I'm able to retrieve my data and display it. But, This is working when I save it as php.
Here I've 2 questions.
How can I separate the code and have HTML displaying data and php doing db related tasks?
When I click on the button, how can I pass the id and show it in the modal?
Thanks
You can't really separate all of the php and HTML thing. But you can do something like this:
first create 2 file:
db_connection_function.php
index.php // Yeah, you can't escape from .php file extension.
relocate your database connection and query to file db_connection_function.php
<?php
$host = "localhost";
$dbUserName = "myUserId";
$dbPassword = "MyPwd";
$dbname = "MyDBName";
try
{
$conn = new mysqli($host, $dbUserName, $dbPassword, $dbname);
}
catch(Exception $ex)
{
echo 'Error : ' . $ex->getMessage();
}
$SELECT = "SELECT * FROM OpenPositions";
$result = mysqli_query($conn, $SELECT);
?>
And this content of file index.php
<?php include 'db_connection_function.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="wrap">
<div class="welcome-two">
<div class="container">
<div class="welcome-detail">
<div class="row">
<div class="col">
<h2>Open <b>one</b></h2>
<div class="tabs">
<?php
while ($row = mysqli_fetch_assoc($result))
{ ?>
<div class="tab">
<input type="radio" id="rd<?php echo $row['JobId']; ?>" name="rd">
<label class="tab-label" for="rd<?php echo $row['JobId']; ?>"><?php echo $row['Title']; ?></label>
<div class="tab-content">
<?php echo $row['JobDescription']; ?><br/>
<p><button id="myBtn">Open Modal</button>
</p>
</div>
</div>
<?php
} ?>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
var accItem = document.getElementsByClassName('accordionItem');
var accHD = document.getElementsByClassName('accordionItemHeading');
for (i = 0; i < accHD.length; i++) {
accHD[i].addEventListener('click', toggleItem, false);
}
function toggleItem() {
var itemClass = this.parentNode.className;
for (i = 0; i < accItem.length; i++) {
accItem[i].className = 'accordionItem close';
}
if (itemClass == 'accordionItem close') {
this.parentNode.className = 'accordionItem open';
}
}
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</body>
</html>
About how to pass id to your modal is like this:
first, put your data 'id' in the attribute of modal button
...
<p><button class="myBtn" data-id="<?php echo $row['JobId']; ?>" data-toggle="modal" data-target="#myModal">Open Modal</button>
...
must change "myBtn" to class, because id can't be used to many data.
And this is for your modal
$(".myBtn").click(function(){
JobId = $(this).data('id')
// put the id into modal
$('div#myModal div.modal-content p').html(JobId)
})
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
i am working on website with buttons each button fire up a bootstrap modal contain data from mysql database i pass a variable from the jquery that fire up the model into a mysql query inside the modal the problam is the php variable cannot get the data send it from the jquery any hints please ?!
i am passing data through jquery post to ajax.php file
the modal code
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<span id="codeElem"></span>
<?php
$resultHead = mysqli_query($con2,"SELECT * FROM coops WHERE Code = $getCode ");// WHERE Code IN ('".$codeArrayStr."')
?>
<?php
$i=0;
$row3 = mysqli_fetch_array($resultHead);
?>
<h4 class="modal-title"><?=$row3['CoopName'];?></h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<?php
$result = mysqli_query($con,"SELECT DISTINCT * FROM reports WHERE host = $getCode GROUP BY host DESC");
?>
<?php
$i=0;
while($row = mysqli_fetch_array($result)) {
?>
<div class="card card-figure has-hoverable">
<figure class="figure">
<img class="img-fluid" src="http://www.iroof.tv/screenshots/<?=$row['screenshot'];?>" alt="Card image cap">
<figcaption class="figure-caption">
<h6 class="figure-title"><?=$row['host'];?></h6>
<p class="text-muted mb-0"> <?=$row['timestamp'];?> </p>
<?php
// Assign JSON encoded string to a PHP variable
$statusJson = $row['status'];
// Decode JSON data into PHP associative array format
$arr = json_decode($statusJson, true);
// Call the function and print all the values
// $result2 = printValues($arr);
echo "<hr>";
echo "<h3> Player </h3>";
// Print a single value
echo "Status: ".$arr["player"]["status"] . "<br>";
echo $arr["player"]["filename"] . "<br>";
echo "<hr>";
echo "<h3> Graphics </h3>";
echo "Display: ".$arr["video"]["display"] . "<br>";
echo "Resolution: ".$arr["video"]["resolution"] . "<br>";
echo "Colors: ".$arr["video"]["colors"] . "<br>";
echo "<hr>";
echo "<h3> System </h3>";
echo "CPU: ".$arr["cpu"] . "<br>";
echo "Ram: ".$arr["ram"] . "<br>";
//echo "Temprature: ".$arr["temperature"] . "<br>";
echo "Fan: ".$arr["fan"] . "<br>";
?>
</figcaption>
</figure>
</div>
<?php $i++;
}
?>
</div>
<!-- Modal footer
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>-->
</div>
the jquery script
<script>
$(document).ready(
function() {
setInterval(function() {
$('.card');
}, 5000); //Delay here = 5 seconds
var gen;
$(".btn").click(function(){
gen = $(this).attr("data-code");
//$.post("ajax.php", {"code": gen},function(data){console.log(data);});
});
$('#myModal').on('shown.bs.modal', function () {
$.post("ajax.php", {"code": gen},function(data){console.log(data);});
//var phpCode = "<? $getCode = $_POST["code"]; ?>";
//$('#codeElem').html(phpCode);
})
});
</script>
ajax.php file
<?php
if(isset($_POST['code']) && isset($_POST['code'])){
//$_SESSION["code"] = $_POST["code"];
$_SESSION['header'] = $_POST['code'];
$getCode = $_POST["code"];
echo $_SESSION['header'];
}
?>
i expect the variable $getCode to get the code from jquery to complete the mysql query inside the modal :
$resultHead = mysqli_query($con2,"SELECT * FROM coops WHERE Code = $getCode");
I dont think its possible to post variables to a modal, I didnt see example like that when I was searching for popup modal login.
guess you need an action page to forvard infos to modal.
This is the solution to post variables:
Change variables to your needs..
$(document).ready(function(){
$("form").submit(function(event){
event.preventDefault();
var post_id =$("#mail-id").val();
var name =$("#mail-name").val();
var email =$("#mail-email").val();
var message =$("#mail-message").val();
var type =$("#mail-type").val();
var captcha_code =$("#captcha_code").val();
var submit =$("#mail-submit").val();
$(".form-message").load("heads/comment.php",{
post_id: post_id,
name: name,
email: email,
message: message,
type: type,
captcha_code: captcha_code,
submit: submit
});
});
});
you probably need some thing like this to show variables in popup
<p class="form-message"></p>
Or you can check Bootstrap modal table :
Here
I'm trying to learn php, mysql and javascript/jquery by building a live bidding system. I want to refresh the value of a bid button and dropdown automatically, but only if the value has changed. I've made a bidbuttons.php that outputs the buttons after querying the db for the current values, and I load and reload the page with this jquery I found elsewhere. I have tried several different methods of refreshing the div, and the best I came up with unfortunately closed the dropdown on the timer. This current version was described as exactly what I need but doesn't seem to work, in fact it logs me out. would prefer the div to refresh and the dropdown to close ONLY if the bidbuttons.php is updated. This is my first post, I hope I did this right.
<div id="bidbuttons"></div>
<script type="text/javascript">
var loadUrl = "includes/bidbuttons.php?id='.$item->id.'";
$("#bidbuttons").load(loadUrl).fadeIn("slow");
var auto_refresh = setInterval(function () {
$.get(loadUrl, function(data) {
if (data.changed) {
$("#bidbuttons").load(loadUrl).fadeIn("slow");
}
});
}, 10000);
</script>
and my bidbuttons.php
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
if (login_check($mysqli) == true) {
$getid = (int)$_GET['id'];
// get current price
$result = $mysqli->query("SELECT ammount, bidder_id FROM bids WHERE ammount=(SELECT MAX(ammount)) && item_id like $getid order by ammount desc");
while($row = $result->fetch_assoc()) {
$bidder_id = $row["bidder_id"];
$current = $row['ammount'];
echo ($mysqli->error);
$result->free();
}
//get item info
$results = $mysqli->query("SELECT * FROM items WHERE id like $getid ");
while($row = $results->fetch_assoc()) {
if (empty ($current)) { $current = $row["start"];}
$title = $row["title"];
$item->thenext = ($current + $row["raise"]);
$buyout = $row["buyout"];
$raise = $row["raise"];
$sold = $row["sold"];
}
$results->free();
echo ('<div id="buttons">
<a class="btn btn-primary btn-lg" style="margin-bottom: 10px; margin-top: 10px; width: 80%;" href="includes\placebid.php?itemid=' . $getid . '&ammount=' . $item->thenext .'">Bid $' . $item->thenext . '</a>
');
if ($buyout){echo ('
<a class="btn btn-success btn-lg" style="margin-bottom: 10px; width: 80%;" href="includes\placebid.php?itemid='.$getid.'&ammount='.$buyout.'">Buyout $'.$buyout.'</a>
');}
echo '</div><!-- buttons -->';
echo ('
<div class="dropdown">
<button style="margin-bottom: 10px; width: 80%;" type="button" class="btn btn-info btn-lg dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Custom Bid<span class="caret"></span></button>
<ul class="dropdown-menu">
');
// build the custom bid dropdown
if (!$buyout) { $maxcust = $item->thenext*25;
for ($cust = $item->thenext; $cust <= $maxcust; $cust = $cust + $raise) {
echo ('<li>' .$cust. '</li>');
}
}
if ($buyout) {
for ($cust = $item->thenext; $cust <= $buyout; $cust = $cust + $raise) {
echo ('<li>' .$cust. '</li>');
}
}
echo ('
</ul>
</div><!-- dropdown -->
');
}
mysqli_close($mysqli);
?>
I think the problem may be in that your PHP file is generating HTML which is continually replacing elements on your page due to them being loaded via AJAX.
Just an idea but you could make your PHP output a JSON instead that contains the database results, then have jQuery read the output. Your code would then process that JSON file and create or update the HTML elements accordingly (rather than replace them).
This way you have more fine grained control in the JavaScript for when your dropdown should close.
See this answer if you'd like to output from MySQLi to JSON.
I am printing out pictures and names (in a grid view). The user will be able to click on the picture or the name, and this will open up a modal with the title of the picture/name (which will be the same) which was clicked.
<?php
$i = 0;
while ($row = mysqli_fetch_assoc($data)) {
print '<li>';
print '<a class="btn btn-default" data-toggle="modal" data-target=".bs-example-modal-lg"><img src="'.$row["image"].'" /></a><br>';
print '<a class="btn btn-default" data-toggle="modal" data-target=".bs-example-modal-lg"><h4>'.$row['name'].'</h4></a>';
print '</li>';
}
?>
When the image/name is clicked, how do I store the image path or the name that was clicked to a variable and send it to php so I can run a query and get more information (based on the click) to populate the modal?
I was reading this other post: How to pass jQuery variables to PHP variable?
But it is only for a single case, how would I pass variables which are printed out using a while loop?
WOuld the data-id tag of modals be useful here?
Basically, what you need to do is this:
Load your images onto the page with your php code
At the same time, load the buttons/links that select each picture
For each button, add a data attribute and store the database row id for each image record in that data attribute (these buttons are all also setup to open the same modal)
When the user clicks the button, get the stored row id from the clicked button
Make an ajax call to another php page passing in the row id
On the other php page, use the id to look up the record and return all of the fields
Back on the first page, when the ajax call returns, use the returned data to fill in the modal's content
Here is a working example
Also note: depending on the additional information you are getting from the database, you might just store all of the information in data attributes of the button when the first page loads and avoid the ajax call all together. Of course, if you're getting a lot of data like pdf files or something, that might not be practical.
Full code for: imagesfromdb.php (the main page):
<?php
// remove below for production
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
// remove above for production
// change these to your own database details
$db = new PDO('mysql:host=sotestdbuser.db.10125908.hostedresource.com;dbname=sotestdbuser;charset=utf8', 'sotestdbuser', 'Sotestuser398!');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); // later, change ERRMODE_WARNING to ERRMODE_EXCEPTION so users wont see any errors
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = 'SELECT id, url FROM imagebase ORDER BY id';
$stmt = $db->prepare($sql);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$imgGroups=array();
// check for errors
if($stmt->errorCode() == 0) {
// no errors
foreach($rows as $row) {
$id = $row['id'];
$url= $row['url'];
$imgGrp ='<div class="col-sm-4">'.
'<div class="row">'.
'<div class="col-sm-12 text-center"><img src="'.$url.'" width="100" height="100" alt=""/></div>'.
'<div class="col-sm-12 text-center">'. //note the addition of the "data-row-id" attribute below
'<button type="button" class="btn btn-primary get-data" data-row-id="'.$id.'" data-toggle="modal" href="#my-modal">Select image</button>'.
'</div>'.
'</div>'.
'</div>';
array_push($imgGroups,$imgGrp);
}
} else {
// had errors
$errors = $stmt->errorInfo();
return $errors[2];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Images From Database Test</title>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<style>
img {
display: block;
margin-left: auto;
margin-right: auto
}
</style>
</head>
<body>
<div class="row text-center" >
<h1>Image From DB Test</h1>
</div>
<div class="row" >
<div class="col-sm-12" id="image-groups"> <?php echo join('',$imgGroups); ?> </div>
</div>
<!-- Modal 7 (Ajax Modal)-->
<div class="modal fade" id="my-modal" >
<div class="modal-dialog">
<div class="modal-content modal-shadow">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="my-modal-title" >Help</h4>
</div>
<div class="modal-body">
<div class="col-sm-12 text-center"><img src="" class="image" id="my-modal-image" width="100" height="100" alt=""/></div>
<div class="col-sm-12 text-center description" id="my-modal-description"> </div>
</div>
<div class="modal-footer">
<button type="button" id="" class="btn btn-default reload" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script>
$(function(){
// when the user clicks on one of the buttons, get the id from the clicked button
// then make an ajax call to another php page
$('#image-groups').on('click', '.get-data', function(){
var id = $(this).data('row-id');
var sendVars = 'id='+encodeURIComponent(id);
$.ajax({
type: "POST",
url: "getimagedetails.php",
data: sendVars,
success: function(rtnData) {
rtnData = $.parseJSON(rtnData)
$('#my-modal-title').html(rtnData.title);
$('#my-modal-image').attr('src', rtnData.url);
$('#my-modal-description').html(rtnData.description);
}
});
});
});
</script>
</body>
</html>
Full code for: getimagedetails.php (the page we make the ajax call to)
<?php
// remove below for production
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
// remove above for production
// change these to your own database details
$db = new PDO('mysql:host=sotestdbuser.db.10125908.hostedresource.com;dbname=sotestdbuser;charset=utf8', 'sotestdbuser', 'Sotestuser398!');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); // later, change ERRMODE_WARNING to ERRMODE_EXCEPTION so users wont see any errors
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
if(isset($_POST['id'])){
$sql = 'SELECT url, title, description FROM imagebase WHERE id=? LIMIT 1'; // "?"s here will get replaced with the array elements belowlinkslinks
$stmt = $db->prepare($sql);
$stmt->execute(array($_POST['id'])); // these array elements will replace the above "?"s in this same order
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
// check for errors
if($stmt->errorCode() == 0) {
// no errors
$rowdata = 'test';
foreach($rows as $row) {
$rowdata = array('url' =>$row['url'], 'title' =>$row['title'], 'description' =>$row['description']);
}
echo json_encode($rowdata);
} else {
// had errors
$errors = $stmt->errorInfo();
echo $errors[2];
}
}
?>
Try to make an ajax call onClick of the element
<?php
$i = 0;
while ($row = mysqli_fetch_assoc($data)) {
print '<li>';
print '<a class="pass_href btn btn-default" data-toggle="modal" data-href="test/path/to-the-image.jpg" data-target=".bs-example-modal-lg"><img src="'.$row["image"].'" /></a><br>';
print '<a class="pass_href btn btn-default" data-toggle="modal" data-href="test/path/to-the-image-2.jpg" data-target=".bs-example-modal-lg"><h4>'.$row['name'].'</h4></a>';
print '</li>';
}
?>
Now the jQuery
$(function(){
$('.pass_href').click(function(){
var href = $(this).attr('data-href');
$.post( "test.php", { href:href } );
});
});
For showing details information on the modal you need to post a form using ajax.Here i am giving you a solution.First add a data-id attribute in your both buttons and also call a function in onclick event.
print '<li>';
print '<a class="btn btn-default" data-id='.$row['id'].' onclick="show(this);" data-toggle="modal" data-target=".bs-example-modal-lg"><img src="'.$row["image"].'" /></a><br>';
print '<a class="btn btn-default" data-id='.$row['id'].' onclick="show(this);" data-toggle="modal" data-target=".bs-example-modal-lg"><h4>'.$row['name'].'</h4></a>';
print '</li>';
and then post a form using ajax on that function call.like-
<script>
function show(x){
var id = $(x).data('id');
$.ajax({
type: "POST",
url: "your/url",
data: { id: id},
success: function(data) {
//parse your json data
var obj = $.parseJSON(data);
if (obj != null){
//append/show your data in your modal body
}
}
});
}
</script>
and in your php function receive your posted id and find details for that id from the database or anywhere. and then return your data as json type using php json_encode() function.