How to post data in ajax from bootstrap modal? - php

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>

Related

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.

Bootstrap modal form submit not working

please i need someone to help me check if i'm missing something. The form in the Bootstrap modal wont submit.
my HTML codes for the modal (sidebar.php)
<!-- start Joel's modal -->
<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">E-Logbook Entry</h4>
</div>
<div class="modal-body">
<form id="modal-form" method="post" action="notes_functions.php">
<fieldset>
<label>Log Entry</label>
<textarea rows="4" cols="50" class="form-control" name="note_content" placeholder="What have you learnt today?..."></textarea>
</form>
</div>
<div class = "modal-footer">
<button type = "button" class = "btn btn-default" data-dismiss = "modal">
Close
</button>
<input type="submit" name="submit" class="btn btn-default" id="submitnote" value="Submit" />
</div>
</div>
</div>
</div>
<!-- end Joel's modal -->
codes for the PHP file (notes_functions.php)
<?php
include_once 'database-config.php';
if (isset($_POST['submitnote'])) {
$noteContent = strip_tags($_POST['note_content']);
$sql = "INSERT INTO account_notes (note_contents) VALUES ('$noteContent')";
$dbh->exec($sql);
echo "New record created successfully";
echo "Log details = ".$note_contents;
}
?>
my AJAX codes for submitting the form
<script type="text/javascript">
var frm = $('#modal-form');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
dataType: "JSON",
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
</script>
I can't seem to spot the error :-(
your submit button is not in the form. place it in the form or add this to the button
form="modal-form"
like so:
<input type="submit" name="submit" class="btn btn-default" id="submitnote" value="Submit" form="modal-form" />
Two things:-
1.Instead of if (isset($_POST['submitnote'])) { use if (isset($_POST['submit'])) {
2.Put ev.preventDefault(); before $.ajax({

Error sending form on a twitter bootstrap to php mysql using ajax

Am trying to submit data using modal bootstrap but i can't get it to work. The page will contain more than one modal to enable user to easily update their details.Here the code.
<div class="modal fade" id="overview-modal" 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">Overview</h4>
</div>
<form id="overview_form" action="neuro/update_profile.php" class="form-horizontal" >
<div class="modal-body">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Overview</label>
<div class="col-sm-10">
<textarea class="form-control" id="overview_input" cols="20" rows="10" name="overview_textarea">
</textarea>
<input type="hidden" name="url"/>
</div>
</div>
<div class="form-group">
</div>
</div>
<div class="modal-footer">
<div class="btn-group">
<input type="submit" id="save" class="btn btn-success" value="Save"/>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
</div>
This is the javascript that will handle the form submission to the php file
<script>
$(document).ready(function () {
$("#save").submit(function () {
var formData = $("form#overview_form").serialize();
var my_url = "neuro/update_profile.php";
$.ajax({
type: "POST",
url: my_url,
data: formData ,
success: function (msg) {
$("#overview-modal").modal('hide');
},
error: function () {
alert("Error encounted");
}
});
return false;
});
});
</script>
The php is in a folder called neoro/update_profile ,since i will be using more than one modal in the profile page i have decided to append a url on the form attributes so that it can be easily processed in the php
$profile = new Profile();
$url = $_POST['url'];
if (isset($url)) {
if ($id == "overview") {
$overview = $_POST['overview'];
$profile->save_overview($user_id, $overview);
return TRUE;
}
} else {
header("Location: ./profile.php");
}
This is full of errors
You are sending the form via GET method and accessing it via POST method
Your URL field is empty
you are using action field and also submit simultaneously
your jquery code is not correct
you are using $id variable in your php code which is undefined
Corrected code:
<form id="overview_form" class="form-horizontal" method="post">
<input type="hidden" name="url" value='yoururl'/>
Do this:
$('#overview_form').submit(// your code here);
Instead of on #save, since you are submitting form not button 😉
Or
Even you can achieve same thing on #save but with click function as below
$('#save').click( // here your code );

Load remote form for editing in bootstrap modal using ajax

This is what I am trying:
To open modal:
<a href="" class="label label-important"
data-toggle="modal" data-target="#editFee"
data-id="'.$month['fid'].'" title="Edit '.$month['status'].' Fee">Edit</a>';
This is the modal dialog:
<div class="modal fade" id="editFee" tabindex="-1" role="dialog"
style="width: 25%" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Pay Fee</h4>
</div>
<div class="modal-body">
<!--Load remode editfee.php--!>
</div>
</div>
</div>
</div>
and this is editfee.php
<?php
$id=$_GET['id'];
$fee = QueryFee('Feetable', $id);
foreach($fee as $feeForm):
?>
<form>
<input type="text" id="amount" value="<?php echo $feeForm['amount']; ?>">
<input type="text" id="dateFee" value="<?php echo $feeForm['dateFee']; ?>">
<input type="submit" id="submitFee" value="Save Fee">
</form>
<?php endforeach;?>
And finally the jquery ajax:
$(document).on("click", ".label", function(e){
e.preventDefault();
var id= $("#id").val();
dataEdit = 'id='+id;
$.ajax({
type:'GET',
data:dataEdit,
url:'editfee.php',
success:function(data) {
$(".modal-body").val(data);
}
});
});
I am using Bootstrap modal V2.0.4. The above code does open the dialog but without the remote data from editfee.php. Please help me.
In your example, this code can't work:
var id= $("#id").val();
Your must to use something like this:
var id = $(this).data('id');
And finish by:
$(".modal-body").html(data);
$(".modal-body").val(data);
will not work, Because modal-body is just a div not an input element. So we should give
$(".modal-body").html(data);
instead of
$(".modal-body").val(data);
.val() attribute only for input elements. .html() is for appending html contents into the div.
And get the id attribute by
$(this).attr("id")
or
$(this).prop("id")

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