I know there have been tons of questions about setting a PHP session from JQuery and then returning it to JQuery. And I have looked at all of them and still cannot figure out why my code doesn't work. I am trying to use a modal to set a PHP session variable on a back end PHP page and then display it in another modal using jquery, but nothing gets returned.
Here is my sending modal:
<div id="sendingModal" class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-md" role="document">
<div class="modal-content">
<div class="modal-body">
<button id="testSession" type="button" class="btn btn-secondary">Session Test</button>
</div>
</div>
</div>
and here is my back end php:
<?php
session_start();
$_SESSION['testInput'] = $_POST['inputData'];
?>
and here is my receiving modal:
<div id="receivingModal" class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-md" role="document">
<div class="modal-content">
<div class="modal-body">
<div id="testDiv"></div>
</div>
</div>
</div>
Here is my JQuery:
$(document).ready(function() {
$('#testSession').on('click',function(e){
var testData = 'testing 123';
$.post("backendSession.php", {"inputData": testData});
$('#testSession').html(<?=$_SESSION['testInput']?>);
$('#testModal').modal('show');
});
});
What am I doing wrong?
You only have a small issue here, and its a simple fix based on the code you provided. You MUST return the new data back during the ajax call, or you will not be able to use it (not until, that is, a whole new page refresh).
First up, add to your backendSession.php:
<?php
session_start();
$_SESSION['testInput'] = $_POST['inputData'];
echo htmlspecialchars( $_SESSION['testInput'] );// new bit
?>
Then adjust your .post usage as follows:
$(document).ready(function() {
$('#testSession').on('click',function(e){
var testData = 'testing 123';
$.post("backendSession.php",
{"inputData": testData},
function( rawdata ) { // add return handler callback
$('#testDiv').html( rawdata ); // use the return data
$('#testModal').modal('show'); // show the modal
}
);
});
});
Now that is the basic change to make what you were wanting to do. However you may want to deal with JSON return data in the future, if you plan on needing more than just an echo of the input. An example of that will go beyond the question though ;)
As another side: You probably will want to sanitize that post input. I know what you provided was a minimal example, but I just wanted to mention it. As simply echoing out the raw user input, back into a page, can open up some XSS attack vectors.
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');
}
I am trying to load the comments of a particular post on a modal. For this I need to pass the post id to the modal and then fetch the corresponding comments.
The modal is triggered by the following:
<a class="xyz" data-toggle="modal" data-target="#compose-modal" data-id="<?php echo $list[$i]->getID(); ?>">View Comments</a>
And the modal is defined at the bottom of the page as follows:
<div class="modal fade" id="compose-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<!-- here i need to use php to fetch the comments using post id -->
</div>
</div>
</div>
PHP is executed before the page is returned to the browser. Once you see the page in your browser, all the PHP has already been executed. What you probably want to do is use AJAX. Here is a general outline of how you would do it:
Have a PHP page that takes the ID and returns the data you want as a JSON.
api.php
$theId = $_POST['theId'];
//Get the information you want, and turn it into an array called $data
header('Content-Type: application/json');
echo json_encode($data);
In your html, you should trigger the modal using an onclick attached to the "View Comments":
<a class="xyz" onclick = "launch_comment_modal(<?php echo $list[$i]->getID(); ?>)">View Comments</a>
then,at the bottom with your other javascript:
<script>
$('#compose-modal').modal({ show: false});
function launch_comment_modal(id){
$.ajax({
type: "POST",
url: "api.php",
data: {theId:id},
success: function(data){
//"data" contains a json with your info in it, representing the array you created in PHP. Use $(".modal-content").html() or something like that to put the content into the modal dynamically using jquery.
$('#compose-modal').modal("show");// this triggers your modal to display
},
});
}
</script>
Just pass the content via ajax with a php page
and echo the content in the modal
I have just made an Esiest way to pass php dynamic data to Bootstrap modal in Laravel > 5
currently i am using larvel 7.
This is HTML DOM using onclick event, simplly call the JavaScript function
<li>Some Option</li>
& pass Dynamic Variable.
This is JavaScript Code
<script type="text/javascript">
function showModal(id=0){
$('#collectionModal').modal('show');
// here is the id of that element where do you want to display / have the passed value
// in my case i am taking in a hidden input which id is = bookID , i am using a form in my modal that why
$('#bookID').val(id);
}
</script>
This is modal's HTML where i am getting the passed value like:
<input type="hidden" name="book_id" id="bookID" value="">
and finally i am submiting the form in modal using javaScript & Ajax.
Hey folks I have content being displayed on a page by using jQuery and Ajax to query my php page. On click I check for all elements with the class edit. I am trying to then grab the unique id of the link that was chosen. I know it should be this.id but it returns nothing. Does anyone have any insight on how to dynamically check the clicked link and get a stored value in any way?
The bellow works for getting a link clicked. but cannot get the id still.
$("body").on("click", ".edit", function(){
var id = this.id;
alert($(this).val());
});
Here is the HTML that is being put on the page via Ajax
<div class="row">
<div class="small-2 large-2 columns">3</div>
<div class="small-10 large-6 columns">Andrew</div>
<div class="small-6 large-2 columns">2013-08-12</div>
<div class="small-6 large-2 columns edit"> Edit </div>
</div>
Solved solution was to use '.edit > a' as the selector. I had edit as the class of the div, not the anchor tag. Thanks for all the help folks!
The sample HTML helped:
You need to select the anchor within the .edit div.
$("body").on("click", ".edit > a", function () {
var id = this.id;
alert(id);
});
JSFiddle: http://jsfiddle.net/QckbT/
Does this works ?
$("a.edit").on("click", function(){
alert($(this).val());
});
alert($(this).val());
relate to body, not to #id.
<a data-toggle="modal" href="msg_id=<?php echo $id; ?>#example" class="link_comment">Comment</a>
<div id="example" class="modal" style="display: none; ">
Your message ID is :
<?php
echo $msg_id = $_GET['msg_id'];
?>
</div>
When I try to mouseover to Comment link, in status URL : I can see the msg_id value. But When I try to click the comment link (I using Jquery modal), it can't be show the value of the link.
So my question, how can I do that to make the value of msg_id show in Jquery modal.
Thanks for your help.
Since you open #example div with jquery Modal, it dosen't reload the page, hence $_GET is empty.
You can achieve what your goal in at least 2 ways:
Use Ajax to load contents of #example div when link is clicked.
<a data-toggle="modal" href="<?php echo $id; ?>#example" class="link_comment">Comment</a>
<script type='text/javascript'>
$('.link_comment').click(function(e) {
e.preventDefault();
var id = $(this).attr('href');
$.get('givemycomments.php?id='+id, function(data) {
$('#example').html(data);
});
});
</script>
Load all possible contents when page is rendered with php. For example, you would have #example_1 , #example_2 divs. When link is clicked, get value of its ID, and fire Modal with correct div. edit: after writing example code i realized that if you have lots of comments, it can be quite heavy to load em all.