Defining a Bootstrap button on a separate php file - php

Working with two php files, index.php and search.php. index sends some parameters to search, which performs a few queries into a database, and then returns the information on a table, stored into $output.
I now want to add a bootstrap button to the output, that calls a simple show/hide jQuery function.
The button is created, but it doesn't work when I test it on index.php
<div class="col-sm-8">
<table class="table table-hover" id="output">
</table>
<div id="edit" >
<div class="page-header" id="editar" style="display: none;">
<h2 id="producto">Placeholder<button id="exit" type="button" class="btn pull-right"><span class="glyphicon glyphicon-remove"></button><!--Clicking this button hides the edit div and shows the output table--></h2>
</div>
</div>
</div>
The exit/editbtn button calls the following:
<script>
$(document).ready(function(){
$("#exit").click(function(){
$(document.getElementById("edit")).hide();
$(document.getElementById("output")).show();
});
});
$(document).ready(function(){
$("#editbtn").click(function(){
$(document.getElementById("edit")).show();
$(document.getElementById("output")).hide();
});
});
</script>
And the definition of the "editbtn" is made on the separate php file:
if($query->num_rows){
$rows = $query->fetch_all(MYSQLI_ASSOC);
forEach($rows as $row){
$output .= '<tr><td><button id="editbtn" type="button" class="btn btn-default"><span class="glyphicon glyphicon-pencil"></span></button></td><!--Clicking this button hides the output table and shows the edit div--></tr>';
}
$output .= '</tbody>';
So in the end, I have the table with the button created, but it does nothing when I click on it.

Why dont you try the same in order?
Like:
<script>
$(document).ready(function(){
$("#exit").click(function(){
$("#edit").hide();
$("#output").show();
});
$("#editbtn").click(function(){
$("#edit")).show();
$("#output")).hide();
});
});
</script>
This should work, always that you dont insert the edit button with ajax AND by definition, if you are using IDs, you are supposed to have only one element, if you have it between a foreach, it could cause you a problem.

It seems to be the jQuery selectors, they should be like this:
$("#edit").show();
Or in JavaScript:
document.getElementById('edit').styles.display = "none"; //or use addClass
PD: don't use two ready functions, put the listeners on the same one ;)
Edit:
Add a console.log in the function, and check out the console on the developer tools of your browser. Also try to comment the PHP query, except the output.

Related

AJAX Respond Not Catched by PHP file

We are on progress creating web page for live search and update file in bulk using JQUERY AJAX method. The files consist of index.php (for display to user and Javascript), and multiple_update.php (for fetch and update file in bulk). Initial reference we got is from here from webslesson website, but it does not have any reference for searching the record, hence we search for help for our journey.
Below is our index.php file
<div class="content-wrapper">
<div class="content-heading">
<div>STO Monitoring<small>Tables, one step forward.</small></div>
<div class="ml-auto"><input type="text" id="search" placeholder="Search" /></div>
<div id="display"></div>
<div class="ml-auto">
<button class="btn btn-primary btn-lg" type="button" data-toggle="modal" data-target="#myModalSmall"><i class="fas fa-plus-square"></i> Add Record</button>
</div>
</div>
<form method="post" id="update_form">
<div class="card">
<div class="card-body">
<table class="display" id="example" style="width:100%">
<thead>
<tr>
<th width="3%"></th>
<th width="5%">No</th>
<th width="15%">STO</th>
<th width="20%">PN</th>
<th width="8%">Qty</th>
<th width="10%">From</th>
<th width="10%">Dest</th>
<th width="15%">Status</th>
<th width="14%">Remark</th>
</tr>
</thead>
<tbody></tbody>
</table>
<div align="left">
<input type="submit" name="multiple_update" id="multiple_update" class="btn btn-info" value="Multiple Update" />
</div>
</div>
</div>
</form>
</div>
.....
Below is script inside our index.php, the one we suspect need troubleshoot at the moment.
<script>
function fill(Value) {
$('#search').val(Value);
if (name == "") {
$("#display").html("");
}
}
$(document).ready(function(){
function fetch_data()
{
$("#search").keyup(function() {
var name = $('#search').val();
if (name == "") {
//Assigning empty value to "display" div in "search.php" file.
$("#display").html("empty");
} else {
$.ajax({
url:"multiple_select.php",
method:"POST",
dataType:"json",
data: {
//Assigning value of "name" into "search" variable.
search: name
},
success:function(data)
{
var html = '';
for(var count = 0; count < data.length; count++) {
html += '<tr>';
html += '<td><input type="checkbox" id="'+data[count].num+'" data-num="'+data[count].num+'" data-sto="'+data[count].sto+'" data-pn="'+data[count].pn+'" data-qty="'+data[count].qty+'" data-supplant="'+data[count].supplant+'" data-dest="'+data[count].dest+'" data-stat="'+data[count].stat+'" data-remark="'+data[count].remark+'" class="check_box" /></td>';
html += '<td>'+(count+1)+'</td>';
html += '<td>'+data[count].sto+'</td>';
html += '<td>'+data[count].pn+'</td>';
html += '<td>'+data[count].qty+'</td>';
html += '<td><span class="btn btn-oval btn-primary">'+data[count].supplant+'</span></td>';
html += '<td><span class="btn btn-oval btn-warning">'+data[count].dest+'</span></td>';
html += '<td>'+data[count].stat+'</td>';
html += '<td>'+data[count].remark+'</td></tr>';
}
$('tbody').html(html);
}
});
}
});
}
fetch_data();
$(document).on('click', '.check_box', function(){
.....
</script>
We modify the AJAX to see if the input can be catched by the network, below is code for multiple_update.php
<?php
include('multiple_connection.php');
$name = $_POST['search'];
echo $name;
$query = "SELECT * FROM matreq_list, sto_list WHERE matreq_list.sto = sto_list.sto AND sto_list.sto LIKE '%$name%' LIMIT 5;
$statement = $connect->prepare($query);
if($statement->execute()) {
while($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
echo json_encode($data);
}
?>
We want to make every search is captured via AJAX, and respond from network will be live-reflected in our index file. Below is our expected final result (this result is without "LIKE" in mysql statement to show the result only) :
And we confirm AJAX can handle our input, below is the image :
--UPDATE-- Below is error messages :
Error messages
However, after we fired the input, nothing cames up in our index.php file. Network shows good respond, but the HTML is not responding the way we expected it to do. Please kindly advise us sir, what is wrong with our method and what should we fix?
Thank you and appreciate your kind help in our case
=====UPDATE=====
2020-07-02 : As mentioned by mr Nadir Baoun, tried to change the order of jquery.js and put it above the bootstrap.js, and somehow my table now able to search some part or whole part of the data.
Before :
.....
<script src="vendor/datatables.net/js/jquery.dataTables.js"></script>
<script src="vendor/datatables.net-bs4/js/dataTables.bootstrap4.js"></script>
<script src="vendor/datatables.net-responsive-bs/js/responsive.bootstrap.js"></script>
<script src="vendor/jquery/dist/jquery3.5.1.js"></script>
<script src="vendor/datatables.net/dist/js/jquery.dataTables.min.js"></script>
After ordered : I move the jquery to the top of all codes.
and below is network screenshot :
After change order of javascript
Surprisingly, this work well :D
The HTML isnt responding the way you want is because you have JavaScript errors thus your response code wont function accordingly.
First thing include your jquery file before bootstrap.
This should solve the " cannot read property fn of undefined " error.
Please update your post with debug messages in the success param of your ajax request after doing what i have mentionned above
After thoroughly reading on various articles with a guide from Mr Nadir Baoun, my problem is now fixed by changing the order of the script, putting the jquery script before the bootstrap script.
Similar answers also posted in stackoverflow website :
script order for jquery with bootstrap
Thank you :)

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

Change content of hidden div depending on which link is clicked

I'm building a website where the admin can make settings for the website. I would like the admin settings page to have a similar "feel" as the rest of the website, which has some nice looking jQuery features.
On the admin site there's a hidden div, which is shown when one of six links has been clicked. I'd like the content of the hidden div to change content before showing itself. I'm not sure how to do this. I could have a div box for every link on the page. But this becomes pretty cumbersome since I'd need to repeat my css and jquery for every link. I imagine that this, somehow, can be done with some javascript/jquery code that determines which link that was click and then decides which php function to call inside the hidden div. Then the php could "echo" out the content of the div, which then could be shown.
How could one do this?
My HTML/jQuery code is as follows:
--- The html links ---
<table id="settings">
<tr>
<td>
<img src="images/folder.gif" alt="" height="100"/>
</td>
<td>
<img src="images/folder.gif" alt="" height="100"/>
</td>
<td>
<img src="images/folder.gif" alt="" height="100"/>
</td>
----- The Hidden div -----
<div id="dashboard_box">
<div class="dashboard_inside">
<form action="#" method="post">
<p style="font-size:20px; font-weight: bold;">Change color</p>
</br>
<fieldset>
<? load_content1();?>
</fieldset>
</form>
</div>
</div>
---- jquery code (working)----
var mouse_is_inside = false;
$(document).ready(function() {
$(".action").click(function() {
var loginBox = $("#dashboard_box");
if (loginBox.is(":visible"))
loginBox.fadeOut("fast");
else
loginBox.fadeIn("fast");
return false;
});
$("#dashboard_box").hover(function(){
mouse_is_inside=true;
}, function(){
mouse_is_inside=false;
});
$("body").click(function(){
if(! mouse_is_inside) $("#dashboard_box").fadeOut("fast");
});
});
You probably want to use ajax to load the content from the server. Take a look at jquery's .load() method: http://api.jquery.com/load/
You could include a data attribute per link:
<a class="action" data-content="content.php?method=load_content1"></a>
<a class="action" data-content="content.php?method=load_content2"></a>
js would look something like this:
$(".action").on('click', function() {
$("#dashboard_box fieldset").load($(this).data('content'), function() {
var loginBox = $("#dashboard_box");
if (loginBox.is(":visible"))
loginBox.fadeOut("fast");
else
loginBox.fadeIn("fast");
}
return false;
});
Then, in your content.php file you could check the method parameter in the url to determine what content to return.
My php is a little rusty, but something like this:
<?
call_user_func($_GET['method']); // i'm not sure how safe this is. you may want to be more explicit
?>
You can just add data attribute in each of your link's
<a href="#" data-url="content1.php" ..
Then on click of any of the a you can get the php to be called.
$('a').on('click',function(){
var phpFunctionToCall = $(this).data('url');
});
You probably need to make ajax call to load content into your fieldset As this <? load_content1();?> run's on server and javascript have no control over it.
Thanks for all the help. this is what I ended up doing.
--- HTML ---
<a class="action" data-content="content.php?method=load_content2"></a>
---Jquery---
var mouse_is_inside = false;
$(document).ready(function() {
$(".action").click(function() {
var phpFunctionToCall = $(this).data('content');
$('#indhold').load(phpFunctionToCall);
var loginBox = $("#dashboard_box");
if (loginBox.is(":visible"))
loginBox.fadeOut("fast");
else
loginBox.fadeIn("fast");
return false;
});
$("#dashboard_box").hover(function(){
mouse_is_inside=true;
}, function(){
mouse_is_inside=false;
});
$("body").click(function(){
if(! mouse_is_inside) $("#dashboard_box").fadeOut("fast");
});
});
--- PHP (shortened)---
function load_settings_panel($settingOnRequest) {
return $settingOnRequest;
}
$result = call_user_func('load_settings_panel', $_GET['method']);
echo($result);

How to close modal window with this jquery function?

Below is the Html button and javascript function I have which closes a modal window:
<button type="button" id="close" onclick="return parent.closewindow();">Close</button>
function closewindow() {
$.modal.close();
return false;
}
Now the code above does close the modal window which is fine.
But I want to know how to write the code by using this function and html button below:
<button type='button' class='add'>Add</button>
$(document).on('click', '.add', function(){
$.modal.close(); ;
return true;
});
The above code does not close the modal window, why is this? Both these codes are on the same page by the way.
I am using simplemodal developed by eric martin
UPDATE:
Below is full code (QandATable2.php) but it is still not closing modal window when clicking on "Add" button:
$(document).ready(function(){
$('.add').on('click', function(){
//close modal window when user clicks on "Add" button (not working)
$.modal.close();
});
});
function plusbutton() {
// Display an external page using an iframe
var src = "previousquestions.php";
$.modal('<iframe src="' + src + '" style="border:0;width:100%;height:100%;">');
//Opens modal window and displays an iframe which contains content from another php script
return false;
}
function closewindow() {
$.modal.close();
return false;
//closes modal window when user clicks on "Close" button and this works fines
}
...HTML
<table id="plus" align="center">
<tr>
<th>
<a onclick="return plusbutton();">
<img src="Images/plussign.jpg" width="30" height="30" alt="Look Up Previous Question" class="plusimage" name="plusbuttonrow"/>
</a>
<span id="plussignmsg">(Click Plus Sign to look <br/> up Previous Questions)</span>
</th>
</tr>
</table>
Below is the full code which displays all of the information that goes into the modal window (this is in previousquestions.php script). This includes both "Add" and "Close" buttons:
<div id="previouslink">
<button type="button" id="close" onclick="return parent.closewindow();">Close</button>
</div>
<?php
$output = "";
while ($questionrow = mysql_fetch_assoc($questionresult)) {
$output .= "
<table>
<tr>
<td id='addtd'><button type='button' class='add'>Add</button></td>
</tr>";
}
$output .= " </table>";
echo $output;
?>
From what I remember from the comments, you wanted to close the modal when clicking in an add button inside the modal right?
$(document).ready(function(){
$('.add').on('click', function(){
$.modal.close();
});
});
​
I made your first example (before your question edit) work, take a look at this JSFiddle.
Be careful with the order you show/hide elements and wrap your function inside the $(document).ready() to prevent the code execution before the DOM is loaded.
If you don't manage to adapt your page to work similarly to my fiddle, you should post more from your page's code as there'd probably be something causing the plugin to don't work properly (or switch to another modal plugin).
edit: You're using an iframe, that's why you can't access the parent window's defined functions from the iframe's scope directly. You could try using the window.opener to access your parent window's scoped functions, or, to solve all and any window scope problem:
Replace
$.modal('<iframe src="' + src + '" style="border:0;width:100%;height:100%;">');
With
$.modal('<div id="modal" style="border:0;width:100%;height:100%;">');
$('#modal').load(src);
This will load content to the div dynamically through Ajax, which is a better approach and resolves any window scope problems which you were facing.
Either that or switch to a modal plugin which supports loading pages directly to it, for instance, colorbox.
EDIT
Now with your full code it was easy to find a solution, simply add onclick='parent.closewindow();' to your add button in your PHP:
<td id='addtd'><button type='button' class='add' onclick='parent.closewindow();'>Add</button></td>
This way, it'll re-use the existing closewindow function and discard the .on binding for the .add buttons. :)

How to add more divs in jQuery

I am trying to add a new div to the page when you click on NEW DIV?
How could I do this? Can someone point me in the right direction?
More example code is always helpful, but I'll try to give you some basics.
<div id="Content">
<button id="Add" />
</div>
$(function () {
$('#Add').click(function () {
$('<div>Added Div</div>').appendTo('#Content');
});
});
There are a bunch of different ways, it depends on what you want to do. A simple way is like this:
$('#id').html('<div>Hello</div>')
Which replaces the inner html of item with id 'id' with "Hello". So this:
<div id='id'>Old Html </div>
Would become:
<div id='id'><div>Hello</div></div>
And this:
$('#id').after('<div>Hello</div>')
Would transform the "Old Html" into this:
<div id='id'>Old Html</div>
<div Hello </div>
Check out www.visualjquery.com and select the Manipulation button. It gives you more than you could need to know in an easy to explore fashion.
Make sure to use the $(document).ready function in jQuery. You need this to "run" the script once your page is loaded and enable the action that is being called on this dummy button to append a new div to an existing div.
You can also use this to append anything you'd like to other elements on the page by using jQuery selectors such as .class or #id.
<div id="Content">
<button id="Add" />
</div>
$(document).ready(function() {
$('#Add').click(function () {
$('<div>Added Div</div>').appendTo('#Content');
});
});
Another useful option is to replace the contents of a tag with jQuery. You can do this using the .html() function.
<div id="Content">
<p id="changed">Hello World!</p>
<button id="change_content" />
</div>
$(document).ready(function() {
$('#change_content').click(function () {
$('#changed').html('Goodbye World');
});
});
Hope this helps!

Categories