bootstrap modal textarea showing empty alert on click jquery - php

i have modal popup in loop with database values. In popup there is a reply textarea and i want to post that value using ajax. But i am getting empty value of textarea when i alert value on click event using jquery. Here is my code
CODE:
<?php
$sn=1;$rep=1;
foreach($view_queries as $q) {?>
Reply
?>
<!-- create reply model -->
<div id="create_reply<?php echo $rep;?>" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<form id="send_reply" method="post" antype="multipart/form-data">
<input type="hidden" name="query_id" value="<?php echo $q->query_id;?>" />
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Reply To Query</h4>
</div>
<div class="modal-body">
<label>Query:</label>
<p><?php echo ucfirst($q->query);?></p>
<div class="form-group">
<label>Reply:</label>
<textarea rows="3" name="mesg" id="<?php echo $sn;?>mesg" class="form-control"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" id="" data-target="<?php echo $sn;?>mesg" class="btn btn-default form_click">Reply</button>
</div>
</form>
</div>
</div>
</div>
<!-- create reply model ends -->
<?php $sn++; $rep++; }?>
HERE IS THE SCRIPT FOR CHECKING VALUE IN ALERT:
<script>
$(document).ready(function(){
$(document).on("click",".form_click",function(event){
event.preventDefault();
var a=$('#' + $(this).data('target')).text();
alert(a);
});
});
</script>

You should use .val() instead of .text(). text() get's the HTML contents of a HTML element. val() is used for getting contents of HTML inputs.
Also as Smit Raval already stated, id's should be unique.
You could give the fields an id with and index set in PHP.
So in every loop you increment the index and add that to your id values, like so:
id="<?=$index?>_mesg".
And in your button do:
<button type="button" data-target="<?=$index?>_mesg" id="" class="btn btn-default form_click">Reply</button>
And then in your jquery you can do var a=$('#' + $(this).data('target')).val();
See the added data-target in your button. And the $(this).data('target') in the jquery for retrieving the value of the target data attribute.

<script>
$(document).ready(function(){
$(document).on("click",".form_click",function(event){
event.preventDefault();
var a= $(this).parents("form.send_reply").find("textarea.mesg").text();
alert(a);
});
});
</script>
change id="mesg" to class="mesg" in your loop.Also make sure you don't repeat the same ID in your loop. Change id="send_reply" to class="send_reply"

Related

get value of input in modal popup loop using jquery

I have modal popup in loop with database values. The modal box contains a form which have hidden input value and a textarea to insert message. I am able to get the value of textbox with the help of stackoverflow.
Reference :
bootstrap modal textarea showing empty alert on click jquery
But when i alert the hidden value in alert box it does not change according to the loop in alert box. The value of hidden element is changing in loop when i check using inspect element but when i alert it, it is showing same value.
CODE:
<?php
$sn=1;$rep=1;
foreach($view_queries as $q) {?>
Reply
?>
<!-- create reply model -->
<div id="create_reply<?php echo $rep;?>" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<form id="send_reply" method="post" antype="multipart/form-data">
<input type="hidden" name="query_id" value="<?php echo $q->query_id;?>" />
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Reply To Query</h4>
</div>
<div class="modal-body">
<label>Query:</label>
<p><?php echo ucfirst($q->query);?></p>
<div class="form-group">
<label>Reply:</label>
<textarea rows="3" name="mesg" id="<?php echo $sn;?>mesg" class="form-control"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" id="" data-target="<?php echo $sn;?>mesg" class="btn btn-default form_click">Reply</button>
</div>
</form>
</div>
</div>
</div>
<!-- create reply model ends -->
<?php $sn++; $rep++; }?>
HERE IS THE SCRIPT FOR CHECKING VALUE IN ALERT:
<script>
$(document).ready(function(){
$(document).on("click",".form_click",function(event){
event.preventDefault();
var a=$('#' + $(this).data('target')).text();
var query_id=$('#query_id').val();
alert(query_id);
});
});
</script>
Easier option is use data-* attribute to persist query id as you are using data-target
<button type="button" data-id="<?php echo $q->query_id;?>" data-target="<?php echo $sn;?>mesg" class="btn btn-default form_click">Reply</button>
Then you can easily use
var query_id= $(this).data('id');
Problem with your implementation is that You have not specified ID of hidden field, thus must be getting undefined while fetching value.
<input type="hidden" name="query_id" value="<?php echo $q->query_id;?>" />
To get its value use DOM relationship of current element.
Use .closest(selector) to traverse up to common parent then use .find() to get the element using Attribute Equals Selector [name=”value”]
Relevant code
var query_id= $(this).closest('form') //target common parent
.find('[name=query_id]') //target element
.val();
$(document).ready(function() {
$(document).on("click", ".form_click", function(event) {
event.preventDefault();
var query_id = $(this).closest('form') //target common parent
.find('[name=query_id]') //target element
.val();
console.log(query_id);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="send_reply" method="post" antype="multipart/form-data">
<input type="hidden" name="query_id" value="1" />
<div class="modal-footer">
<button type="button" id="" class="btn btn-default form_click">Reply</button>
</div>
</form>

How to post data in ajax from bootstrap modal?

I have a problem in bootstrap modal. I want to add caption of an image using bootstrap model.
For the modal section I have done this,
<!-- Modal content Start-->
<form method="POST">
<!-- Modal -->
<div class="modal fade" id="myModal<?php echo $i;?>" role="dialog">
<input type="hidden" id="image_id" name="image_id" value="<?php echo $Array->image_id;?>" >
<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">Image Caption</h4>
</div>
<div class="modal-body">
<input type="text" id="caption" name="caption" placeholder="Caption" value="<?php echo $Array->image_caption;?>"/>
</div>
<div class="modal-footer">
<button class="btn btn-success" id="btn_caption">submit</button>
Close
</div>
</div>
</div>
</div>
</form>
<!-- Modal End Here -->
For the ajax part I have done this,
$(document).ready(function(e) {
$("button#btn_caption").click(function(){
var postData = $(this).serialize();
alert(postData);
$.ajax({
type: "POST",
url: "process.php",
data: postData,
success: function(msg){
//alert('successfully submitted')
},
error: function(){
alert("failure");
}
});
});
});
For the process.php file I put these lines,
<?php
include('require/admin_header.php');
if (isset($_POST['caption'])) {
$caption=strip_tags($_POST['caption']);
$image_id=strip_tags($_POST['image_id']);
echo '<pre>';
print_r($_POST);
// Data base update code
echo 'Update Done';
}?>
Now, the problem is the database is not updating with the value. <?php echo $Array->image_caption;?> it print the value from the database in the modal. But when I do this alert(postData);, it alert nothing. Can any one help me that where I am making the mistake?
Thanks in advance for help.
Replace
var postData = $(this).serialize();
with
var postData = $("#form_id").serialize();
<form method="POST" id="form_id">
</form>
I solve the question like this way,
This is the modal part,
<!-- Modal content Start-->
<form id="contactForm1" action="process.php">
<!-- Modal -->
<div class="modal fade" id="myModal<?php echo $i;?>" role="dialog">
<input type="hidden" id="image_id" name="image_id" value="<?php echo $Array->image_id;?>" >
<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">Image Caption</h4>
</div>
<div class="modal-body">
<input type="text" id="caption" name="caption" placeholder="Caption" value="<?php echo $Array->image_caption;?>"/>
</div>
<div class="modal-footer">
<button class="btn btn-success" id="btn_caption">submit</button>
Close
</div>
</div>
</div>
</div>
</form>
<!-- Modal End Here -->
This is the ajax part,
<script>
// Attach a submit handler to the form
$( "#contactForm1" ).submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
var $form = $( this ),
id = $form.find( "input[name='image_id']" ).val(),
caption1 = $form.find( "input[name='caption']" ).val(),
url = $form.attr( "action" );
// Send the data using post
var posting = $.post( url, { image_id: id, caption: caption1} );
// Put the results in a div
posting.done(function( data ) {});
});
</script>
And the PHP part is like this,
<?php include('require/admin_header.php');
if (isset($_REQUEST['caption'])) {
$caption=$_REQUEST['caption'];
$image_id=$_REQUEST['image_id'];
// Update SQL
echo 'Update Done';
}?>
Thanks for those who interest to solve the question. Thanks once again.
You can use this code, in your ajax code:
var postData = new FormData($("#form_id")[0]);
and in your open form tag, you must add enctype="multipart/form-data" to upload image.
<form method="POST" enctype="multipart/form-data" id="form_id">
<input></input>
</form>

modal, button on modal executing many time

I am trying to send data on button on modal using jQuery, first time it is working well but when I click second time it execute twice and for third time it execute 3 times, I want to execute that button only once, what is wrong exactly?
my modal
`<div id="Modal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content modal-sm">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">product</h4>
</div>
<div class="modal-body">
<label>Quantity</label>
<input type="text" class="form-control" id="qty" value="">
<label>Note:</label>
<input type="text" class="form-control" id="note" value="">
</div>
<div class="modal-footer">
<button id="" type="button" class="btn btn-primary mdismiss" data-dismiss="modal">Add</button>
</div>
</div>
</div>
</div>`
my jQuery :
`
$('#btnbtn').click(function(){
$('#Modal').modal('show');
$('#addbutton').click(function(){
alert();
});
});`
You are adding click handler multiple time whenever you are clicking on #btnbtn button. No need of attaching click event handler to #addbutton on each click. Change your code like below:
$('#btnbtn').click(function(){
$('#Modal').modal('show');
});
$('#addbutton').click(function(){
alert();
});
Instead of using .click() when binding the button you can use one(). It will only execute once.
$('#btnbtn').click(function(){
$('#Modal').modal('show');
$('#addbutton').one('click', function(){
alert();
});
});`

Passing data via Modal Bootstrap and getting php variable?

I'm trying to get an input value passed via jquery and setting into a php variable, but I don't know how to do that.
This button have the value that I want to send:
<button type='button' data-a='".$fila['idPlaza']."' href='#editarUsuario' class='modalEditarUsuario btn btn-warning btn-xs' data-toggle='modal' data-backdrop='static' data-keyboard='false' title='Editar usuario'><img src='../images/edit.png' width='20px' height='20px'></button>
Then I have this js code to send the value:
$(document).on("click", ".modalEditarUsuario", function (e) {
e.preventDefault();
var self = $(this);
$("#a").val(self.data('a'));
$(self.attr('href')).modal('show');
});
Finally I have this bootstrap modal
<!-- MODAL EDITAR-->
<div id="editarUsuario" class="modal fade modal" role="dialog">
<div class="vertical-alignment-helper">
<div class="modal-dialog vertical-align-center">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal-title">Editar usuario</h2>
</div>
<form name="formularioModificaUsuario" method='post' action="usuarios.php">
<div class="modal-body">
<input type="text" class="form-control" name="idPlaza" id="a">
<?php
$valueA = ???
?>
</div>
<div class="modal-footer">
<button type="reset" id="cancelar" class="btn btn-danger" data-dismiss="modal" value="reset"><img src='../images/cancel.png' width='20px' height='20px'> Cancelar</button>
<button type="submit" name="submitModifica" id="submit" class="btn btn-primary" value="submit"><img src='../images/save_changes.png' width='20px' height='20px'> Guardar cambios</button>
</div>
</form>
</div>
</div>
</div>
</div>
My question is, how could I get the value of id='a' input into php variable $valueA to use after?
<button type='button' data-a="<?echo $fila['idPlaza'];?>" href='#editarUsuario' class='modalEditarUsuario btn btn-warning btn-xs' data-toggle='modal' data-backdrop='static' data-keyboard='false' title='Editar usuario'>
<img src='../images/edit.png' width='20px' height='20px'>
</button>
Put below code in footer before end of </body> tag.
<!-- MODAL EDITAR-->
<div id="editarUsuario" class="modal fade modal" role="dialog">
<div class="vertical-alignment-helper">
<div class="modal-dialog vertical-align-center">
<div class="modal-content">
</div>
</div>
</div>
</div>
Use Script like this.
<script>
$('.modalEditarUsuario').click(function(){
var ID=$(this).attr('data-a');
$.ajax({url:"NewPage.php?ID="+ID,cache:false,success:function(result){
$(".modal-content").html(result);
}});
});
</script>
Create NewPage.php, and paste the below code.
(Remember, this page name NewPage.php is used in script tag also. if you are planning to change the name of this page, change page name there in script tag too. Both are related.)
<?
$ID=$_GET['ID'];
?>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal-title">Editar usuario</h2>
</div>
<form name="formularioModificaUsuario" method='post' action="usuarios.php">
<div class="modal-body">
<input type="text" class="form-control" name="idPlaza" id="a">
<?php
$valueA = $ID;
?>
</div>
<div class="modal-footer">
<button type="reset" id="cancelar" class="btn btn-danger" data-dismiss="modal" value="reset">
<img src='../images/cancel.png' width='20px' height='20px'> Cancelar</button>
<button type="submit" name="submitModifica" id="submit" class="btn btn-primary" value="submit">
<img src='../images/save_changes.png' width='20px' height='20px'> Guardar cambios</button>
</div>
</form>
Php loads before anything on your page, so you cannot set a php variable using jQuery or javascript, but the opposite can be done.
If you have the value of the text field initially when loading then you can set it via php on load, otherwise you will need to submit your form to use the value of the input in php.
The following code is valid, php setting javascript
<?php
$valueA = "I am value A";
?>
<script language="javascript">
var jsValueA = "<?php echo $valueA; ?>";
alert(jsValueA); // alerts I am value A
</script>
The following code is invalid, javascript setting php
<input type="text" class="form-control" name="idPlaza" id="a">
<?php
$valueA = $("#a").val();
?>
This is wrong because when PHP executed the input field would not have been created yet, besides jQuery cannot be executed within PHP scope. javascript and jQuery are used at browser level to manage user interaction and DOM objects and events while PHP is used at server level and not browser.
So if you want to set a php variable, you can only set it when the server script loads, i.e php gets executed, which comes before anything else in the page. Or you can grab a value from a posted form $_POST or URI query string $_GET

How can I stop the Bootstrap Modal popup from closing during a submit of data to db?

I have a commenting system that sits within a Bootstrap Modal, all works fine in terms of pulling data from the database, and the ability to enter data. the problem is on Submit.
This below is my code for the submit.
$(document).ready(function(){
var form = $('form');
var submit = $('#submit');
form.on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'projectnoteuploads.php',
type: 'POST',
cache: false,
data: form.serialize(),
success: function(data){
console.log(data);
var item = $(data).hide().fadeIn(800);
$('.comment-block').append(item);
},
error: function(e){
alert(e);
}
});
});
});
myjobspage.php - this is the start of my modal on my main page, it's called from the Notes button
<div id="projnotes" class="modal fade modal-scroll" tabindex="-1" data-width="960">
</div>
I originally had the rest of the modal within the div above, but as I was having this issue of it closing the form and refreshing the page, I decided to move the modal onto another page, and have it called when the button is clicked, but still having the same issue
This is the modal code
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">Project Notes</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<!-- Table shown here (no need to show as not involved) -->
</div>
</div>
<div class="row">
<div class="col-md-12">
<!--comment form -->
<form class="notesform" id="notesform" name="notesform" method="post">
<!-- need to supply post id with hidden fild -->
<input type="hidden" name="postid" value="<?php echo $propid; ?>">
<input type="hidden" name="projno" value="<?php echo $projectno; ?>">
<input type="hidden" name="name" value="<?php echo $inputby; ?>">
<div class="col-md-12 ">
<div class="form-group">
<label for="inputEmail12" class="col-md-2 control-label">Project Notes *</label>
<div class="col-md-8">
<textarea class="form-control col-md-8" rows="3" name="comment" id="comment"placeholder="Type your comment here...." required></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<br>
<input type="submit" class="btn green" id="savenotes" name="submit" value="Submit Comment" />
</div>
</div>
</div>
</form>
</div>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-default">Close</button>
</div>
One question on this though is that to call the jquery/Ajax code is done through my main page, is this right or should it be done through the page that the Model body is on?
When the Submit button id="savenotes" is clicked, the modal closes and refreshes the page losing all data within the main page.
How can I submit data to the database without the Modal closing?
I don't know if you've found an answer to this but at least for others who might need solutions just like I once did.
This is the modal page named modal.php:
<div id="projnotes" class="modal fade modal-scroll" tabindex="-1"
data-
width="960">
<!-- div wrapper for modal dialog -->
<div class="modal-dialog">
<!-- div wrapper for modal content -->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-
hidden="true"></button>
<h4 class="modal-title">Project Notes</h4>
</div>
<!-- I guess you wanted your body centered .justify-content-center
should fix that -->
<div class="modal-body justify-content-center">
<div class="row">
<div class="col-md-12">
<!-- Table shown here (no need to show as not involved) -->
</div>
</div>
<!-- I guess you wanted your form centered .justify-content-center
would fix that -->
<div class="row justify-content-center">
<!--comment form -->
<form class="notesform form-block" id="notesform" name="notesform"
method="post" action="projectnoteuploads.php">
<!-- need to supply post id with hidden fild -->
<input type="hidden" name="postid" value="<?php echo $propid =
'propid'; //replace variable $propid ?>">
<input type="hidden" name="projno" value="<?php echo $projectno =
'projectno'; //replace variable $projectno ?>">
<input type="hidden" name="name" value="<?php echo $inputby =
'inputby'; //replace variable $inputby ?>">
<div class="form-group">
<label for="comment" class="control-label">Project Notes *</label>
<textarea class="form-control form-control-md" rows="3" cols="25"
name="comment" style="resize: none;" id="comment" placeholder="Type
your comment here...." required></textarea>
</div>
<input type="submit" class="btn btn-success" id="savenotes"
name="submit" value="Submit Comment" />
</form>
</div>
<!-- I can't find where your Comments are appended
to, so I placed them here using the
class name 'comment-block' as you used in your script -->
<div class="row justify-content-center">
<div class="comment-block"></div>
</div>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-
default">Close</button>
</div>
</div>
</div>
</div>
Then this is your myjobspage.php where you will include the modal.php
<?php
include 'modal.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Myjobspage</title>
<link rel="stylesheet"
href="path/to/bootstrap4.0.0/dist/css/bootstrap.min.css">
<script src="path/to/Jquery_3.2.1/jquery-3.2.1.js"></script>
<script src="path/to/bootstrap-
4.0.0/assets/js/vendor/popper.min.js">
</script>
<script src="path/to/bootstrap-4.0.0/dist/js/bootstrap.min.js">
</script>
</head>
<body>
<!-- Some Code Here-->
<!-- Button to Launch Modal. Replace appropriately-->
<button type="button" class="btn btn-primary" data-toggle="modal"
data-target="#projnotes">
Launch Comments Modal
</button>
<!-- some other code -->
<!-- script to trigger your modal.php -->
<script src="modalScript.js"></script>
<script src="path/to/bootstrap-4.0.0/js/dist/util.js"></script>
<script src="path/to/bootstrap-4.0.0/js/dist/modal.js"></script>
</body>
</html>
This is the script modalScript.js that will make the request to projectnoteuploads.php via the ajax method.
$(document).ready(function(){
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'projectnoteuploads.php',
type: 'POST',
cache: false,
data: $('form').serialize(),
success: function(data){
console.log(data);
//This I guess was where the error was in the previous code.
$('.comment-block').append(data).hide().fadeIn(800);
$('textarea').val(''); //This will wipe out the textarea after
//comment input
},
error: function(e){
alert(e);
}
});
});
});
Please take note, the codes have all being modified from the question, I tried it and it works.

Categories