Bootstrap 5 Modal not receiving data from PHP with AJAX - php

I have a modal in bootstrap 5 that i'm trying to populate with custom data from a mysql database depending on the option i'm selecting.
So I have a table that is populated with some data using PHP and MYSQL. The last column of the table is a button called "Actions" and I want to have a modal opened when I press this button that is filled with the information from the row where I pressed the button (every row contains this button as the last column).
As you can see in the below code, I have the exact same code as I found out in the sollution in this question: Pass PHP variable to bootstrap modal
Here is my code:
In the main index file:
...
...
<tbody>
<?php $categories = Category::find_all();
foreach ($categories as $category) { ?>
<tr>
<th scope="row"><?php echo $category->id; ?></th>
<td><?php echo $category->cat_name; ?></td>
<td><?php echo $category->cat_creation_date; ?></td>
<td><?php echo $category->cat_created_by; ?></td>
<td><a type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#bsMyModal" data-id="<?php echo $category->id; ?>">Actions</a></td>
</tr>
<?php } ?>
</tbody>
...
...
Modal code (in the same file as the above table):
<div class="modal fade" id="bsMyModal" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Edit Data</h4>
</div>
<div class="modal-body">
<div class="fetched-data"></div> //Here Will show the Data
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JS code (just below the end of body in the same file)
</body>
<script>
$(document).ready(function(){
$('#bsMyModal').on('show.bs.modal', function (e) {
var rowid = $(e.relatedTarget).data('id');
$.ajax({
type : 'post',
url : 'fetch_record.php', //Here you will fetch records
data : 'rowid='+ rowid, //Pass $id
success : function(data){
$('.fetched-data').html(data);//Show fetched data from database
}
});
});
});
</script>
Also the fetch_record.php file which is a basic file just to have this working:
<?php
require_once "backend/init.php";
if($_POST['rowid']) {
$id = $_POST['rowid']; //escape string
echo $id;
}
?>
Now the problem.. nothing happens
The modal openes when I press the Actions button, but I don't get any information (in this specific case I should be getting the category id printed out before the "//Here Will show the Data" text in the modal code.
I looked at the console and I've seen this message:
ajax:681 Uncaught ReferenceError: $ is not defined
at ajax:681:1
(anonymous) # ajax:681
If i click the link at # ajax:681, it points me to this:
enter image description here
What am I doing wrong?...
Thank you!

Stupid mistake...
I tought about searching for the console error and come upon this:
Uncaught ReferenceError: $ is not defined?
And yes.. I was using the script before referencing the jQuery.. I moved it after the jQuery include and now it works.
Dumb

Related

Add record to MySQL using AJAX / jquery on multiple elements with the same class

Im new here and I have some difficulties to make my code to work. Hope u guys can help me. Im displaying records form MySQL in a modal box in a table format. Each row has its own add (+) button generated via php loop which displays records that should be leter on, added to a different table using jquery on click event and AJAX. Each td row is provided with an input field with class name "idKont", but only the first one will be added after I click on the + / add button.
$('#add_kontpers').on("click", function(e) {
e.preventDefault();
var ptId = $('#idAj').text(); // ID of the customer that will be passed
var idKont = $('.idKont').val(); // ID of the contact person
$.ajax ({
url: "folder/insert_data.php",
method:"POST",
data:
{
id: ptId,
idKont: idKont
},
dataType:'text',
success: function(result) {
//$('#myModal').modal('hide');
$('#alert_modal').append( '<div class="alert alert-success">Success</div>' ).fadeIn(1000).fadeOut(4000);
}
})
})
and this is the HTML Code with PHP:
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header" style="padding:10px 50px;">
<p><span class="glyphicon glyphicon-lock"></span> Choose Contact Person</p>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body" style="padding: 40px 50px;">
<form role="form" method="post">
<div id="alert_modal"></div>
<table class="table table-responsive">
<thead class="thead-light">
<tr>
<th>ID</th>
<th>Vorname</th>
<th>Name</th>
<th>Tel</th>
<th>Mobil</th>
</tr>
</thead>
<tbody>
<?php
try {
$stmt = $connser->prepare("SELECT ID, Vorname, Name, Tel, Mobil FROM Contactperson ORDER BY ID DESC");
$stmt->execute();
while ($row = $stmt->fetch()) {
$kontID = $row['ID'];
?>
<tr>
<td><?php echo $row['ID']; ?></td>
<td><?php echo $row['Vorname']; ?></td>
<td><?php echo $row['Name']; ?></td>
<td><?php echo $row['Tel']; ?></td>
<td><?php echo $row['Mobil']; ?></td>
<td><input class="idKont" value="<?php echo $kontID; ?>" type="hidden" /></td>
<td><button type="submit" class="btn btn-success add_kontpers">+</button></td>
</tr>
<?php
}
}
catch(PDOException $e) {
echo "Error";
//echo "Error: " . $e->getMessage();
exit;
}
?>
</tbody>
</table>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger btn-default pull-left" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
The modal box stays open and it shoud be, but if I click the first element on the top, then only this one will be added. I would like to have the oportunity to click for example one position on the list to add it to the table, the the second one, and so on, but if I click other butten then the first one then the modalbox will be closed and the website reloads. Any help or pinting in the right direction will be highly appreciated.
Two things, first you can't reuse the same ID and by having add_kontpers in a loop, you will reusing that.
So first, change that to a class and idAj doesn't exist in the provided code.
<button type="submit" class="btn btn-success add_kontpers">
Then make this change in your jQUERY
$('.add_kontpers').on("click", function(e) {
e.preventDefault();
var ptId = $('#idAj').text(); ?????????????????????
var idKont = $(this).parents("tr").find('.idKont').val(); // ID of the contact person
Javascript
$(document)
.on('click', 'button#add_kontpers', function(a){
a.preventDefault();
var button = $(this);
var row = button.closest('tr');
var id = row.find('input').val();
$.post("folder/insert_data.php", {id : id, idKont : id})
.done(function(response){
//Your response
})
})

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(); ?>

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');
}

Bootstrap modal confirmation delete

Hello guys I'm trying to delete a record/row from my table using a modal delete confirmation. This is what I've tried so far:
<script type="text/javascript">
$(function(){
$(".btn-show-modal").click(function(e){
e.preventDefault();
$("#dialog-example").modal('show');
});
$("#btn-delete").click(function(e) {
$("#dialog-example").modal('hide');
});
});
</script>
<table class="table table-bordered">
<?php
$stmt2 = $conn->prepare( "SELECT project_code, description
FROM tblprojects" );
$stmt2->execute();
for($i=0; $row2 = $stmt2->fetch(); $i++){
$project = $row2['project_code'];
$desc = $row2['description'];
?>
<tr>
<td><a href="project-detail.php?code=<?php echo $project; ?>">
<?php echo $project; ?></a></td>
<td><?php echo $desc; ?></td>
<td><a href="update-project.php?code=<?php echo $project; ?>" title="Update record">
<i class="icon-edit icon-white">
</i>
</a></td>
<td><a href="#<?php echo $project; ?>"
id="<?php echo $project; ?>"
data-id="<?php echo $project; ?>"
class="btn-show-modal" data-toggle="modal" title="Delete record">
<i class="icon-trash icon-white"></i></a></td>
<div class="modal hide fade" id="dialog-example">
<div class="modal-header">
<h5>Confirm Delete</h5>
</div>
<div class="modal-body">
<p class="modaltext">Are you sure you want to delete this record?</p>
</div>
<div class="modal-footer">
<a href="#" data-dismiss="modal" class="btn btn-info">No<a>
<a href="delete-project.php?code=<?php echo $project; ?>"
class="btn btn-danger" id="btn-delete">Yes<a>
</div>
</div>
</tr>
<?php
}
?>
</table>
But the problem is, when I am about to delete the last row the one that gets deleted is the first row. Why is it like that? Any ideas? Help is much appreciated. Thanks.
The problem lies in the modal generation and passing the $project value.
You are using a loop as
for($i=0; $row2 = $stmt2->fetch(); $i++){
$project = $row2['project_code'];
$desc = $row2['description'];
?>
And inside the above loop you are generating the modals so basically you will have many modals which are equal to the num of rows in the query.
Now all of them are having the same "id" i.e. "dialog-example" and once you click on the delete it pop ups the first modal from the DOM and is deleting wrong data.
Solution
For each modal you give the id as
<div class="modal hide fade" id="dialog-example_<?php echo $project; ?>">
Then in the blow code
$(".btn-show-modal").click(function(e){
e.preventDefault();
$("#dialog-example").modal('show');
});
Get the id of the element using attr("id") and append this at the end of
"dialog-example_"+{id you received}
The same thing you need to do for the hide modal as well.
UPDATE ON HOW TO DO IT
Give the modal div id as
<div class="modal hide fade" id="dialog-example_<?php echo $project; ?>">
Then in the click function to as
$(".btn-show-modal").click(function(e){
e.preventDefault();
var id = $(this).attr('id');
var modal_id = "dialog-example_"+id;
$("#"+modal_id).modal('show');
});
Change
<a href="delete-project.php?code=<?php echo $project; ?>"
class="btn btn-danger" id="btn-delete">Yes<a>
to
<a href="delete-project.php?code=<?php echo $project; ?>"
class="btn btn-danger" id="<?php echo $project ;?>">Yes<a>
AND finally
$("#btn-delete").click(function(e) {
$("#dialog-example").modal('hide');
});
to
$(".btn btn-danger").click(function(e) {
var id = $(this).attr('id');
var modal_id = "dialog-example_"+id;
$("#"+modal_id).modal('hide');
});
because you generate modal for every row this is wrong !
and show modal(first modal show) this is wrong!(this delete first row)
create one modal and set parameter with jquery e.g
$(".btn-show-modal").click(function(e){
e.preventDefault();
$("#dialog-example").modal('show');
$("#dialog-example #btn-delete").attr('href','delete-project.php?code='+$(this).attr('data-id'));
});
good luck
On topic
Problem is you have multiple modals. But select it on 1 id. So jQuery will select the first value.
A solution would be to put the delete url in an hidden input field. Then when the user clicks the open delete modal you select the url and put it in the a tag.
Example time
JavaScript Part
$(function(){
$(".btn-show-modal").click(function(e){
// put the right url in the delete
$("#dialog-example .delete-url").attr('href', $(this).attr('data-delete-url');
$("#dialog-example").modal('show');
return e.preventDefault();
});
$("#btn-delete").click(function(e) {
$("#dialog-example").modal('hide');
});
});
PHP part
I assume $stmt is prepared etc
<ul>
<? foreach($stmt->fetchAll() as $record) : ?>
<li>
delete
</li>
<? endforeach; ?>
</ul>
<div class="modal hide fade" id="dialog-example">
<div class="modal-header">
<h5>Confirm Delete</h5>
</div>
<div class="modal-body">
<p class="modaltext">Are you sure you want to delete this record?</p>
</div>
<div class="modal-footer">
<a href="#" data-dismiss="modal" class="btn btn-info">No<a>
<a class="delete-url btn btn-danger">Yes<a>
</div>
</div>
Code explaind
It is not handy to put an bootstrap modal in an foreach/for/while unless you change the id. But then again lot of duplicate code.
What the code does it changes the delete-url on the fly depending on which a the user clicked
Off topic
I highly recommend using the foreach for your iteration of the data records instead of a for loop.
$stmt2 = $conn->prepare( "SELECT project_code, description
FROM tblprojects" );
$stmt2->execute();
for($i=0; $row2 = $stmt2->fetch(); $i++){ /** code **/}
would be
$stmt2 = $conn->prepare( "SELECT project_code, description
FROM tblprojects" );
$stmt2->execute();
foreach($stmt2->fetchAll() as $record){}
Because when you open the modal, it open the first #dialog-example div.
<script type="text/javascript">
$(function(){
$(".btn-show-modal").click(function(e){
e.preventDefault();
$(this).parent().find("#dialog-example").modal('show');
});

Bootstrap modal issue with ckeditor

This is some how related to Passing MySQL data to Modal Form via PHP because I am using method mentioned in that article to edit records.
But now I have quite surprising issue in it. I am using ckeditor to edit product details but when I use it in there, it shows only in the first record. In next records, simple textarea comes up.
Here is code which comes in while loop.
<div class="modal" id="modaledit<?=$id; ?>">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Edit Product</h4>
</div>
<div class="modal-body">
<div class="formleft">Name:</div>
<div class="formright"><input type="text" name="prod_name" value="<?=$r["prod_name"]; ?>" /></div>
<div class="formleft">Details:</div>
<div class="formright">
<textarea name="prod_details" cols="40" rows="10" id="editor1"><?=$r["prod_details"]; ?></textarea>
<script type="text/javascript">
//<![CDATA[
CKEDITOR.replace( 'editor1',
{
filebrowserBrowseUrl :'js/ckeditor/filemanager/browser/default/browser.html?Connector=<?php echo $url;?>js/ckeditor/filemanager/connectors/php/connector.php',
filebrowserImageBrowseUrl : 'js/ckeditor/filemanager/browser/default/browser.html?Type=Image&Connector=<?php echo $url;?>js/ckeditor/filemanager/connectors/php/connector.php',
filebrowserFlashBrowseUrl :'js/ckeditor/filemanager/browser/default/browser.html?Type=Flash&Connector=<?php echo $url;?>js/ckeditor/filemanager/connectors/php/connector.php',
filebrowserUploadUrl :'<?php echo $url;?>js/ckeditor/filemanager/connectors/php/upload.php?Type=File',
filebrowserImageUploadUrl : '<?php echo $url;?>js/ckeditor/filemanager/connectors/php/upload.php?Type=Image',
filebrowserFlashUploadUrl : '<?php echo $url;?>js/ckeditor/filemanager/connectors/php/upload.php?Type=Flash'
});
//]]>
</script>
</div>
</div>
<div class="modal-footer">
Close
Submit
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
It has become a headache for me because first I tried with external page modal, but there ckeditor does not show up for any record. And here it does show up, but only for first record. weird!!!
EDIT
Another thing I noticed, actually ckeditor is showing in modal for only one time. Basically, I am using two modals on same page, one for add new record and one for edit. And because edit modal is inside while loop of showing all products, so it comes earlier on page. And then, ckeditor shows up only for first record edit. Now I notice that ckeditor is not showing up in add new record modal as well (where it was working perfectly before I wrote edit modal code).
This is what shows up in the error console:
Uncaught [CKEDITOR.editor] The instance "editor1" already exists.
If you plan to use more than one instance of CKEditor on your page do the following:
A) Assign different ID to each textarea element you plan to replace. Something like this should do the trick in your case:
<textarea name="prod_details" cols="40" rows="10" id="editor<?=$id; ?>">
and later:
CKEDITOR.replace( 'editor<?=$id; ?>',
OR
B) Or call something like CKEDITOR.instances.editor1.destroy(); whenever you close the modal dialog window
Keep in mind that you have different errors on this sample page, HTTP 404 requests and
Uncaught TypeError: Cannot read property 'length' of undefined
which may result in CKEditor not loading etc.
If you're using BootStrap than you got Jquery, that said you can add this kind of code (Example)
<script>
$('.modal').on('shown.bs.modal', function (e) {
//<![CDATA[
CKEDITOR.replace( 'editor1',
{
filebrowserBrowseUrl :'js/ckeditor/filemanager/browser/default/browser.html?Connector=<?php echo $url;?>js/ckeditor/filemanager/connectors/php/connector.php',
filebrowserImageBrowseUrl : 'js/ckeditor/filemanager/browser/default/browser.html?Type=Image&Connector=<?php echo $url;?>js/ckeditor/filemanager/connectors/php/connector.php',
filebrowserFlashBrowseUrl :'js/ckeditor/filemanager/browser/default/browser.html?Type=Flash&Connector=<?php echo $url;?>js/ckeditor/filemanager/connectors/php/connector.php',
filebrowserUploadUrl :'<?php echo $url;?>js/ckeditor/filemanager/connectors/php/upload.php?Type=File',
filebrowserImageUploadUrl : '<?php echo $url;?>js/ckeditor/filemanager/connectors/php/upload.php?Type=Image',
filebrowserFlashUploadUrl : '<?php echo $url;?>js/ckeditor/filemanager/connectors/php/upload.php?Type=Flash'
});
//]]>
})
</script>
Please note that this example code is binded to the modal class, if you are using modal only for this you can give a try. However, you do not need to have 100 Modal if you've got 100 rows, you can simply use 1 modal and change the contents with Javascript/Jquery when needed.
EDIT: Added the part.

Categories