Hi I submit my form using modal in bootstrap
How can I make this work with dismissal message and not closing the modal?
HTML
<div class="modal fade bs-example-modal-lg" id="myModal" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header modal-header-custom">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body text-center">
<form class="form-inline requestaccessForm" role="form" name="requestaccessForm">
<div class="form-group">
<label class="sr-only" for="First Name">First Name</label>
<input type="text" class="form-control" id="request_first_name" placeholder="First Name">
</div>
<div class="form-group">
<label class="sr-only" for="Last Name">Last Name</label>
<input type="text" class="form-control" id="request_last_name" placeholder="Last Name">
</div>
<div class="form-group">
<label class="sr-only" for="email">Email</label>
<input type="email" class="form-control" id="request_email" placeholder="Email">
</div>
<button type="submit" id="requestformSubmit" class="btn btn-green">Submit</button>
</form>
</div>
</div>
</div>
</div>
PHP
<?php
$myemail = 'dummyemail#email.com';
if (isset($_POST['request_first_name'])) {
$request_first_name = strip_tags($_POST['request_first_name']);
$request_last_name = strip_tags($_POST['request_last_name']);
$request_email = strip_tags($_POST['request_email']);
echo "<span class=\"alert alert-success\" >Your message has been received. Thanks!
Here is what you submitted:</span><br><br>";
echo "<stong>Name:</strong> ".$request_first_name."<br>";
echo "<stong>Name:</strong> ".$request_last_name."<br>";
echo "<stong>Email:</strong> ".$request_email."<br>";
$to = $myemail;
$email_subject = "Contact form submission: $request_first_name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $request_first_name \n ".
"Email: $request_email\n";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $request_email";
mail($to,$email_subject,$email_body,$headers);
}?>
Javascript
$(document).ready(function () {
$("button#requestformSubmit").click(function(){
$.ajax({
type: "POST",
url: "process.php", //
data: $('form.requestaccessForm').serialize(),
success: function(msg){
alert("success");
},
error: function(){
alert("failure");
}
});
});
});
Thank you
To achieve that you have to take some steps first..
Add a div inside the modal which will serve as the success message container.
Before closing the <div class="modal-body text-center"> add the following code:
...
<div id="successMessage"/></div>
...
Change the success handler of the $.ajax request to add the dismissal/success message into the div created in the previous step.
Add the following code to your $.ajax success handler:
...
success: function(msg){
$("#successMessage").html(msg);
},
...
Prevent default actions from the button click so that the modal will not be closed after the request.
Add the following line at the end of your jQuery click function:
return false;
So your jQuery code will look something like this:
$(document).ready(function () {
$("button#requestformSubmit").click(function(){
$.ajax({
type: "POST",
url: "process.php", //
data: $('form.requestaccessForm').serialize(),
success: function(msg){
$("#successMessage").html(msg);
},
error: function(){
alert("failure");
}
});
return false;
});
});
Hope this helps you out
Related
I have a form on my site that I want to send an email on submit. The email gets sent but none of the content gets sent along with it. It seems that isset($_POST['email']) is failing.
Here is my form:
<form id="sponsorForm" name="sponsor" role="form">
<div class="modal-body">
<div class="form-group col-md-12">
<label for="sponsorname">Name</label>
<input type="text" name="sponsorname" class="form-control">
</div>
<div class="form-group col-md-12">
<label for="sponsoremail">Email</label>
<input type="email" name="sponsoremail" class="form-control">
</div>
<div class="form-group col-md-12">
<label for="sponsormessage">Message</label>
<textarea class="form-control" name="sponsormessage" rows="7" placeholder="Message...">
</textarea>
</div>
</div>
<div class="modal-footer" style="border: none;">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-success" data-toggle="modal" data-target="#sponsor-thanks" id="sponsor-submit">
</div>
</form>
Here is some javascript to call the php:
$(document).ready(function(){
$("#sponsorForm").submit(function(event){
submitSponsorForm();
return false;
});
});
function submitSponsorForm(){
$.ajax({
type: "POST",
url: "sendSponsor.php",
cache:false,
data: $('form#sponsorForm').serialize(),
success: function(response){
$("#sponsor").html(response)
$("#sponsor-modal").modal('hide');
},
error: function(){
alert("Error");
}
});
}
And here is the php:
<?php
if (isset($_POST['email'])) {
$sponsorname = strip_tags($_POST['sponsorname']);
$sponsoremail = strip_tags($_POST['sponsoremail']);
$sponsormessage = strip_tags($_POST['sponsormessage']);
$message = "Name: ".$sponsorname."\r\nEmail: ".$sponsoremail."\r\nMessage: ".$sponsormessage;
}
mail("xxx#xxx.com", "subject", $message, "from: xxx");
?>
In your form, the name of your email input field is 'sponsoremail'
So you should use the name sponsoremail as the index of $_POST variable as $_POST['sponsoremail'] to check if user fill the email or not but you have used $_POST['email'] which is not found in your form.
Use if (isset($_POST['sponsoremail'])) instead of if (isset($_POST['email'])) and it should work.
Try this
<?php
if (isset($_POST['sponsoremail'])) {
$sponsorname = strip_tags($_POST['sponsorname']);
$sponsoremail = strip_tags($_POST['sponsoremail']);
$sponsormessage = strip_tags($_POST['sponsormessage']);
$message = "Name: ".$sponsorname."\r\nEmail: ".$sponsoremail."\r\nMessage: ".$sponsormessage;
mail("xxx#xxx.com", "subject", $message, "from: xxx");
}
?>
Aim: Continue to display any form validation errors through json callback
Problem: When I submit on the form with invalid input it shows an error message in a div element. If all inputs are valid it will process the ajax request and show a success message in a div element. After which, the form resets but the modal remain open. When I try to again validate the input in doesn't show any error message. When I try to test the valid input still the same no message shown.
In short: Ajax success function not working on the second time.
Here's my code:
Bootstrap Modal (where my form inputs placed)
<div class="modal fade" id='frmModal'>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button class='close' data-dismiss='modal'>×</button>
<h4 class='title'>Add new data</h4>
</div>
<div class="modal-body">
<?php echo form_open('Employee/save',array('id'=>'frm', 'class'=>'form-horizontal')); ?>
<div id="message"></div>
<div class="form-group">
<label for='fname' class='col-md-3 control-label'>First Name:</label>
<div class="col-md-9">
<input type="text" name="fname" id='fname' class='form-control' placeholder='First Name...'>
</div>
</div>
<div class='form-group'>
<label for='lname' class='col-md-3 control-label'>Last Name:</label>
<div class="col-md-9">
<input type="text" name="lname" id='lname' class='form-control' placeholder='Last Name...'>
</div>
</div>
<div class='form-group'>
<label for='age' class='col-md-3 control-label'>Age:</label>
<div class="col-md-9">
<input type="text" name="age" id='age' class='form-control' placeholder='Age...'>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary action" type='submit'><i class='glyphicon glyphicon-floppy-disk'></i> Save Data</button>
</div>
<?php echo form_close(); ?>
</div>
</div>
</div>
</div>
Jquery Code:
$(document).on('submit','#frm',function(e){
e.preventDefault();
var form = $('#frm');
$.ajax({
url: form.attr('action'),
type: 'POST',
dataType: 'json',
encode: true,
data: form.serialize(),
success: function(data) {
if (!data.success) {
if (data.errors) {
$('#message').html(data.errors).addClass('alert alert-danger');
}
} else {
reloadData();
$('#message').html("<span class='glyphicon glyphicon-ok'></span> " + data.message).removeClass('alert alert-danger').addClass('alert alert-success');
setTimeout(function() {
$("#message").fadeTo(500, 0).slideUp(500, function() {
$(this).remove();
});
}, 3000);
$('#frm')[0].reset();
}
}
});
});
CodeIgniter Controller:
$this->form_validation->set_rules('fname','First Name', 'required|trim');
$this->form_validation->set_rules('lname','Last Name', 'trim|required');
$this->form_validation->set_rules('age','Age', 'trim|numeric|required');
if($this->form_validation->run()===FALSE)
{
$info['success'] = false;
$info['errors'] = validation_errors();
}
else
{
$info['success'] = true;
$data = array(
"firstname" => $this->input->post('fname'),
"lastname" => $this->input->post('lname'),
"age" => $this->input->post('age'),
);
$this->Employee_model->save('ci_table', $data);
$info['message'] = 'Successfully saved data';
}
$this->output->set_content_type('application/json')->set_output(json_encode($info));
}
I think I understand... The form still works but the messages do not appear? If so then try the below...
You are removing the #message element instead of clearing it... try:
$("#message").fadeTo(500, 0).slideUp(500, function() {
$(this).empty();
This way you are emptying the #message element instead of removing it completely..
Been struggling with this for about few hours. I'm attempting to have a modal drop down (Twitter bootstrap modal) that contains a form to choose a category of user. This is built in CodeIgniter. But when i try to save form's value using AJAX, the SUCCESS function won't run without alert(). I'm sorry for my bad grammar, i hope you can understand what i mean.
i need for your help...
view (kasir_halaman.php):
<div id="editModal" class="modal fade" role="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title"><span class="glyphicon glyphicon-plus"></span> Ubah Kasir</h3>
</div>
<div class="modal-body">
<form action="#" id="editform" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Nama</label> <span class="error" id="report1"></span>
<input type="text" id="editnama" name="nama" class="form-control" maxlength="100" required>
</div>
<div class="form-group">
<label>E-mail</label>
<input type="email" id="editemail" name="email" class="form-control" maxlength="150" required>
</div>
<div class="form-group">
<label>Kategori</label>
<select class="form-control" name="kategoripetugas" id="editkategori" required>
<option value=""> -- Pilih Kategori -- </option>
<option value="1">Admin</option>
<option value="2">Kasir</option>
</select>
</div>
<button type="submit" class="btn btn-primary" style="width:100%;">Simpan</button>
</form>
</div>
</div>
</div>
</div>
controller (kasir.php):
public function updatePetugas($id)
{
$nama_petugas = $this->input->post('nama');
$email_petugas = $this->input->post('email');
$kategori_petugas = $this->input->post('kategoripetugas');
$data = array('nama'=>$nama_petugas, 'email'=>$email_petugas, 'kategori'=>$kategori_petugas);
$update = $this->Crud->update(array('idpetugas'=>$id), 'petugas', $data);
if($update){
echo 1;
}else{
echo 2;
}
}
javascript (petugas.js) :
$(document).ready(function(){
var check1=0; var id;
$("#nama").bind("keyup change", function(){
var nama = $(this).val();
$.ajax({
url:'kasir/cekData/kasir/nama/'+nama,
data:{send:true},
success:function(data){
if(data==1){
$("#report1").text("");
check1=1;
}else{
$("#report1").text("*nama petugas sudah terpakai");
check1=0;
}
}
});
});
$(".edit").click(function(){
id = $(this).attr('id');
$.ajax({
url:'kasir/getData/'+id,
data:{send:true},
success:function(data){
$("#editnama").val(data['nama']);
$("#editemail").val(data['email']);
$("#editkategori").val(data['kategori']);
}
});
});
$("#editform").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url:'kasir/updatePetugas/'+id,
data:formData,
type:'POST',
contentType: false,
processData: false,
success:function(data){
if(data==1){
$("#editModal").hide();
window.location.reload(true);
}else if(data==2){
alert('gagal');
}
}
});
alert("success!"); // if i remove this alert, the success function won't run or executed
});
});
you can solve this a few ways, what is actually happening is that you are submitting the data via ajax as well as submitting the form itself.
using e or the event
$("#editform").submit(function(e){
e.preventDefault();
or by returning false on submit
});
//alert("success!"); we can comment this out because it will work now without the alert holding the page
return false;
});
in either case you can remove your alert.
Inserting into mysql using php file called via AJAX. Before insert statement php code performs select query to find duplicate records and continue to insert statement.
Issue: When calling php file from ajax. it executed twice and getting response as duplicate record.
well i tried error_log from insert function its called twice.
Trigger point of form validation
$("#load-modal").on("click","#addcountryformsubmitbtn",function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$form.submit();
});
This is how form submitted after validation:
}).on('success.form.bv', function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$.post($url,$form.serialize()).done(function(dte){ $("#load-modal").html(dte); });
});
using bootstrapvalidator, Core PHP, mysqli, Chrome Browser.
Actual JS:
$(document).ready(function() {
$php_self_country="<?php echo $_SERVER['PHP_SELF']."?pg=countrycontent"; ?>";
$("#country-content").load($php_self_country,loadfunctions);
$("#country-content").on( "click", ".pagination a", function (e){
e.preventDefault();
$("#country-loading-div").show();
var page = $(this).attr("data-page");
$("#country-content").load($php_self_country,{"page":page}, function(){
$("#country-loading-div").hide();
loadfunctions();
});
});
$("#country-content").on("click","#closebtn",function(e){
e.preventDefault();
$("#country-content").load($php_self_country,loadfunctions);
});
});
function loadfunctions(){
$("[data-toggle='tooltip']").tooltip();
$("#country-content").on("click","#addcountrybtn, #addcountrylargebtn",function(e){
e.preventDefault();
$.ajax({
url: $php_self_country,
type: "POST",
data: { 'addcountry':'Y' },
dataType: "html",
cache: false
}).done(function(msg){
$("#load-modal").html(msg);
$("#load-modal").modal('show');
$('input[type="radio"]').iCheck({ checkboxClass: 'icheckbox_minimal', radioClass: 'iradio_minimal' });
modalvalidation();
}).fail(function() {
$("#load-modal").html( "Request Failed. Please Try Again Later." );
});
});
$("#country-content").on("click",".tools a",function(e){
e.preventDefault();
var recordid = $(this).attr("record-id");
$.ajax({
url: $php_self_country,
type: "POST",
data: { 'modifycountry':recordid },
dataType: "html",
cache: false
}).done(function(msg){
$("#load-modal").html(msg);
$("#load-modal").modal('show');
$('input[type="radio"]').iCheck({ checkboxClass: 'icheckbox_minimal', radioClass: 'iradio_minimal' });
modalvalidation();
}).fail(function() {
$("#load-modal").html( "Request Failed. Please Try Again Later." );
});
});
$("#load-modal").on("click","#addcountryformsubmitbtn",function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$form.submit();
});
$("#load-modal").on("hide.bs.modal", function () {
window.location.href=$php_self_country_pg;
});
}
function modalvalidation(){
$('#addcountryform').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
[-------Validation part comes here----------]
}
}).on('success.form.bv', function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$.post($url,$form.serialize()).done(function(dte){ $("#load-modal").html(dte); });
});
}
HTML
this html is called on button click addcountrybtn via AJAX and write in to div load-modal which is in base html file.
<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"><i class="fa fa-exchange"></i> <?php echo COUNTRYLABEL; ?></h4>
</div>
<div class="modal-body">
<form role="form" method="POST" action="self.php" name="addcountryform" id="addcountryform" class="form-horizontal">
<div class="form-group">
<div class="col-xs-3">
<label for="countryname" class="pull-right">Country Name</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="countryname" placeholder="Enter Country Name">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="crncyname" class="pull-right">Currency Name</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="crncyname" placeholder="Enter Currency Name">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="crncycode" class="pull-right">Currency Code</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="crncycode" placeholder="Enter Currency Code">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="forrate" class="pull-right">Foreign Currency Rate<?php echo isset($icon)?$icon:''; ?></label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="forrate" placeholder="Enter Foreign Currency Rate.">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="taxpercent" class="pull-right">Tax %</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="taxpercent" placeholder="Enter Tax Percentage">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer clearfix">
<button type="button" class="btn btn-danger pull-right" id="addcountryformsubmitbtn">Add</button>
</div>
</div>
Note:- in Database point of view code works as expected.
Couple of things that I have seen could possibly be the cause.
If you are using IE, I have seen that perform a GET immediately before doing a POST (to the same URL, with the same data being sent over), so it could be worth trying to check for that on your server (and ignore the GET)
Something else it maybe to add the following to the end of your button click events after the AJAX call (actually, normally I'd put the first line at the top with the prevent default, and the return statement obviously goes very last)...
e.stopImmediatePropagation();
return false;
I have a JSON returned data from a pho function that looks as follows:
[{"id":"15","activity_type":"call","activity_title":"Call to check "}]
Here the script that initiates the request (actvitiy.js)(Edited)
$(document).on("click", ".view_contact_activity", function () {
var this_activity_id = $(this).closest('.feeds').find('#this_activity_id').val();
$('#view-contact-activity').modal('show');
$.ajax({
url: '../includes/functions/contact-functions.php',
data: {view_activity_id:this_activity_id},
dataType:'json',
Success: function(response){
$('#activity_id').val(response[0].id);
$('#activity_type').val(response[0].activity_type);
}
});
});
The modal where i need the values to show:
<div class="modal fade" id="view-contact-activity" tabindex="-1" role="basic" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<div class="portlet-body form">
<form class="form-horizontal" role="form" id="view-contact-activity-form" method="post">
<div class="form-group">
<label class="col-sm-3 control-label col-lg-3"> Activity Title</label>
<input type="text" name="activity_id" id="activity_id" value="">
<label class="col-sm-3 control-label col-lg-3"> Activity Type</label>
<input type="text" name="activity_type" id="activity_type" value="">
<div class="modal-footer">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" name="create-new-account" class="btn btn-danger" id="edit">Edit Activity</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
The modal shows but no data is passed into the modal. Any ideas what i might be doing wrong here.
EDIT: Adding PHP function that returns the JSON
function view_activity(){
global $connection;
$activity_id = $_POST['view_activity_id'];
$get = "SELECT * FROM contact_activities WHERE activity_id = '$activity_id' "
or die("Error: ".mysqli_error($connection));
$query = mysqli_query($connection, $get);
$activitiy_field = array();
while ($activity_array = mysqli_fetch_array($query)){
$activity = array(
'id' => $activity_array['activity_id'],
'activity_type' => $activity_array['activity_type'],
'activity_title'=>$activity_array['activity_title'],
'activity_details'=>$activity_array['activity_details'],
'activity_status'=>$activity_array['activity_status'],
'activity_details'=>$activity_array['activity_details'],
'activity_details'=>$activity_array['activity_details'],
);
$activitiy_field[] = $activity;
}
echo json_encode($activitiy_field);
}
if (isset($_POST['view_activity_id'])) {
view_activity();
}
Thank you.
Use .val() instead of .html().
$('#activity_id').val(response.id);
$('#activity_type').val(response.activity_type);
Modified: Your javascript should look like this:
$(document).on("click", ".view_contact_activity", function () {
var this_activity_id = $(this).closest('.feeds').find('#this_activity_id').val();
$('#view-contact-activity').modal('show');
$.ajax({
url: '../includes/functions/contact-functions.php',
data: {view_activity_id:this_activity_id},
dataType:'json',
Success: function(response){
$('#activity_id').val(response[0].id);
$('#activity_type').val(response[0].activity_type);
}
});
});
After digging on multiple sites. i found a similar question that could help.
$(document).on("click", ".view_contact_activity", function () {
var this_activity_id = $(this).closest('.feeds').find('.id #this_activity_id').val();
$('#view-contact-activity').modal('show')
$('#view-contact-activity').on('show.bs.modal', function() {
$modal = $(this);
$.ajax({
url: '../includes/functions/contact-functions.php',
data: {view_activity_id:this_activity_id},
dataType:'json',
success: function(response){
// Find the elements in the modal
$modal.find('#activity_id').val(response[0].id);
$modal.find('#activity_type').val(response[0].activity_type);
}
});
});
});