open modal bootstrap on submit form - javascript

how can I open a modal when the user has validated the form ?
S’inscrire
<div class="modal fade" id="registration" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<h3 class="modal-title">Merci !</h3>
</div>
</div>
</div>
</div>

You can use the modal id or class to open it when the user clicks on submit button.
Lets say you have this HTML
<form id="submit-button">
//form components
</form>
Then you can write this JQuery code:
//trigger when form is submitted
$("#submit-button").submit(function(e){
$('#registration').modal('show');
return false;
});
The $('#registration').modal('show'); will display the modal and return false; prevent the form to post the data which will stop the page to reload. Or, you can also do this
$(document).ready(function() {
$('#submit-button').on('submit', function(e){
$('#registration').modal('show');
e.preventDefault();
});
});
e.preventDefault(); will stop the page from the page reload.

You can add this to to your function when you the form is validated:
$('#registration').modal({
show: 'false',
backdrop: 'static',
keyboard: false
});
Keyboard false means when you press escape the modal won't
disappeared.
Setting the backdrop to static means when people click with their
mouse outside of the modal. The modal won't close.
EDIT
if ($("form button").valid()) {
$('#registration').modal({
show: 'false',
backdrop: 'static',
keyboard: false
});
};

I would use an Ajax solution to submit the form without refreshing the page.
You could even update the modal response based on the outcome of the request.
$("#ajaxform").submit(function(e) {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#ajaxform").serialize(), // serializes the form's elements.
success: function(data)
{
//if request successful
$(".modal-title").text('Request successful');
$('#registration').modal('show');
},
error: function(data)
{
//if request unsuccessful
$(".modal-title").text('Request failed');
$('#registration').modal('show');
}
}).done(function() {
//finally, reinitialise modal text back to default 'merci'
$(".modal-title").text('merci');
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<form name="ajaxform" id="ajaxform" action="ajax-form-submit.php" method="POST" class="form-group">
First Name: <input type="text" name="fname" value="" class="form-control"/> <br/> Last Name: <input type="text" name="lname" value="" class="form-control"/> <br/> Email : <input type="text" name="email" value="" class="form-control"/> <br/>
<button type="submit" class="btn btn-default">submit</button>
</form>
<div class="modal fade" id="registration" tabindex="1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<h3 class="modal-title">Merci !</h3>
</div>
</div>
</div>
</div>

you can add this on validation success:
$("#registration").modal('show');

Related

Laravel Submit Form Without Page Refresh Using Ajax

I want to post the phone number in my modal popup form.but don't want to disappear the popup after submitting the form clicking on "continue" button. Here is my blade.php code.
<div id="modal-wrapper" class="modal">
<form class="modal-content animate" id="addform">
<input type="text" class="form-control" name="phone_number" placeholder="01**********">
</div>
</div>
<div style="text-align: center; margin-top: 10px;padding-left:18px;">
<button type="submit" style="background-color: #a5abb0;" class="mobile-login__button">CONTINUE
</button>
</div>
here is my script part for ajax part of the code.
<script>
$("#addform").on('submit',function(e){
e.preventDefault();
$.ajax({
type:"post"
url: "/client-mobile-login"
data: $("addform").serialize(),
success:function(response){
},
error:function(error){
console.log(error)
alert("not send");
}
)};
});
});
</script>
and here is my controller function
public function client_mobile_login(Request $request)
{
$client_phone1='88'.$request->input('phone_number');
$result=DB::table('client')
->where('client_phone1',$client_phone1)
->first();
{{ here is my otp sending code.... }}
if($result)
{
$request->session()->put('client_title', $result->client_title);
// print_r($client_phone1);
}
Use type=button
<button type="button" id="submitForm" ...>CONTINUE</button>
And trigger your ajax on click event
$("#submitForm").on('click',function(e){ ... }

AJAX form only allows one submission?

I am creating a form which will be submitted through the use of jQuery AJAX, but I am for some reason only able to submit the form once. To submit again I have to refresh page?
How do i accomplish the form and script so I do not have to refresh?
Here is the form:
<form role="form" class="form-horizontal validate" name="create_form" id="create_form">
<div class="form-group">
<label class="col-sm-2 control-label" for="name">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" name="name" data-validate="required" data-message-required="Remeber to fill name" placeholder="">
</div>
</div>
<div class="form-group-separator"></div>
<div class="form-group">
<button id="submit_btn" class="btn btn-success">Create</button>
<button type="reset" class="btn btn-white">Reset</button>
</div>
</form>
And here is the AJAX part:
$(document).ready(function(){
$("#submit_btn").on("click", function () {
$.ajax({
type: 'POST',
url: 'data/create.php',
cache: false,
data: $('#create_form').serialize()
})
.done(function(data){
$("#name").val("");
})
.fail(function() {
console.log("ERROR");
});
// Prevent refreshing the whole page page
return false;
});
});
Hoping for help and thanks in advance :-)
use submit instead of click.
$('#submit_btn').on('submit', function(e) {
e.preventDefault();
... //rest of the code
});
I don't really see why you are wanting to run your script on document load. I would suggest you to include the script's source in the html and include an onClick attribute to the button element and then assign the event handler function call to it to be fired every time you click the Submit button.
<button onclick="myFunction()">Click me</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>

How to display modal form after submitting through AJAX

I Have a login in form inside a modal. After submitting the form i am getting success or failure message..let's say failure message. But when i am reopening the modal same message is appearing instead of log in form. After refreshing the page only modal is showing the log in form.
Here is my code....please help me how can i fix it so it will show the log in form when i reopen the modal after submission.
<!-- Sign in feature starts here -->
<div id="sign_in" class="modal fade" role="dialog">
<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">Sign In</h4>
</div>
<div class="modal-body">
<div class="panel-body" id="form">
<form class="form-horizontal" role="form" method="post" id="log-in" >
<fieldset>
<div class="form-group">
<input class="form-control" id="username" placeholder=" Username or Mobile No." type="text" autofocus AutoComplete=off required>
</div>
<div class="form-group">
<input class="form-control" id="password" placeholder=" Enter Password" type="password" autofocus AutoComplete=off required>
</div>
<!-- Change this to a button or input when using this as a form -->
<button class="btn btn-lg btn-success btn-block" type="submit">Sign In</button>
</fieldset>
</form> </div>
</div>
</div>
</div></div>
<!-- Sign In feature ends here -->
<script type="text/javascript">
$(document).ready(function()
{
$(document).on('submit', '#log-in', function()
{
var data = $(this).serialize();
$.ajax({
type : 'POST',
url : '<?php echo site_url('verifylogin');?>',
data : data,
success : function(data)
{
$("#log-in").fadeOut(500).hide(function()
{
$("#form").fadeIn(500).show(function()
{
$("#form").html(data);
if(data != null && data == "success"){ //redirect...
window.location.replace('home.php');
}
});
});
}
});
return false;
});
});
</script>
The problem is at $("#form").html(data);
Why are you removing the form HTML and replacing it with the data you are receiving ?
When are you putting back the form HTML in the modal? It is working after refresh because the page is getting loaded again.
In the previous case you have updated the DOM, removed the form HTML and replaced it with data that you are receiving. So the next time you open the modal you will get to see the same data.
try to change this part
$("#form").html(data);
if(data != null && data == "success")
{ //redirect...
window.location.replace('home.php');
}
TO
$("#form").html(data);
i.e. REMOVE THIS PART
if(data != null && data == "success")
{ //redirect...
window.location.replace('home.php');
}
Also add this div somewhere in your code; This is the div that returns the result from your PHP code.
<div id="form"></div>
If redirecting is your success. Then add the redirecting code in your success definition in the PHP code i.e.
<?php
echo 'please wait! redirecting...';
echo "<script>window.location.href='home.php';</script>";
?>
Ajax does not understand what your PHP means by success. Failure might be success to another person and failure to another person.
In your question, if someone enters wrong username or password. it is likely to redirect Because that is also a success.
Hope this helps

How to produce a modal on form submit instead of a page redirect

To give a little background, I am using the Mailchimp API to add email addresses from the form on my site to my Mailchimp email list. I found an example / snippet here (modified slightly in my code) that passes the emails to my list, but instead of having a page redirect once the form is submitted, I want a modal to pop up (i.e. AJAX-ify it).
Here's what I'm starting with:
HTML:
<form role="form" id="signup" class="formee form-inline" action="subscribe.php" method="post">
<div class="form-group">
<label class="sr-only" for="email-input">Email address
</label>
<div class="email-input-wrapper">
<input type="text" id="email" name="email" class="form-control input-lg" placeholder="name#school.edu" size="40" value="">
</div>
</div>
<div class="form-group">
<button class="btn btn-lg" id="request-invite-btn" type="submit" title="Send" value="Send"> Request Invite </button>
</div>
</form>
Javascript:
<script type="text/javascript">
$(document).ready(function() {
// jQuery Validation
$("#signup").validate({
// if valid, post data via AJAX
submitHandler: function(form) {
$.post("subscribe.php", { email: $("#email").val() }, function(data) {
$('#response').html(data);
});
},
// all fields are required
rules: {
email: {
required: true,
email: true
}
}
});
});
</script>
Subscribe.php:
<?php
require_once 'inc/MCAPI.class.php';
$api = new MCAPI('************************');
// Submit subscriber data to MailChimp
// For parameters doc, refer to: http://apidocs.mailchimp.com/api/1.3/listsubscribe.func.php
$retval = $api->listSubscribe( '********', $_POST["email"], $merge_vars, 'html', false, true );
if ($api->errorCode){
echo "<h4>Please try again.</h4>";
} else {
echo "<h4>Thank you, you have been added to our mailing list.</h4>";
}
?>
Modal HTML (I'm using Bootstrap):
<div class="modal fade" id="emailModal" 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-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Success!</h4>
</div>
<div class="modal-body">
<p>
Thanks for your interest!
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
I also used the MCAPI.class.php doc from the site at the top.
I'm very new to this, so I apologize for posting any unnecessary code. Any direction would be much appreciated. Thanks!
if you just want to display your modal when you server respond you can just do the following :
Doc : http://getbootstrap.com/javascript/#via-javascript
<script type="text/javascript">
$(document).ready(function() {
// Handle submission event
$("#signup").submit(function(event){
event.preventDefault();
});
// jQuery Validation
$("#signup").validate({
// if valid, post data via AJAX
submitHandler: function(form) {
$.post("subscribe.php", { email: $("#email").val() }, function(data) {
//$('#response').html(data);
$('#emailModal').modal();
});
},
// all fields are required
rules: {
email: {
required: true,
email: true
}
}
});
});
</script>
This code just trigger the modal on server response for the example, feel free to improve it for your needs :)
Apparently, this post deal with redirecting and validate jQuery plugin
Stackoverflow post.
So you can bind an event on form submission and just prevent default.

How to POST the data from a modal form of Bootstrap?

I have a page using a modal to get the users email and I want to add it to a list of subscribers (which is a Django model). Here is the modal code for that:
<div id="notifications" class="modal hide fade" role="dialog" ara-labelledby="Notification" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">X</button>
<h4>Subscribe to Status Notifications</h4>
</div>
<form>
<div class="modal-body">
<input type="email" placeholder="email"/>
<p>This service will notify you by email should any issue arise that affects your plivo service.</p>
</div>
<div class="modal-footer">
<input type="submit" value="SUBMIT" class="btn"/>
</div>
</form>
</div>
I tried to look in the Twitter Bootstrap doc but it really is minimal. I want to POST the data to a Django view that's listening forPOST` requests.
This is the bare essential. I am using regex to compare the format of the email before storing the email id. So if the email does not match the regex the view returns an Invalid Email. So I would like to notify the user about that within the modal itself. But I really have no idea as to how to do this. Someone please help.
UPDATE 1
Tried this based on karthikr's answer:
<form id="subscribe-email-form" action="/notifications/subscribe/" method="post">
<div class="modal-body">
<input type="email" placeholder="email"/>
<p>This service will notify you by email should any issue arise that affects your service.</p>
</div>
<div class="modal-footer">
<input id="subscribe-email-submit" type="submit" value="SUBMIT" class="btn" />
</div>
</form>
<script>
$(function(){
$('subscribe-email-form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: "/notifications/subscribe/",
type: "POST",
data: $("subscribe-email-form").serialize(),
success: function(data){
alert("Successfully submitted.")
}
});
});
});
</script>
There is something that is confusing me. What about the onclick event of the modal button?
I got it! I added name="Email" in the line <input type="email" placeholder="email"/>
The Django field is looking for the Email Field. So in my Django view the code is:
request.POST.get("Email", '')
So specifying the field name helps. But it takes me to the URL where I am posting. I want it to display a alert in the same page.
UPDATE 2
So part 1 is working. As in the posts are working. Now I need to show a modal for the success or failure.
Here's what I am trying. So I created this modal with a textarea:
<div id="subscription-confirm" class="modal hide fade in" aria-hidden="true">
<div class="modal-header">
<label id="responsestatus"></label>
</div>
</div>
And the JavaScript:
<script>
$(function(){
$('#subscribe-email-form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: 'notifications/subscribe/',
type: 'POST',
data: $('#subscribe-email-form').serialize(),
success: function(data){
$('#responsestatus').val(data);
$('#subscription-confirm').modal('show');
}
});
});
});
</script>
So the modal comes up, but the data is not set into the label field of the modal.
You need to handle it via ajax submit.
Something like this:
$(function(){
$('#subscribe-email-form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: url, //this is the submit URL
type: 'GET', //or POST
data: $('#subscribe-email-form').serialize(),
success: function(data){
alert('successfully submitted')
}
});
});
});
A better way would be to use a django form, and then render the following snippet:
<form>
<div class="modal-body">
<input type="email" placeholder="email"/>
<p>This service will notify you by email should any issue arise that affects your plivo service.</p>
</div>
<div class="modal-footer">
<input type="submit" value="SUBMIT" class="btn"/>
</div>
</form>
via the context - example : {{form}}.
I was facing same issue not able to post form without ajax.
but found solution , hope it can help and someones time.
<form name="paymentitrform" id="paymentitrform" class="payment"
method="post"
action="abc.php">
<input name="email" value="" placeholder="email" />
<input type="hidden" name="planamount" id="planamount" value="0">
<input type="submit" onclick="form_submit() " value="Continue Payment" class="action"
name="planform">
</form>
You can submit post form, from bootstrap modal using below javascript/jquery code :
call the below function onclick of input submit button
function form_submit() {
document.getElementById("paymentitrform").submit();
}
You CAN include a modal within a form. In the Bootstrap documentation it recommends the modal to be a "top level" element, but it still works within a form.
You create a form, and then the modal "save" button will be a button of type="submit" to submit the form from within the modal.
<form asp-action="AddUsersToRole" method="POST" class="mb-3">
#await Html.PartialAsync("~/Views/Users/_SelectList.cshtml", Model.Users)
<div class="modal fade" id="role-select-modal" tabindex="-1" role="dialog" aria-labelledby="role-select-modal" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Select a Role</h5>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Add Users to Role</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
</form>
You can post (or GET) your form data to any URL. By default it is the serving page URL, but you can change it by setting the form action. You do not have to use ajax.
Mozilla documentation on form action

Categories