How to display modal form after submitting through AJAX - javascript

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

Related

Return back to location on page after Post request using PHP LARAVEL

I am trying to build a one page web page using PHP laravel and all its features.
I use javascript to scroll through the pages when pressing specific links.
At the bottom of the page I have a form that runs some php code (sends an email,...)
After this POST request I redirect back to my webpage.
The problem is that when I redirect back I see the top of the page and the contact form and error or success codes are at the bottom of my page near the FORM.
This is why I am looking for a way to automatically scroll/move to the contact form after the post request just like i do when pressing the link button.
HTML:
#if (count($errors) > 0)
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert">×</button>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
#endif
<form method="post" action="sendemail">
{{ csrf_field() }}
<div class="form-group">
<label for="exampleFormControlInput1">Name</label>
<input type="text" class="form-control" name="name" id="exampleFormControlInput1">
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Email</label>
<input type="email" class="form-control" name="email" id="exampleFormControlInput1">
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Message</label>
<textarea class="form-control" name="message" id="exampleFormControlTextarea1" rows="8"></textarea>
</div>
<div class="form-group">
<input type="submit" name="send" class="btn btn-secondary" value="Send" />
</div>
</form>
</div>
PHP Route:
Route::post('/sendemail', 'App\Http\Controllers\SendEmailController#send');
PHP Controller:
function send(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email',
'message' => 'required'
]);
$data = array(
'name' => $request->name,
'email' => $request->email,
'message' => $request->message
);
Mail::to($request->email)->send(new SendMailValidation($data));
return back()->with('success', 'Thank you!');
}
Javascript (atm only used for client side browsing when pressing a link item):
let contactLinkItem = document.querySelector("#contactLinkItem");
contactLink.addEventListener("click", navigateContact, false);
function navigateContact() {
contactLinkItem.scrollIntoView({ behavior: "smooth" });
}
You can check if errors bag has any messages then call javascript function that you already created above to trigger scrolling behavior
#if($errors->any())
<script>
navigateContact()
</script>
#endif
// Your old code
let contactLinkItem = document.querySelector("#contactLinkItem");
contactLink.addEventListener("click", navigateContact, false);
function navigateContact() {
contactLinkItem.scrollIntoView({ behavior: "smooth" });
}
Recommendation:
Use Ajax calls with API to submit your forms (Or Livewire), and you have the ability to show validation errors without scrolling or even leaving the page. This is the best for your users experience.

open modal bootstrap on submit form

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');

Form preventDefault then activate again not working

I have a little form in my modal which looks like this:
<form name="form" action="" method="post">
<div class="modal-body">
<input type="text" name="edited_id" value="" id="edited_id" class="hidden"/>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="edited_name" class="form-control" id="edit_name" value="">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="edited_email" class="form-control" id="edit_email" value="">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" name="edit_submit" class="btn btn-primary" value="Edit user"/>
</div>
</form>
and I want to prevent the form to submit if the user enters an email that it is already in my database. I have the following script:
$("#check_email").click(function() {
var email = $(this).parent().siblings().find("#email").val();
var that = $(this);
$(this).parent().parent().submit(function( event ) {
$.get("php/verify_email.php", {email: email}, function(data){
if(data === "")
{
that.parent().parent().unbind('submit').submit();
}
else {
alert(data);
event.preventDefault();
}
});
});
});
The problem is that if I put the even.preventDefault() in that else condition, the $.get() seems to not trigger, because I guess that the form submits faster. Otherwise if I put the event.preventDefault() right after the .submit(function( event ) { then I can't unbind the submit to work after the user changes the email.
What I am doing wrong?
P.S.
My php file looks like this:
<?php
include "connect.php";
if(isset($_GET['email']) && !empty($_GET['email'])){
$sql = "SELECT * FROM users WHERE email='".$_GET['email']."';";
$result = $conn->query($sql);
if ($result->num_rows > 0){
echo "The email is already in our database. Please try another one!";
}
}
?>
I understand you would like to avoid form sending if email is already used.
At first, where is your magic button to do this :D ?
I added button in example.
You must be sure that your "this" is element you want, creating structure like .parent().parent().parent() everywhere is stupid - one change and everything not work.
Next thing to avoid form submit you must return false; inside submit function, preventDefault() work with <a> or other events like click
And next.. if you send ajax your callback function can back to your browser after your submit click.
For example checkClick -> sendAjax -> submitClick -> ajaxBack
And next :D - PHP: Your form have method="post" but server use $_GET
So.. if you send post you must use $_POST if get than $_GET
This time you used $.get so i dont know your ajax configuration but this can cause errors.
Here is some code but im sure this is not final implementation you want, but it should help :)
sorry for english btw.
html:
<form name="form" action="" method="post">
<div class="modal-body">
<input type="text" name="edited_id" value="" id="edited_id" class="hidden"/>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="edited_name" class="form-control" id="edit_name" value="">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" id="email" name="edited_email" class="form-control" id="edit_email" value=""> <button type="button" id="check_email" data-dismiss="modal">check</button>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" name="edit_submit" class="btn btn-primary" value="Edit user"/>
</div>
</form>
javascript:
$("#check_email").click(function() {
var email = $(this).parent().find("#email").val();
var that = $(this);
alert(email);
console.log($(this).parent().parent().parent())
$(this).parent().parent().parent().submit(function( event ) {
$.get("php/verify_email.php", {email: email}, function(data){
if(data === "")
{
that.parent().parent().unbind('submit').submit();
}
else {
alert(data);
event.preventDefault();
}
});
return false;
});
});

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