Ajax form submitting twice? - javascript

I couldn't find the mistake but it submit form twice . Please help me what i missed in this .
$('#supplierForm').on('submit', function(e) {
e.preventDefault();
if ($(this).valid()) {
$.ajax({
async: false,
data: $("#supplierForm").serialize(),
url: '{{ url('supplier_edit_new') }}',
type: 'POST',
success: function (data) {
window.location.reload();
}
});
}
return false;
})
;
For validating script
$("document").ready(function(){
$('#supplierForm').validate({
errorClass: 'help-block',
rules: {
'line1': "required",
'line2': "required",
'suburb': "required",
'state' : "required",
'country':"required",
},
messages: {
'line1':{required: "Please enter supplier's address."},
'line2':{required: "Please enter supplier's address."},
'suburb':{required: "Please enter supplier's suburb."},
'state':{required: "Please select a state"},
'country':{required: "Please enter country"},
'postcode':{required: "Please enter postcode"},
},
highlight: function (element) {
$(element).parent().parent().removeClass("success").addClass("error");
},
unhighlight: function (element) {
$(element).parent().parent().removeClass("error").addClass("success");
}
}); // validate
});
For html
{{ form_widget(form.submit,{'attr':{'class':'btn btn-primary btn-large btn-style','value':'Save changes'} }) }}
it generate
<button id="ovc_bundle_productbundle_supplier_submit" class="btn btn-primary btn-large btn-style" value="Save changes" name="ovc_bundle_productbundle_supplier[submit]" type="submit">Save / Update Details</button>

Try this to prevent binding the event multiple times,
$('#supplierForm').off('submit');
$('#supplierForm').on('submit', function(e) {
e.preventDefault();
if ($(this).valid()) {
$.ajax({
async: false,
data: $("#supplierForm").serialize(),
url: '{{ url('supplier_edit_new') }}',
type: 'POST',
success: function (data) {
window.location.reload();
}
});
}
return false;
})

Related

How to prevent page from refreshing after ajax submit

I just started using Ajax function in my work and I'm not very familiar with it. I have this problem that when I submit data, it submits without refreshing the page, but on a second time when trying to submit, the page refreshes before submitting. I've used the e.preventDefault() to prevent the page from refreshing but it is not working for me. It just seems there is something I'm not doing right.
This is my Ajax code
<!--AJAX PROCESS TO SUBMIT CHECKED COURSES-->
$(document).ready(function(){
loadNewCourse();
loadDelTable();
$('#submit').click(function(){
$('#form').submit(function(e){
e.preventDefault();
var in_arr = [],
name = ("<?php echo $_SESSION['name']?>"),
email = ("<?php echo $_SESSION['email']?>"),
regno = ("<?php echo $_SESSION['regno']?>"),
level = ("<?php echo $_SESSION['level']?>"),
dept = ("<?php echo $_SESSION['dept']?>"),
semester = ("<?php echo $_SESSION['semester']?>");
$('.inChk').each(function(i){
var checked = $(this).is(':checked');
if(checked){
in_arr.push($(this).val());
}
});
$.ajax({
url: 'submit.php',
type: 'POST',
cache: false,
async: false,
data: {
post_inId : in_arr,
name : name,
email : email,
regno : regno,
level : level,
dept : dept,
semester : semester
},
success: function(data){
loadNewCourse();
loadDelTable();
// setTimeout(function(){
// $('#regModal').modal('hide');
// }, 1000);
$('body').removeAttr('style');
$('#regModal').removeAttr('style');
$('.modal-backdrop').remove();
swal({
// "Success", "Registration successful", "success"
position: "top-end",
type: "success",
title: "Registration successful",
showConfirmButton: false,
timer: 2000
})
},
error: function(data){
swal("Oops...", "Registration failed.", "error");
}
});
});
});
////////////////////////////////////////////////////////////////////////////////////////
// PROCESS AJAX DELETE ON CHECKBOX SELECT
$('#deleteCheck').click(function(){
$('#delform').submit(function(e){
e.preventDefault();
var id_arr = [],
regno = ("<?php echo $_SESSION['regno']?>"),
level = ("<?php echo $_SESSION['level']?>");
$('.delChk').each(function(i){
var checked = $(this).is(':checked');
if(checked){
id_arr.push($(this).val());
}
});
swal({
title: "Are you sure you want to delete selected courses?",
text: "You can add these courses by registering again!",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes, delete!",
confirmButtonClass: 'btn btn-success',
cancelButtonClass: 'btn btn-danger',
closeOnConfirm: false
},
function(isConfirm){
if(isConfirm){
$.ajax({
type: "POST",
url: "submit.php",
data: {
post_id : id_arr,
regno : regno,
level : level
},
cache: false,
async: false,
success: function(data){
// console.log(data);
loadDelTable();
loadNewCourse();
swal({
// "Success", "Registration successful", "success"
position: "top-end",
type: "success",
title: "Delete successful",
showConfirmButton: false,
timer: 2000
})
},
error: function(data){
swal("Oops...", "Delete failed.", "error");
}
});
}else{
// alert('isNotConfirm and is not success');
swal("Oops...", "Delete failed", "error");
}
});
return false;
///////////////////////////////////////////////////////////////////////////////////////////
});
});
function loadNewCourse(){
$.ajax({
url: 'processReg.php',
type: 'POST',
cache: false,
async: false,
data: {
loadit : 1
},
success: function(disp){
$("#reveal").html(disp).show();
}
});
}
function loadDelTable(){
$.ajax({
url: 'delete_tbl.php',
type: 'POST',
cache: false,
async: false,
data: {
loadDel : 1
},
success: function(deldisp){
$("#showRegtbl").html(deldisp).show();
}
});
}
});
And this is the page displaying submitted data
<div class="" style="margin:auto;margin-top:0;text-align:center">
<div class="" >
<h2 class="#" style="font-family: 'proxima-nova','Helvetica Neue',Helvetica,arial,sans-serif;letter-spacing:5px;font-weight:100;color:#061931;">Welcome!</h2>
<p style="width:100%;font-size:14px;text-align:center;padding:5px;background:whitesmoke;padding:20px;">If this is your first visit, click on <b>Register Courses</b> to register courses available for you. <br>If you are re-visiting, you can continue where you left off.<br><span class="btn btn-md btn-primary" style="letter-spacing:3px;margin-top:10px;"><b>Register Courses</b></span></p>
</div>
</div><br>
<!--Display Courses that are available-->
<span id="reveal"></span>
<!--Table to display courses registered-->
<span id="showRegtbl"></span>
</div>
</div>
I've been stuck in this for more than 3days now. Can anyone here help me out pls?
I think you misunderstood the submission of the form and even handling.
The default action of the form ie submit can be done with input type="submit" or <button>
The default
<h2> Form default action </h2>
<form action="">
<input type="hidden" id="someInput" value="hey">
<input type="submit" value="submit">
</form>
To prevent form's default action you can do 2 things.
Avoid using type="submit" or button
Do something like this
function customForm(){
alert("Hey this is custom handler, dont worry page will not refresh...!");
}
<h2> Form with custom action </h2>
<form action="">
<input type="hidden" id="someInput" value="hey">
<input type="button" value="submit" onclick="customForm()">
</form>
Use event.preventDefault()
$('#myform').submit(function(e){
e.preventDefault();
alert("custom handler with preventDefault(), no reload no worries...!");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2> Form with custom handler using preventDefault() </h2>
<form id="myform" action="">
<input type="hidden" id="someInput" value="hey">
<input type="submit" value="submit" onsubmit="customForm(this)">
</form>
For any queries comment down.
Calling $("#form").submit(function() { ... }) creates a handler for the next time the form is submitted. Doing this inside the handler for $("#submit").click() is not correct. Clicking the submit button will establish a handler for the next submission, but then the default action will submit the form immediately, which refreshes the page. Putting e.preventDefault() inside the click handlers would prevent the reload, but then you would have to click twice to submit the form (and this wouldn't actually work, because the default action of a submit button is to trigger the submit event, and you're preventing that).
Just create submit handlers for each form, without doing it inside a click handler.
$(document).ready(function() {
loadNewCourse();
loadDelTable();
$('#form').submit(function(e) {
e.preventDefault();
var in_arr = [],
name = ("<?php echo $_SESSION['name']?>"),
email = ("<?php echo $_SESSION['email']?>"),
regno = ("<?php echo $_SESSION['regno']?>"),
level = ("<?php echo $_SESSION['level']?>"),
dept = ("<?php echo $_SESSION['dept']?>"),
semester = ("<?php echo $_SESSION['semester']?>");
$('.inChk').each(function(i) {
var checked = $(this).is(':checked');
if (checked) {
in_arr.push($(this).val());
}
});
$.ajax({
url: 'submit.php',
type: 'POST',
cache: false,
async: false,
data: {
post_inId: in_arr,
name: name,
email: email,
regno: regno,
level: level,
dept: dept,
semester: semester
},
success: function(data) {
loadNewCourse();
loadDelTable();
// setTimeout(function(){
// $('#regModal').modal('hide');
// }, 1000);
$('body').removeAttr('style');
$('#regModal').removeAttr('style');
$('.modal-backdrop').remove();
swal({
// "Success", "Registration successful", "success"
position: "top-end",
type: "success",
title: "Registration successful",
showConfirmButton: false,
timer: 2000
})
},
error: function(data) {
swal("Oops...", "Registration failed.", "error");
}
});
});
////////////////////////////////////////////////////////////////////////////////////////
// PROCESS AJAX DELETE ON CHECKBOX SELECT
$('#delform').submit(function(e) {
e.preventDefault();
var id_arr = [],
regno = ("<?php echo $_SESSION['regno']?>"),
level = ("<?php echo $_SESSION['level']?>");
$('.delChk').each(function(i) {
var checked = $(this).is(':checked');
if (checked) {
id_arr.push($(this).val());
}
});
swal({
title: "Are you sure you want to delete selected courses?",
text: "You can add these courses by registering again!",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes, delete!",
confirmButtonClass: 'btn btn-success',
cancelButtonClass: 'btn btn-danger',
closeOnConfirm: false
},
function(isConfirm) {
if (isConfirm) {
$.ajax({
type: "POST",
url: "submit.php",
data: {
post_id: id_arr,
regno: regno,
level: level
},
cache: false,
async: false,
success: function(data) {
// console.log(data);
loadDelTable();
loadNewCourse();
swal({
// "Success", "Registration successful", "success"
position: "top-end",
type: "success",
title: "Delete successful",
showConfirmButton: false,
timer: 2000
})
},
error: function(data) {
swal("Oops...", "Delete failed.", "error");
}
});
} else {
// alert('isNotConfirm and is not success');
swal("Oops...", "Delete failed", "error");
}
});
return false;
///////////////////////////////////////////////////////////////////////////////////////////
});
function loadNewCourse() {
$.ajax({
url: 'processReg.php',
type: 'POST',
cache: false,
async: false,
data: {
loadit: 1
},
success: function(disp) {
$("#reveal").html(disp).show();
}
});
}
function loadDelTable() {
$.ajax({
url: 'delete_tbl.php',
type: 'POST',
cache: false,
async: false,
data: {
loadDel: 1
},
success: function(deldisp) {
$("#showRegtbl").html(deldisp).show();
}
});
}
});
If you had multiple submit buttons in the same form you would instead assign click handlers to each button, but not create submit handlers for the form.
Thanks everyone for the assistance. I did some debugging on my end and was able to fix the issue by removing the form tags from the Add and Delete scripts and then include them in the page displaying the submitted data.
Like this...
<div class="" style="margin:auto;margin-top:0;text-align:center">
<div class="" >
<h2 class="#" style="font-family: 'proxima-nova','Helvetica Neue',Helvetica,arial,sans-serif;letter-spacing:5px;font-weight:100;color:#061931;">Welcome!</h2>
<p style="width:100%;font-size:14px;text-align:center;padding:5px;background:whitesmoke;padding:20px;">If this is your first visit, click on <b>Register Courses</b> to register courses available for you. <br>If you are re-visiting, you can continue where you left off.<br><span class="btn btn-md btn-primary" style="letter-spacing:3px;margin-top:10px;"><b>Register Courses</b></span></p>
</div>
</div><br>
<!--Display Courses that are available-->
<form id='form' action='POST' href='#'>
<span id="reveal"></span>
</form>
<!--Table to display courses registered-->
<form id='delform' action='POST' href='#'>
<span id="showRegtbl"></span>
</form>
</div>
</div>
Is there a more proper way to do this or this is just okay? Thank you for the help so far.

Alert function not working after ajax call in laravel

<script>
$(function () {
$("#portal_register_post").validate({
rules: {
user_email: {
required:true,
email: true,
maxlength: 50
},
CreatePwd: {
required:true,
maxlength: 50,
minlength: 8,
pwcheck:true
},
confirmpassword: {
required:true,
equalTo: "#CreatePwd"
}
},
messages: {
user_email: {
required: "Please Enter E-mail",
},
CreatePwd: {
required: "Please Enter Password",
},
confirmpassword: {
required: "Please Enter Confirm Password",
}
},
submitHandler: function(form) {
var $form_id = '#register_post';
var form = document.forms.namedItem("register_post");
var formdata = new FormData(form);
var $inputs = $($form_id+' :input:not(input[name=_token] :input)');
$inputs.prop("disabled", true);
request = $.ajax({
async: true,
type: "POST",
dataType: "json",
contentType: false,
url: "{{ URL::to('/portal/register') }}",
data: formdata,
processData: false,
success: function (result) {
alert(result);
},
timeout: 1000000
});
request.always(function () {
$inputs.prop("disabled", false);
});
}
});
});
</script>
route:
Route::get('/portal/register', 'PortalController#register');
Route::post('/portal/register', ['as' => 'portal.register.post', 'uses' => 'PortalController#postRegister']);
In the above code I am simply want to get response in my alert function after ajax success but what happen when I click on form submit button then it show status code: 302 and not able to get response in alert function. I don't know where I am doing wrong? Please help me to solve this.
Thank you

how to validate a same form in different button click using jquery

edit-txt,updatePassword are two buttons in a single form superAdminDetailsForm . i want to valide this form in both button click. I wrote form validation on each button click .but it doesn't work. edit-txt button is type of text and update password is type of button
$().ready(function() {$('#edit-txt').on('click', function() {
$("#superAdminDetailsForm").validate({
rules: {
superadminEmail:{
required:true,
email:true
},
},
messages: {
superadminEmail:"Please enter your Email id"
},
submitHandler: function(){
var formData =$("#superAdminDetailsForm").serialize();
$.ajax({
url:'/accounts',
type:'post',
datatype: 'json',
data: formData,
success : function(response){
if(response == "true"){
window.location='/accounts';
} else {
alert("false")
}
},
error: function (request,status, error) {
}
});
return false;
}
});
});
$('#updatePassword').on('click', function() {$("#superAdminDetailsForm").validate({
rules: {
oldPassword:"required",
newPassword:"required",
confirmpassword:{
require :"true",
equalTo : "#oldPassword"
}
},
messages: {
oldPassword:"Please enter Old Password ",
newPassword: "Please enter New Password",
confirmpassword:"Retype password is incorrect"
},
submitHandler: function(){//to pass all data of a form serial
var formData =$("#superAdminDetailsForm").serialize();
$.ajax({
url:'/changePassword',
type:'post',
datatype: 'json',
data: formData,
success : function(response){
if(response == "true"){
window.location = '/accounts';
} else {
alert("password incorrect");
}
},
error: function (request,status, error) {
}
});
return false;
}
});
});
});

Jquery validate submit handler not working With Ajax

I am trying to submit the form using jquery validate and ajax.But it doesnt work.neither it throws any error.
here is the html
{% if form %}
<form method="POST" action="." id="change_password_form">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="action" value="{% trans 'change password' %}"/>
</form>
{% else %}
<p>{% trans 'Your password is now changed.' %}</p>
{% endif %}
Here is the script
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
<script type="text/javascript">
$(function() {
$("#change_password_form").validate({
rules: {
password1: {
required: true,
maxlength:10
},
password2: {
required: true,
maxlength:10
},
},
messages: {
password1: {
required: "Please provide a password",
},
password2: {
required: "Please Confirm your password",
},
},
submitHandler: function(form) {
var pass = $('input[name=password1]').val();
var repass = $('input[name=password2]').val();
if (pass != repass) {
console.log("error")
}
else {
$.ajax({
type: $(form).attr('method'),
url: $(form).attr('action'),
data: $(form).serialize(),
})
.done(function (response) {
$('#loading-image').hide();
if (response.location == 'accounts/password/reset/key/done/'){
window.location = "{% url 'home' %}"
}
}).error(function(response){
console.log(response)
});
return false;
}
});
});
</script>
Somehow the submit event is not occurring ? what can i do to submit the form using ajax and jquery validate
I did some minor changes in your code, i think you had a typo.
The problem was you was using the rules without "" and jquery.validate was not able to recognize.
I also added a custom validation to control if the passwords are the same, all validations should be with standard rules or customs but you shouldn't add validations into submitHandler method.
$("#change_password_form").validate({
rules: {
"password1": {
required: true,
maxlength:10,
"isSamePassword": true
},
"password2": {
required: true,
maxlength:10,
"isSamePassword": true
}
},
messages: {
"password1": {
required: "Please provide a password",
maxlength:"Max 10",
isSamePassword: "Pwd no son iguales"
},
"password2": {
required: "Please provide a password",
maxlength:"Max 10",
isSamePassword: "Pwd no son iguales"
}
},
submitHandler: function(form) {
$.ajax({
type: $(form).attr('method'),
url: $(form).attr('action'),
data: $(form).serialize(),
})
.done(function (response) {
$('#loading-image').hide();
if (response.location == 'accounts/password/reset/key/done/'){
window.location = "{% url 'home' %}"
}
}).error(function(response){
console.log(response)
});
}
});
$.validator.addMethod("isSamePassword", function(value) {
var pass = $('input[name=password1]').val();
var repass = $('input[name=password2]').val();
return pass === repass;
}, 'Pwd no son iguales');

Validation not firing submitHandler

As stated in the title, the submitHandler is not firing/being reached, but the validation is working correctly. The submit handler is in the correct, but not firing.
$(function () {
$("#form").validate({
rules: {
domain: {
required: true
},
playerClass: {
required: true,
}
},
submitHandler: function (form) {
var accountNumber = $("input#accountNumber").val();
var domain = $("input#domain").val();
var playerClass = $("input#playerClass").val();
var dataString = JSON.stringify([{
"accountNumber": accountNumber,
"playerClass": playerClass
}]);
//Save Form Data........
$.ajax({
type: "POST",
dataType: "json",
url: "/",
contentType: "application/json",
data: dataString,
success: function () {
$('.render-info').html("<div class='alert alert-success'>You've successfully built your player code</div>");
$(".player-code").show();
},
failure: function () {
alert(dataString);
$('.render-info').html("<div class='alert alert-failure'>Submission Error</div>");
}
});
$(".player-code").show();
}
});
});
jsFiddle: Link
Because you don't have a real submit button. A div is not a button...
<div class="btn btn-default submit">Submit</div>
You need a button or input with type="submit" to trigger the submitHandler when the form is valid.
<input type="submit" class="submit" />
OR
<button type="submit" class="submit">Submit</button>
http://jsfiddle.net/e04rca0t/7/

Categories