Passing Jquery variable to php within a modal - php

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.

Related

Ajax not redirecting me to next page

I am trying to pass the ID of the clicked image to next page. When I developed my code, it didn't redirect me to the next page. When I click F12 and check the POST in network, it shows that the variable is passed correctly to the next page as shown in the attached image but it didn't redirect me to the next page. So now I know that the variable is passed and received correctly in the next page but I need what needed in my code to direct me to the next page,
Note: when I tried to put window.location.href = 'userevent.php'; it redirect me but without the variable and gives me error (Notice: Undefined index: clicked in)
Also when I use url: '#userevent.php.Action("delivery", "service")',, it gives me network status 403
this is my code:
<?php
session_start();
require "init.php";
login();
?>
<html>
<!--...-->
<head>
<meta charset="utf-8">
<title> Ghost </title>
<!-- <link rel="Stylesheet" href="css/style1.css">-->
<link rel="stylesheet" href="css/style2.css" media="screen" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script >
function myFunction(clicked) {
document.getElementById('test').innerHTML = clicked;
$.ajax({
type: "POST",
//url: '#userevent.php.Action("delivery", "service")',
url: 'userevent.php',
dataType:'json',
data: {"clicked": clicked},
success: function(data){
}
});
window.location.href = 'userevent.php';
}
</script>
</head>
<body>
<div class="sidenav">
Main Page
About Us
</div>
<div class="login-box">
<h1>Add Event</h1>
<div>
<p id="test"> </p>
<?php
// LOGIN USER
function login(){
global $con;
global $counter;
echo "<table align='center' >";
//$email = $mysqli->escape_string('');
$query="SELECT * FROM events ORDER BY ID ASC";
$result=mysqli_query($con,$query);
if ( $result->num_rows == 0 ) // User doesn't exist
echo "User with that ID doesn't exist!";
else { // User exists
$counter = 0;
$emptyArray = [];
while($row = $result->fetch_assoc())
{
$emptyArray[$counter]= $row["ID"];
if($counter == 0)
{
echo '<tr>';
}
echo '<td><img id=' . $row["ID"]. ' onClick="myFunction(this.id)" src="images/' . $row["photo"]. '" width="250px" height= "250px" alt="Avatar" >
<h1 id = "GFG_DOWN" style =
"color:white;text-align:center; font-size: 20px; font-weight: bold;"> '.$emptyArray[$counter].'
</h1> </td>';
$counter++;
if($counter == 3)
{
echo "</tr>";
$counter = 0;
}
}
}
}
mysqli_close($con);
?>
and this is the code in the second page:
<div class='textbox'>
<label> ID: ".$_POST['clicked']."</label>
</div>
The entire point of Ajax is that that request is made with JavaScript and the response is handled by JavaScript without navigating to a new page.
If you want to make a POST request and navigate to the resulting page, then use a <form>
window.location.href = 'userevent.php';
it redirect me but without the variable
Assigning a URL to location.href triggers browser navigation (with a GET request) to that URL.
It is a completely different request to the Ajax request so it doesn't have the data from that request.
Again: Use a form for this.
I read the data from database and I get the clicked id of the images.
Put the data you want to send in a submit button instead.
<form method="POST" action="userevent.php">
<?php while($row = $result->fetch_assoc()) ?>
<button name="clicked" value="<?php echo htmlspecialchars($row["ID"]); ?>">
<img src="images/<?php echo htmlspecialchars($row["photo"]); ?> alt="Put useful and unique alt text so people know what they are selecting if they can't see the image">
</button>
<?php } ?>
</form>
I think you are better off making a small form, since you want to send the user to a new page when clicking.
<?php while($row = $result->fetch_assoc()) ?>
<form action="userevent.php" method="POST">
<input type="hidden" name="clicked" value="$row["ID"]">
<img src="images/{{ $row['photo'] }}" class="img">
</form>
<?php } ?>
$('.img').click(function() {
this.form.submit();
});
*Edited to reflect your current edits.

How to make an id from a PHP while echo loop make work with JQuery AJAX

I want to make an id reference "logout" work when clicked from my php code. Please this would aid me very well in continuing the project. this method is important because it involves phonegap
php file
The php file gets user details from the database. the logout id is used to call the php page through an AJAX request and then log the user out and redirect them.
<?php
session_start();
$con = mysqli_connect("localhost", "*****", "*****", "*****");
//check connection...
if ($con === false) {
die ("couldn't connect to SQL Server");
}
if (isset($_SESSION['people_email'])){
$selectdata = "SELECT * FROM people WHERE people_email = '".$_SESSION['people_email']."'" ;
$query = mysqli_query($con, $selectdata);
while ($row = mysqli_fetch_array($query)) {
echo '<div class="ui fluid card">';
echo '<div class="extra content">';
echo '<div class="left floated meta">';
echo '<a href="#" id="logout">';
echo '<i class="remove circle icon"></i>';
echo "Log out";
echo '</a>';
echo '</div>';
echo '<div class="right floated meta">';
echo '<a>';
echo '<i class="plus icon"></i>';
echo "Upload a photo";
echo '</a>';
echo '</div>';
echo '</div>';
echo '<div class="image">';
echo '<img src="/images/avatar2/large/kristy.png">';
echo '</div>';
echo '<div class="content">';
echo '<a class="header">'.$row['people_name'].'</a>';
echo '<div class="meta">';
echo '<span class="date">'.$row['people_name'].'</span>';
echo '</div>';
echo '<div class="description">'.$row['people_email'].'</div>';
echo '</div>';
echo '<div class="extra content">';
echo '<a><i class="send icon"></i>'.$row['people_username'].'</a>';
echo '<a><i class="alarm icon"></i>'.$row['people_username'].'</a>';
echo '</div>';
echo '</div>' ;
}
}
else {
echo "no";
}
?>
this is the HTML file.
the html file graps the user data for php echo and displays them.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
<!-- Path to your custom app styles-->
<link rel="stylesheet" href="css/my-app.css">
<link rel="stylesheet" href="Semantic/semantic.min.css">
<!--<link rel="stylesheet" type="text/css" href="css/index.css" />-->
<title>MyApp</title>
</head>
<body>
<!-- Views -->
<div class="views">
<!-- Your main view, should have "view-main" class -->
<div class="view view-main">
<!-- Pages container, because we use fixed navbar and toolbar, it has additional appropriate classes-->
<div class="pages navbar-fixed toolbar-fixed">
<!-- Page, "data-page" contains page name -->
<div class="page " data-page="profile">
<!-- Top Navbar. In Material theme it should be inside of the page-->
<div class="navbar bar-color">
<div class="navbar-inner">
<div class="left"><i class="bell icon"></i>
</div>
<div class="center"><form><input size="50px" type="search" placeholder="Search"/></form></div>
<div class="right">
<!-- Right link contains only icon - additional "icon-only" class-->
<i class="building outline icon"></i>
</div>
</div>
</div>
<!-- Toolbar. In Material theme it should be inside of the page-->
<div class="toolbar toolbar-bottom bar-color">
<div class="toolbar-inner">
<!-- Toolbar links -->
<i class="eye icon"></i>
<i class="calendar icon"></i>
<i class="plus icon"></i>
<i class="user icon"></i>
</div>
</div>
<!-- Scrollable page content -->
<div class="page-content" >
<div id="profile" style="height:90%; width:90%;margin:auto;position:relative;top:20px;"></div>
</div>
</div>
</div>
</div>
</div>
<script src="js/jquery-2.2.3.min.js"></script>
<script src="Semantic/semantic.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
type: 'get',
url: 'profile.php',
dataType: 'html',
success: function (response) {
$('#profile').html(response);
}
});
$("#logout").click(function() {
$.ajax({
type: 'get',
url: 'logout.php',
success: function (response) {
if (response == "success") {
window.location.href="login.html";
}else{
alert("You were not logged out");
}
}
});
});
});
</script>
</body>
</html>
You can include data attributes like data-page-id in the log out button html and use jQuery's attr() function to fetch that data.
<div id='logout' data-info='some_info'></div>
$('#logout').attr('data-info'); //returns the value
But I don't see why you need this extra info since it's just a log out button and you can bind it's id to click event.

Load MySQL data dynamically by unique id into Bootstrap modal -CodeIgniter

Having successfully eliminated the issue from a previous question I posed in add limit to data passed to bootstrap modal with foreach() in codeigniter, I now find myself with the residue of that issue. As succinctly posited by #webcrazymaniac;
The idea is to have a unique modal window, with it's unique id for each article, uniquely called with the corresponding button
According to the solution listed in Send parameter to Bootstrap modal window?, I should be able to have my desired effect as stated above - adapted as;
On page Modal
<!-- alert view -->
<div class='modal fade' id='myModal' role='dialog'>
<div class='modal-dialog'>
<!-- Modal content-->
<div class='modal-content' id='#myModal<?php echo $a->art_id;?>'>
<div class='modal-header'>
<button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>
<h2 class='modal-title'>Title: <?php echo $a->title;?></h2>
</div>
<div class='modal-body'>
<h3>Category: <?php echo $a->cat_name;?></h3>
<h3>Date: <?php echo $a->public_date;?></h3>
<h3>Content: <?php echo $a->description;?></h3>
</div>
<div class='modal-footer'>
<button type='button' class='btn btn-default' data-dismiss='modal'>Close</button>
</div>
</div>
</div>
jQuery Script
<script type="text/javascript">
$( document ).ready(function() {
$('#myModal').on('show.bs.modal', function (e) { //Modal Event
var id = $(e.relatedTarget).data('id'); //Fetch id from modal trigger button
$.ajax({
type : 'POST',
url : 'query.php', //Here you will fetch records
data : 'post_id='+ id, //Pass $id
success : function(data){
$('.form-data').html(data);//Show fetched data from database
}
});
});
});
</script>
Modal Trigger Button
echo "<a href='#myModal/".$a->art_id."' class='btn btn-success btn-sm' data-toggle='modal' data-target='#myModal' data-id='".$a->art_id."'>View</a> ".
query.php
<?php
//Include database connection here
$dsn = 'mysql:host=localhost;dbname=articles;charset=utf8';
$user ='';
$pass ='';
$options = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES, false);
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
if($_POST['art_id']) {
$id = $_POST['art_id'];
$category = $_POST['cat_name'];
$public_date = $_POST['public_date'];
$description = $_POST['description'];
// Run the Query
$sql = "SELECT `art_id`, `cat_name`, `public_date`, `description` FROM `articles` WHERE `art_id`='?'";
$stmt = $pdo->prepare($sql);
// Fetch Records
$stmt->execute();
}
?>
It all works to call the modal, but this attempt only nets me the 5th result on-page for all (green) buttons clicked. As (maybe) an important note, I'm having trouble with data-id='#myModal<?php echo $a->art_id;?> fitting into the modal trigger button as it destroys the popup of the modal. I know I have to maybe pull a destruction mode in order to change to another ID like so;
$('#myModal').on('hidden.bs.modal', function () {
$(this).removeData('bs.modal');
});
Now, mind you, I'm not especially conversant in jQuery, so what I've come up with is based on a solid few hours of reading and experimentation. Having pored over numerous examples, I'm still at a loss as to exactly how to make this all work. I'm really stuck as I'm getting the same result (off by a factor of either the display of the first or fifth result for clicking green buttons) whether I'm trying this straight PHP or jQuery. It seems like every question that I've read in this category of question gets me to the current dilemma I'm in where if I use the PHP version solution, I'm returned the 1st page result for every view button on the page. jQuery solution returns the fifth page result for each view button. This is strange indeed... Not even changing out the jQuery for simplified js like this;
<script type="text/javascript">
//jQuery Library Comes First
//Bootstrap Library
($ 'a[data-toggle=modal]').click ->
target = ($ #).attr('data-target')
url = ($ #).attr('href')
($ target).load(url)
I was pulling for that snippet to rescue me, but, no. Neither did this one;
<script type="text/javascript">
//jQuery Library Comes First
//Bootstrap Library
$(document).ready(function(){
$('#myModal').on('shown.bs.modal', function () {
var $modal = $(this),
modal_title = $(this).data('modal-title'),
modal_params = $(this).data('modal-params');
if(typeof modal_title !== typeof undefined && modal_title !== false) {
title = modal_title;
}
else{
title = 'Title';
}
$.ajax({
cache: false,
type: 'POST',
url: 'query.php',
data: modal_params,
success: function(data) {
$modal.find('.modal-title').html(title);
$modal.find('.modal-body').html(data);
}
});
});
});
</script>
//crabbed from
//https://stackoverflow.com/questions/35702374/bootstrap-modal-with-individual-attributes
But, as par for the course, no love... There's either Human Error to blame, or I'm just missing something plainly hiding in full view. Having read more than 200-plus questions today, I'm having problems re-reading this for formatting, etc. (lol!). Learned tons, but still stuck.
UPDATE
In the time since I've looked at what #progrAmmar suggested, I went back to try and refine my approach. The key issue is how to make the jQuery reload process;
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
clear out the modal so that upon click of another button, the corresponding table row content flows in like water. I'm having problems figuring out what sequencing is correct for the jQuery - as it stands now;
<script type="text/javascript">
//jQuery Library Comes First
//Bootstrap Library
$(document).ready(function() {
// Fill modal with content from link href
$('.myModal').on('click', function(e) {
var link = $(this).data('href');
$('#myModal').modal('show');
$('#myModal .modal-body').load(link );
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});
})
</script>
Which results in the view below:
If you look on the bottom-left of the image you'll see the corresponding id value is 3, but the open modal is pulling content from id value 5. I'm still having the process of calling the modal and displaying table row go smoothly, but the modal reload process is bent. Suggestions? I'm out of ideas at this point.
#progrAmmar, I went back to your proffered suggestion, but these are the following things preventing me from fully adapting;
article/index (controller/index function)
public function index()
{
$modal = $this->article_model->modal($art_id=NULL);
$category = $this->category_model->listAll();
$article =$this->article_model->index($this->limit);
$total_rows=$this->article_model->count();
$config['total_rows']=$total_rows;
$config['per_page']=$this->limit;
$config['uri_segment']=3;
$config['base_url']=site_url('article/index');
$this->pagination->initialize($config);
$page_link =$this->pagination->create_links();
$this->load->view('admin/article',compact('article', 'page_link', 'category', 'modal'));
}
article_model.php
public function modal($art_id)
{
$data = array();
$this->db->select('art_id', 'cat_name', 'public_date', 'description');
$this->db->from('tbl_article');
$query = $this->db->get();
if($query->num_rows() > 0)
{
$results = $query->result();
}
return $results;
}
Still trying to figure out where the needle is here. Thanks again for your suggestions #progrAmmar.
UPDATE ANNOYANCES
Back to purely PHP as jQuery wasn't doing anything different for me - even after playing around with #progrAmmar's code. Now I'm left back at ground zero and having read for another two hours (mainly # the jQuery forum). :sigh:
ALMOST THERE....
After consulting the BS 3.3.5 docs, I know my answer is in the Varying modal content based on trigger button section. Tried to extrapolate this;
//Modal window trigger button
echo "<a href='".base_url()."article/$a->art_id' class='btn btn-success btn-sm' data-toggle='modal' data-target='#myModal' data-id='".$a->art_id."'>View</a> ".
//jQuery code
$('#myModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var id = button.data('id') // Extract info from data-* attributes
var href = button.data('href') // Extract info from data-* attributes
var target = button.data('target') // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this)
modal.find('.modal-title').text('Title:')
modal.find('.modal-body').val('Category:')
modal.find('.modal-body').val('Date:')
modal.find('.modal-body').val('Content:')
$('#myModal > div.modal-body).empty();
})
I'm pretty sure I'm doing it wrong as I just can't get my head around any attempted extrapolations - been poring over other solution examples on SO, but am still working out approaches to the above coding. Research in motion...
Extrapolating Code Proffered By #progrAmmar;
Controller Article(.php)
------------------------
public function index()
{
$data['modal'] = $this->article_model->modal($art_id); // Gets all the data
$this->load->view('('admin/article',compact('article', 'page_link', 'category', 'modal') $data);
}
View article(.php)
------------------
<div class='modal fade' id='myModal' role='dialog'>
<div class='modal-dialog'>
<!-- Modal content-->
<div class='modal-content' id='myModal'>
<div class='modal-header'>
<button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>
<h2 class='modal-title'>Title: <?php echo $a->title;?></h2>
</div>
<div class="modal-body">
<div class="row">
<div class="col col-md-12">
<h3>Category: <?php echo $a->cat_name;?></h3>
<h3>Date: <?php echo $a->public_date;?></h3>
<h3>Content: <?php echo $a->description;?></h3>
<input type="hidden" id="hidId" value="<?php echo $a->art_id;?>" />
</div>
</div>
</div>
<div class='modal-footer'>
<button type='button' class='btn btn-default' data-dismiss='modal'>Close</button>
</div>
//Finally call the html via JavaScript
$.get(window.base_url + 'index.php/article/'+ id, function (data) {
$('#myModal' > div.modal-body).empty();
$('#myModal').html('data');
$('#myModal').modal('show');
}
Did a little juggling to fit in this attempt, but there's no change as the fifth page result is never bumped out by another content ID as shown below;
Still stuck in the same position before...round and round we go ミ●﹏☉ミ
Of the section I'm interested in within the docs;
$('#exampleModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var recipient = button.data('whatever') // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this)
modal.find('.modal-title').text('New message to ' + recipient)
modal.find('.modal-body input').val(recipient)
})
my primary issue is;
HOW do I extrapolate Update the modal's content?
THIS is essentially the core of my impedance and not located by an intensive search of the BS docs. If I could sync up some kind of way to force-reload the content within the modal, I have my answer. In fact the closest I've found to any example of how to (maybe) approach this was a post here (sorry forgot which one) detailing how to reload an image within a modal by targeting the src element;
//And then you just change the src attribute of the picture element from your function.
var picture = button.data('picture')
$('#picture').attr('src',picture);
THAT'S IT!* (theoretically)...Between the above example and the Varying modal content based on trigger button example, I'm on my way to losing it. I can't believe I can't just make the logical connection required to fire off the force-reload. I just don't see it, and every example I've used thus far keeps me in the same place.
Having gone through fifty-plus JQuery code examples, not one of them did squat as far as activating any functionality, so I'm off attempting to use it as any sort of solution. NONE of the answers under this topic worked (even a little). This is the 1st time in my career where I've been completely stumped with nowhere to turn.
Here are the things I've tried:
Situation 1
Initially dealing with an HTML table <table class="table table-condensed"> listing out the articles db elements of 'art_id', 'title', 'cat_name', 'public_date', 'image', the table elements are scooped from the db with foreach ($article->result() as $a){.
The table ends with the activity buttons, the 1st of which is the BS modal trigger (unable to change table being echoed out in PHP - just mucks it all up);
echo "<a href='".base_url()."article/#myModal/$a->art_id' button class='btn btn-success btn-sm' data-toggle='modal' data-target='#myModal' data-id='".$a->art_id."'>View</a> ".
Situation 2
The modal data-toggle (as posted above) is the trigger for the modal to popup and is located on page bottom;
<!-- alert view -->
<div id="myModal<?php echo $a->art_id" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<?php
$i=0;
foreach ($article->result() as $a){
?>
<div id="#myModal<?php echo $a->art_id ?>" class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h2 class='modal-title'>Title: <?php echo $a->title;?></h2>
</div>
<div class='modal-body'>
<h3>Category: <?php echo $a->cat_name;?></h3>
<h3>Date: <?php echo $a->public_date;?></h3>
<h3>Content: <?php echo $a->description;?></h3>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
<?php
if(!$i=0) break;
$i++;
}
?>
</div>
If the modal foreach isn't both included and augmented like so;
<?php
if(!$i=0) {
break;
} else {
$i++;
}}
?>
then the modal pulls all of the $a->art_id elements into view simultaneously like so;
And, even with the necessary jQuery at the bottom (after the modal);
<script type="text/javascript">
jQuery(document).ready(function($) {
jQuery(document).ready(function($) {
$('.myModal').click(function(event){
var $link = $(this);
new BootstrapDialog({
title : 'Title : ' + $link.attr('href'),
content : $('<div>Loading...</div>').load($link.attr('href')),
buttons : [{
label : 'Close',
onclick : function(dialog){
dialog.close();
}
}, {
label : 'View',
cssClass: 'btn-primary',
onclick : function(dialog){
alert('The content of the dialog is: ' + dialog.getBody().html());
dialog.close();
}
}]
}).open();
event.preventDefault();
});
});
});
</script>
//crabbed from - https://stackoverflow.com/questions/14045515/how-can-i-reuse-one-bootstrap-modal-div/14059187#14059187
Situation 3
NOTHING WORKS.... The jQuery is not destroying and reloading the modal, so I'm only getting that 1st on-page result from the 1st button on the page (completely correct content and ID). The most frustrating thing is if I hover over each button, the correct content ID is returned. I think it's safe to say that it's not any problem with the code - I have to investigate WHY that specific code isn't working on-page. Confusing because I'm using jQuery already;
<script src="<?php echo base_url(); ?>asset/js/jquery.js"></script>
<script src="<?php echo base_url(); ?>asset/js/jquery-latest.min.js"></script>
putting these two lines just above the modal and jQuery at the bottom of the page. It looks as if there is a conflict somewhere preventing the jQuery-driven script from firing. The only conflict I can maybe even see is that with the CKEditor that loads just above the jQuery.
Even with switching to another code block;
<script type="text/javascript">
jQuery(document).ready(function($) {
$('.myModal').click(function(){
$(this).find('.inner').clone().appendTo('#myModal .modal-content');
$('#myModal .modal-title .modal-body .control-group.hide').show();
$('#myModal').modal();
});
$('#myModal').on('hidden', function(){
$('#myModal .inner').remove();
});
});
</script>//forgotten SO crabbing
I keep getting the same results. Since throwing in the towel, I've come upon several SO solutions which suggest the scenario I want, but I can never physically fulfill them and it making me angrier than a rattlesnake in a Texans' boot. Not only were these questions completely similar to mine, but they (almost) all got upvoted # +1 or better, and the selected solutions did nothing to extract me from my bottleneck.
This is an issue that I'd like to see cleared up as I know there's a solution, and from the numerous Fiddles and Plunkers, they're all similar in nature with slight variations that I haven't been able to employ.
The simplest (and probably the easiest) way to call a MODAL for data is to call the HTML from the server.
Create a separate view for your model.
Call the data into it, load the model from the controller.
Here's how I am calling my Modal with codeigniter
Controller
public function EditData($id)
{
$data['entity'] = $this->Home_model->getData($id); // Gets all the data
$this->load->view('Home/modal_data', $data);
}
views/Home/modal_data.php
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Edit <?= $entity['name'] ?></h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col col-md-12">
<label>Name</label>
<input type="text" id="txtName" class="form-control" value="<?= $entity['name'] ?>" />
<input type="hidden" id="hidId" value="<?= $entity['id'] ?>" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success has-spinner" id="btnSave">
<span class="spinner"><i class="glyphicon glyphicon-spin glyphicon-refresh"></i></span>Save
</button>
</div>
Make sure you have a modal div on your page to call the html into.
views/Home/index.php
<html>
.
.
.
<body>
<div id="home_modal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content" id="home_modal_cont">
</div>
</div>
</div>
</body
</html>
Finally call the html via JavaScript
$.get(window.base_url + 'index.php/home/EditData/'+ id, function (data) {
$('#home_modal_cont').empty();
$('#home_modal_cont').html(data);
$('#home_modal').modal('show');
}

Render new data of modal inside modal PHP, jQuery

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.

How to pass msg_id into jquery modal form?

I have a following data where I am showing data from database. When i click Comment a dialog appear, there i need to show data in modal from db. but for getting data from db i need msg_id in modal form.
<?php
$msg_id = $data['message_id'];
?>
<a data-toggle="modal" href="msg_id=<?php echo $msg_id; ?>#example" class="link_comment">Comment</a>
So here I want to pass msg_id to jquery modal form, where i can get data from db on the base of msg_id for that specific message and show it in modal box.
<div id="example" class="modal" style="display: none; ">
Your Message id : <?php echo $msg_id; ?>
</div>
So how can I pass $msg_id into jquery modal form.
php
<?php
$msg_id = 123; // testing mode
?>
html
<a data-toggle="modal" href="msg_id=<?php echo $msg_id; ?>#example" class="link_comment">Comment</a>
<div id="example" class="modal" style="display: none; ">
Your Message id : <span class="msg_id">?</span>
</div>
<script type="text/javascript">
$('a.link_comment').click(function(event) {
event.preventDefault();
var a = $(this);
var msg_id = 'fetched id'; // parse msg_id from a.attr('href')
$('div.' + a.attr('data-toggle')).show().find('span.msg_id').text( msg_id );
});
</script>

Categories