Laravel Submit Form Without Page Refresh Using Ajax - javascript

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){ ... }

Related

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 would I make data disappear when successfully submitted

I want user inserted data to disappear from the input field when it is submitted successfully and it should be in the field if it fails to submit e.g. such as duplicate of data.
I have a form that will accept user input and submit it to the database and I use JavaScript to communicate with my form and PHP Script, so now I want when data is successfully submitted it should disappear and when it fails it should be there.
This is the HTML code
<form role="form">
<div class="box-body">
<div class="form-group">
<label for="inputClass">Class Title</label>
<input type="class" class="form-control" id="inputClass" placeholder="Class Title">
</div>
<div class="form-group">
<label for="selectSection">Class Section</label>
<select name="selectSection" id="selectSection" class="form-control" required="required">
<option selected disabled>Class Section</option>
<?php echo(getSection()); ?>
</select>
</div>
<span id="loading"><img src="../assets/images/loading.gif" height="40px" width="100%" alt="Ajax Indicator" /></span>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-primary" id="registerClass">Submit</button>
</div>
</form>
And the JavaScript code is
<script type="text/javascript">
$(document).ready(function() {
$('#loading').hide();
$('#registerClass').click(function(){
$('#loading').show();
$.post("check-class.php", {
inputClass: $('#inputClass').val(),
selectSection: $('#selectSection').val()
}, function(response){
$('#resultInfo').fadeOut();
setTimeout("finishAjax('resultInfo', '"+escape(response)+"')", 2000);
});
return false;
});
});
function finishAjax(id, response) {
$('#loading').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
</script>
I expected to disappear when successfully but unfortunately it is still there
Add id attribute in form tag and use that id to reset form data in finishAjax function like:
document.getElementById(' ID THAT MENTIONED IN FORM TAG ').reset();
You should reset the from by adding an Id to from like
<form role="form" id ="myFrom">
and then reset from, once you received response from server and want to clear the form values
document.getElementById('myFrom').reset();
You can add this reset logic in finishAjax function
function finishAjax(id, response) {
$('#loading').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
document.getElementById('myFrom').reset();
}

Form get submitted even the form validation fails

I am using http://www.formvalidator.net/index.html to validate my form but the form gets submitted even when the validation get failed.
Form code:
<form name="add-todo" class="form-horizontal" action="" method="post">
<h5>Add New Item</h5>
<div class="form-group">
<div class="col-md-12">
<input type="text" data-validation="required" class="form-control" id="todo-text-input" name="todo-text">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<button type="submit" class="btn btn-primary btn-add">Add</button>
</div>
</div>
</form>
jQuery code:
$(document).ready(function() {
$.validate({
modules: 'security'
});
$('form[name=add-todo]').submit(function(e) {
e.preventDefault();
var text = $("#todo-text-input").val();
$('.btn-add').text('Saving ....');
$.ajax({
url: this.action,
type: this.method,
data: {
text: text
},
success: function(response) {
$("#todo-text-input").empty();
$('.messages').removeClass('hide-element');
$('.alert').addClass('alert-success');
$('.alert').text('To do item added successfully.');
$('.alert').fadeTo(2000, 500).slideUp(500, function() {
$('.alert').slideUp(500);
});
}
});
});
});
dont use submit button. You can use
<button type="button" class="btn btn-primary btn-add">Add</button>
after that check your validation status. if its valid then submit the form.
<input type="text" data-validation="required" class="form-control" id="todo-text-input" name="todo-text">
In your input field you don't need to use data-validation="required" just use required like
<input type="text" required class="form-control" id="todo-text-input" name="todo-text">
Please change you form validation code configuration like this:
$.validate({
form : '#registration-form',
modules : 'security',
onSuccess : function($form) {
alert('The form '+$form.attr('id')+' is valid!');
// write your ajax code to submit form data on server
return false; // Will stop the submission of the form
}
});
For more info follow:
http://www.formvalidator.net/index.html#configuration

Single click event acts as double click event

I'm using Ajax to submit the login form without refreshing the page. I've added a function to see whether the data returns 'error' (which comes up when the user enters an incorrect email/password). If it does not return 'error', the user has been logged in and will be transferred to the page within 2 seconds.
The problem is that my button acts like a double-click button and I cannot see why. This is my JS file:
$(function() {
$("#goLogin").click(function() {
$.ajax({
type: "POST",
url: "db-requests/db-login.php",
data: $("#loginForm").serialize(),
success: function(data,textStatus,jqXHR){ finishLogin(data,textStatus,jqXHR); }
});
});
});
function finishLogin( data , textStatus ,jqXHR ) {
if ( data == "error" ) {
$('.errorMsg').fadeIn(500).hide();
$('.succesMsg').fadeOut(300).hide();
} else {
$('.succesMsg').fadeIn(500).show();
$('.errorMsg').fadeOut(300).hide();
setTimeout("location.href = 'protected.php';",2000);
}
}
I've tried placing it between the document_ready tags, but that isn't working either.
Part of the HTML code:
<div class="login form">
<div class="login-header">Please Login</div>
<form method="post" id="loginForm" name="form">
<label for="email" class="short">Email*</label>
<input type="text" name="email" id="email" class="required" placeholder="" />
<label for="password" class="short">Password *</label>
<input type="password" name="password" id="password" class="required" placeholder="" maxlength="15" />
</form>
<div id="login-functions">
<div class="loginbtn-container">
<input type="submit" id="goLogin" name="goLogin" class="button green" value="Login" />
</div>
<div class="login form actions">
<p class="register account">Register an account</p>
<p class="request password">Lost your password?</p>
</div>
</div>
</div>
<div class="errorMsg">Incorrect. Please recheck your details</div>
<div class="succesMsg"><b>You've been logged in!</b> Please wait while we transfer you</div>
$('.errorMsg').fadeIn(500).hide();
$('.succesMsg').fadeOut(300).hide();
did you mean tto hide both? I see the click is working fine, though you should ideally do submit
Take your submit inside the form, and prevent normal form submit using preventDefault()
$("#goLogin").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "db-requests/db-login.php",
data: $("#loginForm").serialize(),
success: function(data,textStatus,jqXHR){ finishLogin(data,textStatus,jqXHR); }
});
});
Please move your submit button inside the form closing tag first
<input type="submit" id="goLogin" name="goLogin" class="button green" value="Inloggen" />
The above button is placed after the </form> tag.
Because you click on input type submit and progress Ajax on it; it cause submit 2 times.
To avoid it, you can use as Zach Leighton said above ; or use as below
$("#goLogin").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "db-requests/db-login.php",
data: $("#loginForm").serialize(),
success: function(data,textStatus,jqXHR){ finishLogin(data,textStatus,jqXHR); }
});
});

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