Passing PHP variable through pop-up link - php

I need to pass a variable through the link when calling a pop up window. When adding a variable like I normally would the names don't match up with the pop up window.
This is what I have:
<a data-toggle="modal" href="#allMessages?id=<?php echo $job['job_id']; ?>" class="btn btn-warning btn-sm btn-icon">
<i class="fa fa-unlock-alt"></i>View All Messages
</a>
<div class="modal fade" id="allMessages" tabindex="-1" role="dialog" aria-labelledby="allMessages" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header success">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="fa fa-times"></i></button>
<h4 class="modal-title">Reply</h4>
</div>
<?php
$getMessages = mysqli_query($mysqli,
"SELECT *
FROM messages
WHERE messages.job_id = $GET['id']
"
);
$messages = array();
while($message = mysqli_fetch_assoc($getMessages)) {
$messages[] = $message;
}
The problem is when I add the variable at the end of the button link #allMessages?id= it no longer calls the pop-up window.
Javascript:
$("[data-toggle='popover']").popover();
});
function load_page() {
var selected_page = document.getElementById("selected_page").value;
if (selected_page != "") {
window.location.href = selected_page
//Please note that the value recived,
//in this case selected_page,
//should be a valid url!
//Therefore the value of the
//<option> tag should be itself
//a url !
//ex.: <option value="page.php"> is valid
//<option value="page_1"> is not valid
}

I can't see this working.
The modal is already on the page, just invisible so any PHP queries would be done when the page is rendered, not when the modal is activated.
Personally I'd send the ID over in a data attribute, do the processing in an AJAX request and then push the results into the modal box.

Related

Bootstrap 5 Modal not receiving data from PHP with AJAX

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

Search Results display inside of modal

i have a basic search form # service.php
Currently the search results display # search.php
i want the results display # service.php inside modal "bootstrap" instate of moving to search.php
Thank you
service.php
<form class="input-group" method="post">
<input type="text" class="form-control" name="keyword" placeholder="search..." />
<span class="input-group-btn">
<button class="btn btn-primary" data-toggle="modal" data-target=".bs example-modal-lg" href="index.php"><i class="fa fa-search"></i></button>
</span>
</form>
<div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<!-- modal body -->
<div class="modal-body">
Search Results
</div>
<!-- /modal body -->
</div>
</div>
</div>
search.php
$page = 1;
if(isset($_GET['page'])){
$page = $_GET['page'];
}
$searchQuery = '';
if(isset($_GET['keyword'])){
$keyword = $_GET['keyword'];
$searchQuery = '(serviceTitle LIKE "%'.$keyword.'%" or serviceDescription LIKE "%'.$keyword.'%")';
}
// get total news rows
$countRset = mysql_query('SELECT COUNT(*) as Total FROM service where '.$searchQuery);
$countRows = mysql_fetch_assoc($countRset);
$countRows = $countRows['Total'];
// get news by page
$limitPerPage = 20;
$startPage = 0;
if($page>1){
$startPage = ($page-1)*$limitPerPage;
}
$newsRset = mysql_query('SELECT * FROM service where '.$searchQuery.' order by serviceID desc LIMIT '.$startPage.', '.$limitPerPage);
$news = array();
while($row = mysql_fetch_array($newsRset)){
array_push($news, $row);
}
?>
<?php foreach($news as $key=>$item){?>
<?php echo $item['serviceTitle']; ?> ......
<?php }?>
So display it inside a modal you should definitely need an ajax request.
So first is:
make your search.php returns a json encoded result
Based on your code above you can return the json encoded result like this:
return json_encode($news);
then grab the result using an ajax request
then display it by target the modal body element
You could choose an vanilla JS of Ajax or Jquery Ajax

How do I get my modal information to show, while trying to make it dynamic?

Trying to open a modal which should grab information from my database and present it onto the modal, after clicking on a specific image. The modal pops up, but it shows on the html inputs and none of the php inputs. How can i fix this? rental_id is the primary in the database table.
<?php
require_once '../core/init.php';
$id = $_POST['rental_id'];
$id = (int)$id;
$sql = "SELECT * FROM rental WHERE rental_id = '$id'";
$result = $db->query($sql);
$rental = mysqli_fetch_assoc($result);
?>
<!-- the div that represents the modal for the form -->
<?php ob_start();?>
<div class="modal fade" id="quote" tabindex="-1" role="dialog" aria-labelledby="quote" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button class="close" type="button" data-dismiss='modal' aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title text-center">Quote</h4>
</div>
<div class="modal-body">
<div class="container-fluid">
<div class="row">
<div class="col-sm-6">
<div class="center-block">
<img src="<?= $rental['img']; ?>" alt="<?= $rental['make']; ?>" class="w3-image img-responsive"/>
</div>...
and...
<script>
function detailsmodal(rental_id){
var data = {"rental_id" : rental_id};
jQuery.ajax({
url : <?php echo BASEURL;?> + 'includes/detailsmodal.php',
method : "post",
data : data,
success: function(data){
jQuery('body').append(data);
jQuery('#quote').modal('show');
},
error: function(){
alert("Something went wrong!");
}
});
}
</script>
Have you checked $id = (int)$id; ? is it set, ok with a value ?
Any return error message ? (SO question )
<?php
print_r($rental); /* seems ok when tested with ie: $id=3 */
$sql = " SELECT img, make FROM rental WHERE rental_id=? ";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $id);
$results = $stmt->execute();
$stmt->bind_result($img, $make);
$stmt->store_result();
while($stmt->fetch()){
echo"[ $img / $make ]";
}
?>
does it make a difference ?

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

Render View Via Bootstrap Modal

I need to use bootstrap modal to load form , how I can call bootstrap modal with parameters via link ?
View:
<?php echo CHtml::link(Yii::t('app','addaction'),'#myModal',array('class'=>'btn btn-primary','data-toggle'=>'modal')) ;?>
<br/><br/><br/>
<!-- Bootstrap modal dialog -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<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"><?php echo Yii::t('app','AddAction'); ?></h4>
</div>
<div class="modal-body">
<?php echo $this->renderPartial('_form', array('model'=>$model,'productId'=>$productId)); // I need $productId to by dynamic related to link
?>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
Controller :
public function actionCreate()
{
$model=new Actions;
$productId=intval($_GET['productId']);
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if(isset($_POST['Actions']))
{
$model->attributes=$_POST['Actions'];
$model->product_id=$productId;
if($model->validate()){
$model->save(false);
$message=Email::setJavaMessage('success',Yii::t('app','sm'),Yii::t('app','actionWasAdded'));
echo CJSON::encode(array('status' => 'success','message'=>$message));
Yii::app()->end();
}else{
$error = CActiveForm::validate($model);
if($error!='[]')
echo $error;
Yii::app()->end();
}
}
if(Yii::app()->request->getIsAjaxRequest())
echo $this->renderPartial('_form',array('model'=>$model,'productId'=>$productId),false,true);//This will bring out the view along with its script.
else
$this->render('create',array(
'model'=>$model,'productId'=>$productId));
}
So with above code form is work with validation also, the problem if I need to add dynamic parameters to link how to ?
For example : use it in CRGidview via update function then the $product_id will change for every row related to values in database .
I don't know if you already found a solution but here is how I would do it:
In your link add a parameter like "data-productId" (for example: CHtml::link('Addaction','#myModal',array('id'=>'link','data-toggle' => 'modal','data-productId'=>$id, 'class' => 'link'))).
Bind a javascript function to the click event on your link like this:
$("a#link").click(function()
{
var productId = $(this).data('productId');
//you can change the value of a form component like this
//in the below example I have a hidden input field whose val I want to change to be submitted with the form
$("input#FormId_idHiddenInput").val(productId);
$('#myModal').modal('show');
});
For this example to work you would have to move your form from the partial to your dialog file.
Let me know if this helps you or if there are other problems you encounter.

Categories