jquery duplicate ajax request after submit - javascript

I have a form that opens inside a BS4 modal window. This contents of the form comes from an AJAX request and that part works fine. However, when I submit the form (again an AJAX request) and it returns some info without closing the modal, and then I submit again, it submits twice. If I submit again, it submits 3 times, etc etc, each time one more submit.
What I missing here? This is my code:
<div id="empModal">
... modal stuff here ...
<div id="NewCustomer" class="col-12 view">
<div id="NewCustomerErrors"></div>
<form name="create_account" class="needs-validation" novalidate>
<div class="form-group">
... form stuff here ...
</div>
<div class="pull-right mt-3">Add new customer</div>
<div class="pull-left mt-3">Back to Log In</div>
</form>
</div>
... modal stuff here ...
</div>
Part 1
$(document).ready(function () {
$("#empModal").on('click', '#customerNewSubmit', function(e) {
$('.needs-validation').on('submit', function(e) {
if (!this.checkValidity()) {
e.preventDefault();
e.stopPropagation();
}
e.preventDefault();
e.stopPropagation();
$(this).addClass('was-validated');
var values = $(this).serialize();
doCreateAccount(values);
});
$('.needs-validation').submit();
return false;
});
});
Part 2
function doCreateAccount(values) {
$.ajax({
url: 'ajax_controller.php',
type: 'post',
dataType: 'json',
data: values+'&act=new',
success: function (res) {
if (res.result_success == true) {
$("#userButton").html(res.result_content);
$('#empModal').modal('hide');
} else {
$("#addNewCustomerErrors").html(res.result_content);
}
},
});
}

from your part 1.
$('.needs-validation').submit();
Comment this code because this is submitting a form again after single submission.

Related

Laravel AJAX response loads wrong route/window

I have two routes:
Route::get('/download/{hash}','DownloadController#exists')->name('exists');
Route::post('/download/{hash}','DownloadController#verify')->name('verify');
Procedure:
Basically the user enters a URL e.g. localhost/download/56iq45agosasa the first route is called and the download.blade.php view is shown. There is a form, where the user has to input a password and when the submit button is clicked, an ajax request is sent to the second (post) route.
The DownloadController#verify returns the json but displays it in a blank window (see screenshot) But it should be returned in the download.blade.php view.
Somehow the form disappears and the ajax success function is not called.
Code snippets Download.blade.php:
#section('content')
<div class="container-fluid mt-5">
<div class="row justify-content-md-center">
<div class="col-md-4">
<form method="POST">
<label for="uploadPassword">Password</label>
<input type="password" name="password" class="form-control" id="uploadPassword" placeholder="Password" required="">
<button id="btn-submit" type="submit" class="btn btn-success mt-2">Submit</button>
{{ csrf_field() }}
</form>
</div>
</div>
</div>
#endsection
#push('scripts')
<script type="text/javascript">
$(".btn-submit").click(function(e){
e.preventDefault();
let password = $("input[name=password]").val();
$.ajax({
type:'POST',
url:"",
data:{
password:password
},
success:function(data){
console.log("I don't get shown");
//alert(data.success + " " + data.matches);
}
});
});
</script>
#endpush
DownloadController:
class DownloadController extends Controller
{
public function exists(Request $request, $hash)
{
// Some private mysql queries
// Return the hash to the download view
return view('download',[
'hash' => $hash
]);
}
public function verify(Request $request, $hash)
{
return response()->json(
['success'=>'Got Simple Ajax Request.']
);
}
}
So there are two things that will help improve this code:
Wrap the listener in a document.ready function to ensure it's attached when the button is available in the page. This is necessary if #push will make the script end up above the form declaration in the page.
Listen for the form submit event so you can capture the submit via any of the possible ways that one can submit a form (e.g. by pressing ENTER on an input)
#push('scripts')
<script type="text/javascript">
$(function () {
$("form").on('submit', function (e) {
e.preventDefault();
let password = $("input[name=password]").val();
$.ajax({
type:'POST',
url:"",
data:{
password:password
},
success:function(data){
console.log("I don't get shown");
//alert(data.success + " " + data.matches);
}
});
});
});
</script>
#endpush
The problem here is that the form gets submitted.
Instead of overriding button click with your jQuery function, use it to change submit handler like so
Prevent Default on Form Submit jQuery
Make sure you put id on the form.

Form validation quit working after adding ajax submission to page

I had a regular form submission page the old fashion way that used form validation javascript that worked fine. See below. I changed the page to submit via ajax and now the form validation is skipped. How do I "combine" the two to make it all work? I assume I need to move the validation in the ajax post somehow, but I can't figure it out. Any help would be appreciated.
<form class="card" name="myform" id="myform">
<div class="card-body">
<h3 class="card-title">Add New Blog Post</h3>
<div id='response'></div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="form-label">Blog Title</label>
<input name="subject" type="text" required class="form-control" id="subject" required>
<div class="is-valid"></div>
</div>
</div>
</div>
</form>
<script>
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles
//to
var forms = document.getElementsByClassName('card');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
<script>
$(document).on("click","#submitbtn",function(e){
//Prevent Instant Click
e.preventDefault();
$(document).ajaxSend(function(event, request, settings) {
$('#loading-indicator').show();
$("#submitbtn").prop('disabled', true);
});
$(document).ajaxComplete(function(event, request, settings) {
$('#loading-indicator').hide();
$("#output").fadeTo(4000, 500).slideUp(500, function(){
$("#output").slideUp(500);
});
$("#myform")[0].reset();
$("#submitbtn").prop('disabled', false);
});
var formData = new FormData($('#myform')[0]);
$.ajax({
url: 'add_blog_do.php',
enctype: 'multipart/form-data',
type: 'POST',
data: formData,
success: function(response) {console.log(response);},
contentType: false,
processData: false,
cache: false
});
});
</script>
You've attached your AJAX call to the click event on your submit button. This fires before the submit event. Since you're invoking event.preventDefault() inside the submit button click handler, the submit event is never running.
You'll want to instead fire your AJAX call in your submit event handler or move it into the click handler. Once the form passes the validity check, you can fire off your actual AJAX call.
An example:
<form class="card" name="myform" id="myform">
<div class="card-body">
<h3 class="card-title">Add New Blog Post</h3>
<div id='response'></div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="form-label">Blog Title</label>
<input name="subject" type="text" required class="form-control" id="subject" required>
<div class="is-valid"></div>
</div>
</div>
</div>
</form>
<script>
$(document).on("click","#submitbtn",function(e){
//Prevent Instant Click
e.preventDefault();
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('card');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
// Check and see if the form is INVALID
// if it is, it currently console logs.
// You may want to do something else here but that's up to you
if (form.checkValidity() === false) {
console.log('Form validation failed')
} else {
// If the form DOESN'T fail, we'll enter this block and run our AJAX
// call as normal
form.classList.add('was-validated');
var formData = new FormData($('#myform')[0]);
$.ajax({
url: 'add_blog_do.php',
enctype: 'multipart/form-data',
type: 'POST',
data: formData,
success: function(response) { console.log(response); },
contentType: false,
processData: false,
cache: false
});
}
});
}, false);
// AJAX Event Listeners for ajaxSend and ajaxComplete
$(document).ajaxSend(function(event, request, settings) {
$('#loading-indicator').show();
$("#submitbtn").prop('disabled', true);
});
$(document).ajaxComplete(function(event, request, settings) {
$('#loading-indicator').hide();
$("#output").fadeTo(4000, 500).slideUp(500, function(){
$("#output").slideUp(500);
});
$("#myform")[0].reset();
$("#submitbtn").prop('disabled', false);
});
});
</script>

How to post form inside load() div

I have form with $_POST type from second page,on first page i've loaded the form with this code :
<div class="option_dialog" id="search">
<div class="close_option">Search <img onclick="search()" style="float:right;height:20px" src="img/close.png">
</div>
<div id="search_content" style="overflow:scroll;max-height:400px">
<script>
$('#first_page_div').load('second_page.php #second_page_form');
</script>
</div>
</div>
When the function search() called using onclick the above code will excuted and load the form from second page...then i submit the form using this code :
$(function () {
$('#form_id').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'second_page.php',
data: $('#form_id').serialize(),
success: function () {
$('#first_page_search_result').load('second_page.php #searched_result');
search_result();
}
});
});
});
When form submited via ajax on first page,the second page should process his/her request and return the searched result on first page and execute search_result() which is another hidden div will be shown after returned result.
please tell me how to make this work?regards

How do I submit Ajax form from javascript and update target div?

I have a bootstrap modal popup, with an ajax helper form on which I need to do some js validation prior to submitting. If validation fails, I'm showing some extra things on the form. If my validation passes I want to submit the form, and update a specific div with a PartialView. To do the validation, I'm calling a js function from a button on the form, and passing in the form. If my validation passes, I call the form's submit.
This works, but the PartialView displays full page, rather than in the target div. The form works properly and updates the target div when I submit directly from a submit input on the form instead of submitting from the js function.
How do I update my target div when submitting from js function?
See code:
function validateActionItem(sender) {
var $formToSubmit = $(sender).closest('form');
$formToSubmit.submit();
}
<div id="MyDivContainer" class="col-lg-12">
#Html.Action("MyPartial", "MyController", new { ID = Model.ID })
<div class="modal fade" id="MyModal">
<div class="modal-dialog modal-lg">
<div class="modal-content">
#using (Ajax.BeginForm("MyAction", "MyController",
new { ID = Model.ID },
new AjaxOptions {
UpdateTargetId = "MyDivContainer",
OnSuccess = "closeModal()"
},
new { #id = "MyForm"}))
{
<div class="modal-body">
<!-- My form fields -->
</div>
<div class="modal-footer">
<button class="btn btn-primary" role="button"
type="button" onclick="validate($(this))">
Validate Submit
</button>
</div>
}
</div>
</div>
</div>
My _Layout.cshtml contains...
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
The MyAction action returns PartialView(model).
Can anyone point to what I'm doing wrong, and why my PartialView displays full page when submitting the form from javascript but properly updates the target div when I replace the button with a regular input submit on the form?
UPDATE
I have refactored the submit like so, but it's never getting called for some reason?
jQuery().ready(function () {
$("#MyForm").submit(function (e) {
$.ajax({
url: "/MyController/MyAction",
type: "POST",
dataType: "html",
contentType: false,
data: $("#MyForm").serialize(),
success: function (partialViewResult) {
closeModal();
$("#MyDivContainer").empty().append(partialViewResult);
}
});
});
});
UPDATE 2
I discovered that the jquery script must be after the modal popup in my cshtml, so now I'm reaching the submit event of my input button. However, I can't get to my controller action... the ajax call errors.
$("#MyForm").submit(function (e) {
e.preventDefault();
var id = $('#ID').val();
alert("submit function called");
alert("ID: " + id);
$.ajax({
url: "/MyController/MyAction",
type: "POST",
dataType: "html",
data: { ID: (id)},
error: alert("Error!")
});
});
I hit the "Error" alert, and don't know how to debug this to figure out what's wrong.
I've got it working. Thanks everyone for the help. Here's the code:
For whatever reason, the script has to be placed after the modal popup markup.
<script type="text/javascript">
$("#MyForm").submit(function (e) {
e.preventDefault();
//getting fields to be checked
if //checking failed validations
{
//doing some things if val fails
}
else
{
var id = $('#ID').val();
$.ajax({
url: "/MyController/MyAction",
type: "POST",
dataType: "html",
data: {ID: id},
success: function (partialViewResult) {
closeMyModal();
$("#MyDivContainer").empty().append(partialViewResult);
}
});
}
});
</script>

submitting a form via AJAX

I have a form that looks as following:
<form accept-charset="UTF-8" action="{{ path("fos_user_resetting_send_email") }}" method="post">
<div class="field">
<label for="username">Email:</label>
<input class="text" id="passwordEmail" name="username" required="required" size="30" type="text">
<div class="field-meta">Put in your email, and we send you instructions for changing your password.</div>
</div>
<div class="field">
<input id="submitPasswordRequest" class="full-width button" name="commit" tabindex="3" type="submit" value="Get Password">
</div>
<div class="field center">
Nevermind, I Remembered
</div>
I am trying to do the post via AJAX, so I did a simple test like this:
$("#submitPasswordRequest").click(function() {
var username = $('#passwordEmail').value();
console.log(username);
/*
$.ajax({
type: "POST",
url: "/resetting/send-email",
data: { username: username}, // serializes the form's elements.
success: function( data ) {
console.log(data); // show response from the php script.
}
});
*/
return false;
});
However it seems that the click function is not triggered and it goes to posting the form via the regular form action. What am I doing wrong here? I want to handle this via AJAX.
When you click upon the button, you simply submit the form to the back-end. To override this behavior you should override submit action on the form. Old style:
<form onsubmit="javascript: return false;">
New style:
$('form').submit(function() { return false; });
And on submit you want to perform an ajax query:
$('form').submit(function() {
$.ajax({ }); // here we perform ajax query
return false; // we don't want our form to be submitted
});
Use jQuery's preventDefault() method. Also, value() should be val().
$("#submitPasswordRequest").click(function (e) {
e.preventDefault();
var username = $('#passwordEmail').val();
...
});
Full code: http://jsfiddle.net/HXfwK/1/
You can also listen for the form's submit event:
$("form").submit(function (e) {
e.preventDefault();
var username = $('#passwordEmail').val();
...
});
Full code: http://jsfiddle.net/HXfwK/2/
jquery and ajax
$('form id goes here).submit(function(e){
e.preventDefault();
var assign_variable_name_to_field = $("#field_id").val();
...
if(assign_variable_name_to_field =="")
{
handle error here
}
(don't forget to handle errors also in the server side with php)
after everyting is good then here comes ajax
datastring = $("form_id").serialize();
$.ajax({
type:'post',
url:'url_of_your_php_file'
data: datastring,
datatype:'json',
...
success: function(msg){
if(msg.error==true)
{
show errors from server side without refreshing page
alert(msg.message)
//this will alert error message from php
}
else
{
show success message or redirect
alert(msg.message);
//this will alert success message from php
}
})
});
on php page
$variable = $_POST['field_name']; //don't use field_id if the field_id is different than field name
...
then use server side validation
if(!$variable)
{
$data['error']= true;
$data['message'] = "this field is required...blah";
echo json_encode($data);
}
else
{
after everything is good
do any crud or email sending
and then
$data['error'] = "false";
$data['message'] = "thank you ....blah";
echo json_encode($data);
}
You should use the form's submit handler instead of the click handler. Like this:
$("#formID").submit(function() {
// ajax stuff here...
return false;
});
And in the HTML, add the ID formID to your form element:
<form id="formID" accept-charset="UTF-8" action="{{ path("fos_user_resetting_send_email") }}" method="post">
You need to prevent the form from submitting and refreshing the page, and then run your AJAX code:
$('form').on('submit',function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/resetting/send-email",
data: $('form').serialize(), // serializes the form's elements.
success: function( data ) {
console.log(data); // show response from the php script.
}
});
return false;
});

Categories