Passing variables to a bootstrap modal form - php

I have a table that shows film reviews stored in a mysql database. Each of these reviews can be edited with a form that resides within a bootstrap modal. The problem I have is I can't understand how to give each form within the modal a unique ID. At the moment the modal only ever echoes varibales from the first row of reviews in the database. Many thanks.
The Jquery
<script type="text/javascript">
//Edit Review
$(document).ready(function(){
$(".editReview").click(function (e) {
$('#myModal').modal({
e.preventDefault();
var username = $(this).data("username");
var film_id = $(this).data('filmid');
var id = $(this).data('id');
var review = $(this).data('review');
$.post('ajax_editReview.php', {username: username, film_id: film_id, id: id, review: review},
function(data){
$('#myModal').modal('hide');
$("#message").html(data);
$("#review").val('');
$("#message").fadeIn(500);
$("#message").fadeOut(2500);
});
return false;
});
});
</script>
The Form
<div class="container">
<?php
$sql = "SELECT * FROM user_reviews WHERE username='$username' ORDER BY DATE desc";
$result = $db_conx->query($sql);
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$film_id = $row['film_id'];
$review = $row['review'];
$movie = $tmdb->getMovie ($film_id);
echo '
<div class="row">
<div class="col-md-1">
<img id="image1" src="'. $tmdb->getImageURL('w150') . $movie->getPoster() .'" width="80" />
</div>
<div class="col-md-4">
<h3>
' . $movie->getTitle() .'
</h3>';
<p>
'.$review. '
</p>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-success btn-xs pull-right" data-toggle="modal" data-id="'.$id.'" data-username="'. $username.'" data-filmid="'.$film_id .'" data-target="#myModal">edit review</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><h3> Edit your review for '. $movie->getTitle().'</h3></h4>
</div>
<div class="modal-body">
<form>
<div class="editReview">
<div class="form-group">
<label for="review">Review:</label>
<textarea class="form-control" rows="5" id="review" placeholder="'. $review.'" name="review"></textarea>
<input type="hidden" id="username" name="username" value="'.$username.'">
<input type="hidden" id="film_id" name="film_id" value="'. $film_id.'">
<input type="hidden" id="film_title" name="film_title" value="'.$movie->getTitle.'">
<input type="hidden" id="id" name="id" value="'.$id.'">
</div>
<button type="submit" id="FormSubmitReview" data-dismiss="modal" class="btn btn-danger btn-sm pull-right">Save Review</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-7">
</div>
</div>';
}
?>

You need to have the modal only once on your page and it seems like you a creating a new one for every review, you don't need to do that, just output it once.
You then need to use the event show.bs.modal like so.
$('#myModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var username = button.data("username");
var film_id = button.data('filmid');
var id = button.data('id');
var review = button.data('review');
....
});

Related

How to send a jQuery ID to Bootstrap Modal to use it in PHP function?

I know there are lots of similar posts but nothing really helps me. I'm trying to run a PHP function in Bootstrap Modal with two parameters, one of the parameter is a row ID that needs to go from jQuery.
I can send it and display it in a div id but how can I convert this parameter for a PHP function?
jQuery
$(document).ready(function() {
$("a").click(function(){
var hrefs = $(this).attr("href");
$("#modal_form").attr('action',hrefs);
var ids = hrefs.split("=").pop();
$("#sid").html(ids);
});
});
Bootstrap Modal
<!-- Update Record Modal -->
<div class="modal fade" id="updateModal" tabindex="-1" aria-labelledby="updateModalLabel" aria-hidden="true">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="updateModalLabel">Update Translation</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form action="translation.php" id="modal_form" method="post">
<div class="modal-body">
<div id="sid"></div> /* I'm getting the right ID here*/
<?php selectedTranslation($dbh, $ids); ?> /*I need to run this function*/
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" name="update" class="btn btn-primary">Save changes</button>
</div>
</form>
</div>
</div>
</div>
php function
function getAllTranslationById($dbh, $id){
...
<?php
$sqlSelect = "SELECT * FROM xxxx";
$result = mysqli_query($dbh, $sqlSelect);
while ($row = mysqli_fetch_array($result)) {
?>
<tr>
<td><input type="text" class="form-control" value="<?php echo $row['swrd_text'] ?>" readonly="readonly"></td>
<td><input type="text" class="form-control" value="<?php echo $row['swrd_context'] ?>" ></td>
<td><img alt="Link" src="images/edit.png" title="Update this row"></td>
</tr>
<?php }?>
</table>
<?php }
php function
function selectedTranslation($dbh, $sid){
....
<?php
$sqlSelect = "SELECT * FROM xxxx ";
$result = mysqli_query($dbh, $sqlSelect);
while ($row = mysqli_fetch_array($result)) {
?>
<tr>
<td><input type="text" class="form-control" value="<?php echo $row['swrd_text'] ?>" readonly="readonly"></td>
<td><input type="text" class="form-control" value="<?php echo $row['swrd_context'] ?>" ></td>
</tr>
<?php }?>
</table>
<?php }?>
Its just impossible like the way you want
So what you can do instead?
Use Ajax.
<div class="modal-body">
<div id="sid"></div> /* I'm getting the right ID here*/
<div id="ajaxResult"></div>
</div>
// JS Codes
$(document).ready(function() {
$("a").click(function(){
var sid = ""; // set your `sid` here
$.ajax({
url: "/url_here", //url to your PHP page
type: "post",
data: {id: sid},
success: function(data) {
$("#ajaxResult").html(data); //result html
}
});
});
});

How to pass value from other table in form modal bootstrap

I created a modal form to update the record with storage field that has an option and have to be taken from another table but if storage data already exist in the database then show existing data.
I did this code but it cannot show existing data.
If I change the code for "storage" to : ABC then it can show existing data in database.
<?php
// to connect database
include '../connection/connect.php';
$query_storage = mysqli_query ($connect, "SELECT * from storage ORDER BY
storages ASC");
?>
//code for modal bootstrap
<div id="add_data_Modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Reagent Detail Information</h4>
</div>
<div class="modal-body">
<form method="post" id="insert_form">
<label>Storage</label>
<select class="form-control" name = "storage" id="storage" required >
<?php while($row = mysqli_fetch_assoc($query_storage)){?>
<option value="<?php echo $row['id_storage']; ?>">
<?php echo $row['storages']; ?></option>";
<?php }
?>
</select>
<br />
<label>Min Stock</label>
<input type="text" name="min_stock" id="min_stock" class="form-control" />
<br />
<input type="hidden" name="reagent_id" id="reagent_id" />
<input type="submit" name="insert" id="insert" value="Insert" class="btn btn-success" />
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$('#add').click(function(){
$('#insert').val("Insert");
$('#insert_form')[0].reset();
});
$(document).on('click', '.edit_data', function(){
var reagent_id = $(this).attr("id");
$.ajax({
url:"php/reagent_master/fetch.php",
method:"POST",
data:{reagent_id:reagent_id},
dataType:"json",
success:function(data){
$('#storage').val(data.storages);
$('#min_stock').val(data.min_stock);
$('#max_stock').val(data.max_stock);
$('#reagent_id').val(data.id_reagent_master);
$('#insert').val("Update");
$('#add_data_Modal').modal('show');
}
});
});
get data from database by stroge and then if record found with this storage show your error message. Storage already exists

PHP-jQuery-AJAX: How to POST values while using a form in Modal

I'm having an issue passing input and textarea values from a form in modal to AJAX so I can pass them to php.
The input field and textarea values are coming up blank when I submit the form in modal and jquery is not displaying any errors. It simply POST an empty (blank) string for each element.
for example, it shows something like this.
subject=&content=
in the dialog box, I load a name and an ID and both POST successfully but the input values which are not loaded with the form, are not being sent. I understand that the name and ID do POST because they are loaded on DOM along with the form but I do not know how to pass values that are not loaded along with the form in modal.
This is a sample of the form.
<?php while($row = mysqli_fetch_array($res)){
//row data for each post
$r_id = $row['r_id'];
$name = $row['name'];
?>
<div id="m_f_box" class="modal fade msg-box-custom" tabindex="-1" data-width="400">
<div class="modal-header-custom">
<h5 class="modal-title">Send to <span><?php echo $name ?></span></h5>
</div>
<form id="user_m_form" name="user_m_form" action="#" method="POST">
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<div id="s_row" class="col_full">
<h5>Asunto</h5>
<input id="m_subject" name="m_subject" class="required sm-form-control" type="text" maxlength="40"></input>
</div>
<div id="m_row" class="col_full">
<h5>Mensaje</h5>
<textarea id="m_content" name="m_content" class="required sm-form-control" type="text"></textarea>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="send_m" name="user_m_form" class="button button-mini button-blue" value="<?php echo $r_id ?>">Send</button>
<button type="button" id="can_m" name="can_m" data-dismiss="modal" class="button button-mini button-blue">Cancel</button>
</div>
</form>
</div>
<?php } ?>
This is a sample of the jquery/ajax call.
<script type="text/javascript">
$(document).on('click', '#send_m', function(e){
e.preventDefault();
var r_id = $('#send_m').val();
var subject = $('#m_subject').val();
var content = $('#m_content').val();
//var form_data = $('#user_m_form').serialize(); test with serialized form data.
//alert(subject); test what is being sent as an alert
//console.log(subject); test what is being sent to view in console
$.ajax({
type:'POST',
url:'test_file.php',
data: { r_id : recipient_id,
subject : subject,
content : content,
},
cache: false,
success:function(res){
//do some stuff
}
});
return false;
});
</script>
Any ideas on why and/or how to POST these values?
Thanks in advance,
Note: Excuse the formatting for the HTML portion. It's hard to properly format everything using a phone.
Note: If you are trying to define multiple modal using while loop,
Your HTML
<div id="m_f_box" class="modal fade msg-box-custom" tabindex="-1" data-width="400">
<div class="modal-header-custom">
<h5 class="modal-title">Send to <span><?php echo $name ?></span></h5>
</div>
<form id="user_m_form" name="user_m_form" action="#" method="POST">
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<div id="s_row" class="col_full">
<h5>Asunto</h5>
<input id="m_subject_<?php echo $row['r_id']; ?>" name="m_subject" class="required sm-form-control" type="text" maxlength="40"></input>
</div>
<div id="m_row" class="col_full">
<h5>Mensaje</h5>
<textarea id="m_content_<?php echo $row['r_id']; ?>" name="m_content" class="required sm-form-control" type="text"></textarea>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="<?php echo $row['r_id']; ?>" name="user_m_form" class="button button-mini button-blue send" value="<?php echo $r_id ?>">Send</button>
<button type="button" id="can_m" name="can_m" data-dismiss="modal" class="button button-mini button-blue">Cancel</button>
</div>
</form>
</div>
<?php } ?>
Your Script
<script type="text/javascript">
$(document).on('click', '.send', function(e){
var r_id = (this).attr('id');
var subject = $('#m_subject'+id).val();
var content = $('#m_content'+id).val();
//......
//.......
});
</script>
Note: You just need to understand the JQuery selector (ID and Class). See the difference between #ID and .Class selectors in Jquery.
You are generating multiple Modal with same ID and try to get those field values using IDs (selector). But the IDs for each modal input fields must be unique to get the value. and for on click operation the button must have unique ID or you just need to define class as above code has.
See how I have defined class for click button and getting ID for each modal. Modal must be unique in the sense of their field.
Example done POST request with Ajax call on ModalBox
My View page code:
<div class="panel panel-default">
<div class="panel-body">
<p class="text-danger">There are total <span class="text-bold">{{ sizeof($data) }}</span> Departments.</p>
<table class="table" id="department-data">
<tr>
<th>#</th>
<th>Name</th>
<th>Edit</th>
<th>Delete</th>
<th>Manage</th>
</tr>
<?php $order = 0; ?>
#foreach($data as $key)
<tr>
<td>{{ ++$order }}</td>
<td id="department_name">{{ $key->title }}</td>
<td>
<a href="#">
<button class="btn btn-default edit-department" data-toggle="modal" data-target="#updateDepartmentModel" id="{{ $key->id }}"><i class="fa fa-pencil"></i></button>
</a>
</td>
<td>
<button id="{{ $key->id }}" class="btn btn-danger delete-btn" data-toggle="modal" data-target="#delete-department"><i class="fa fa-trash"></i></button>
</td>
<td>
<a href='program/{{ $key->id }}' id="delete-id">
<button class="btn btn-primary"><i class="fa fa-cog"></i></button>
</a>
</td>
</tr>
#endforeach
</table>
</div>
</div>
Modals on the same page:
<!-- Add New Department Modal -->
<div class="modal fade" id="newDepartmentModel" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add New Department</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form action="{{ url('department/create') }}" method="POST">
{{ csrf_field() }}
<div class="modal-body">
<div class="form-group">
<label for="title">Department Name:</label>
<input type="text" class="form-control" id="title" name="title">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Add</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
<!-- ./Model -->
<!-- Update Department Modal -->
<div class="modal fade" id="updateDepartmentModel" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Update a Department</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form>
<div class="modal-body">
<div class="form-group">
<label for="old-title">Department Name:</label>
<input type="text" class="form-control" id="old-title" name="title">
</div>
</div>
<div class="modal-footer">
<button type="submit" id="edit-dept" class="btn btn-primary edit-dept">Edit</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
<!-- ./Model -->
Here is Script:
<script type="text/javascript">
var token = '{{ Session::token() }}';
var url = '{{ route('department/edit') }}';
var dept_id = '';
// Setup Ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
// Update the department
$(document).on('click', '.edit-department', function () {
var department_id = $(this).attr('id');
console.log(department_id);
dept_id = department_id;
$.get('department/'+department_id, function (data) {
$('#old-title').val(data.title);
console.log(data);
});
});
// Handle Post Request (Edit Department)
$(document).ready(function () {
$('#edit-dept').click(function () {
$.ajax({
method: 'POST',
url: url,
data: { id: dept_id, title: $('#old-title').val(), _token: token},
dataType: 'JSON'
}).done(function (data) {
//console.log(data);
});
});
});
</script>
Routes is:
Route::post('department/edit', function (\Illuminate\Http\Request $request){
$id = $request->input('id');
$title = $request->input('title');
DB::table('departments')->where('id', $id)->update(array('title' => $title));
return redirect('department')->with('alert_info', 'Department was successful Update!');})->name('department/edit');
Put this line on page Head:
<!-- csrf for meta -->
<meta name="csrf-token" content="{{ csrf_token() }}" />
And in Controller Create and Get routes:
Route::post('department/create', 'DepartmentController#store');
Route::get('department/{id}', 'DepartmentController#showById');
And these definitions:
public function store(StoreDepartmentPostRequest $request)
{
$department = new Department;
$department->title = $request->input('title');
$department->timestamps = time();
$department->save();
return redirect('department')->with('alert_success', 'Department was successful added!');
}
public function showById($id){
$data = Department::findOrFail($id);
return response()->json($data);
}

using _get to get the id from hidden input and to insert it into the database

i use modal for validation
<div class="modal-body">
<div class="row">
<div class="col-lg-8">
<div class="form-group margin-top-20">
<p><strong>Do you want to join this group?</strong></p>
</div>
</div><br>
<button type="button" name="join" id = "join" class="btn btn-black">Join</button>
<button type="button" class="btn btn-black" data-dismiss="modal">Cancel</button>
<?php
$db = new Group($conn);
$gid = '';
if(isset($_POST['join'])){
if ( !empty($_GET['gr_id'])) {
$gid = $_GET['gr_id'];
$inserted = $db->insertgroup($session_id, $gid);
?>
<script>
window.location = '../views/groups.php';
</script>
<?php
}
}
?>
</div>
</div>
using this script im getting the id of a certain group and insert it into my db but it seems that the gid is not getting fetch so what happens is that when i tried to click the join button
<script>
window.location = '../views/groups.php';
</script>
this script supposed to run but did not..
im getting the ID from here:
<?php
$res = $db->g_viewlist();
$gid ='';
foreach ($res as $key => $value){
$gid = $value['g_id'];
?>
<div class="col-lg-12" align="center" style="border:1.5px solid #59960b;padding-bottom:10px;padding-top:10px;">
<button class="btn2 btn-2" data-toggle="modal" data-target="#joinModal" style="padding: 2px 2px; margin-left:50%"><strong> Join</strong></button>
<input id="gr_id" type="hidden" name="gr_id" value="<?php echo $gid ?>">
</div>
<?php
}
?>
the gid is from outside the modal form.. is there a way to fetch the id for me to be able to insert it into my db?.
You method of doing is wrong. You cannot get the gr_id value using $_GET method and $_POST.. one more you are posting any form in modal therefore $_POST will not work.
Calling Modal HTML :
<button class="btn2 btn-2 join" data-id="<?php echo $value['g_id']; ?>"
data-toggle="modal" data-target="#joinModal" style="padding: 2px 2px;
margin-left:50%"><strong> Join</strong></button>
I have added new class 'join' and added a attribute 'data-id'.
Revise your modal structure code :
<div class="modal fade" id="joinModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" data-keyboard="false">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" aria-label="Close" data-dismiss="modal"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal Heading</h4>
</div>
<div class="modal-body">
Do you want to join this group?
</div>
<div class="modal-footer">
<button type="button" name="join" id = "join" class="btn btn-black" onclick="joinGroup()">Join</button>
<button type="button" class="btn btn-black" data-dismiss="modal">Cancel</button>
<input type="hidden" name="join_id" id="join_id">
</div>
</div>
</div>
</div>
I have added <input type="hidden" name="join_id" id="join_id"> and onclick="joinGroup()" to store the join_id value and save it the database respectively.
Using javascript click function, you can assign the data-id value to input hidden field of modal box. After that when someone clicks on JOIN button ajax will trigger and save the data into database.
<script type="text/javascript">
$('.join').click(function(){
var id = $(this).attr('data-id');
$('#join_id').val(id);
});
function joinGroup(){
var join_id = $('#join_id').val();
$.ajax({
url:"insertvalue.php", // ajax call to insert data
data: 'join_id=' + join_id,
success:function(data) {
window.open('your url','_self');
}
});
}
</script>

How to update data using modal with ajax, php and mysql?

I want to update data using modal with ajax in PHP. I am beginer, plz tell me where is my mistake .
HTML Code
<button type="submit" class="btn btn-success" data-toggle="modal" data-cphone='.$row['country_phon'].' data-cname='.$row['country_name'].' >Update</button>';
<div id="myModal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Update Country</h4>
</div>
<form action="" method="post">
<div class="modal-body">
<input type="text" id="cn" name="pcountry">
</div>
<div class="modal-body">
<input type="text" id="cph" name="pphone">
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary updt" name="updatecountry" >Save</button>
JS Code: Here when I click on Button, modal appears with the values fetched from database with the help of jquery.
<script>
$(document).ready(function(){
$(".btn").click(function(){
var cphone =$(this).data('cphone');
var cname = $(this).data('cname');
$("#cph").val(cphone);
$("#cn").val(cname);
$("#myModal").modal('show');
});
});</script>
JS code : This is ajax code . I want to update the text of textbox.
<script>
$(".updt").click(function(e){
e.preventDefault();
var cnt = $("#myModal").find("input[name='pcountry']").val();
var cp = $("#myModal").find("input[name='pphone']").val();
$.ajax({
dataType: 'json',
type:'POST',
url: 'test.php',
data:{pcountry:cnt, pphone:cp},
})
)};
</script></div>
PHP Code :
<?php
if(isset($_POST['updatecountry']))
{$country1 = $_POST['pcountry'];
$phone1 = $_POST['pphone'];
echo $country1;
echo $phone1;
echo "Updated Successfully";
mysqli_query($conn,"update country set country_name='$country1' , country_phon='$phone1' where country_id=18");
mysqli_close($conn);
}?>
On view btn class use for update and save. I suggest you please use different class name or id.
<button type="submit" class="form_update btn btn-success" data-toggle="modal" data-cphone='.$row['country_phon'].' data-cname='.$row['country_name'].' >Update</button>';
JS changes
<script>
$(document).ready(function(){
$(".form_update").click(function(){
var cphone = $(this).attr("data-phone");
var cname = $(this).attr("data-cname");
$("#cph").val(cphone);
$("#cn").val(cname);
$("#myModal").modal('show');
});
});
</script>
Hope this code is workinf fine.

Categories