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.
The following code is working fine when the form is submitted correctly with all valid data in the first attempt. If there is any server side error after submitting the form then when user resubmits the form the recaptcha does not reset.
Following is the sample code:
html-form
<script src="https://www.google.com/recaptcha/api.js"></script>
<div>
<form name="signupForm" method="POST" action="/signup">
<div class="form-group mobile-number">
<input type="tel" id="mobileNo" class="form-control" name="mobileNumber" maxlength="10"
autofocus>
<label for="mobile"> Your Mobile no. </label>
</div>
<div class="g-recaptcha"
data-sitekey="{key}"
data-callback="setResponse"
data-badge="inline"
data-size="invisible">
</div>
<input type="hidden" id="captcha-response" name="captcha-response"/>
<button id="submitButon" type="submit">Sign me up!</button>
</form>
</div>
javascript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
function setResponse(response) {
document.getElementById('captcha-response').value = response;
submitForm();
}
function submitForm() {
var $form = $("form");
var data = JSON.stringify($form.serializeObject());
var myJsonObject = JSON.parse(data);
data = JSON.stringify(myJsonObject);
$.ajax({
type: "POST",
url: "dummy url",
contentType: "application/json",
xhrFields: {withCredentials: true},
data: data,
success: function (data, textStatus, request) {
// success
},
error: function (xhr, err) {
// logics here
grecaptcha.execute();
setResponse;
}
});
}
</script>
<script>
jQuery(document).ready(function () {
//homepage form
$('form[name="signupForm"]').validate({
onfocusout: function (element) {
$(element).valid();
},
rules: {
mobileNumber: {
required: true,
minlength: 10,
maxlength: 10
}
},
// Specify validation error messages
messages: {
mobileNumber: "A valid mobile number is of 10-digit",
},
//submit handler
submitHandler: function (form) {
submitForm();
}
});
});
</script>
I think the error is in ajax call but not able to figure out why the captcha is not resetting again.
I have the following input HTML tag
<input type="submit" id="submitForm" value="Submit" class="btn btn-primary start" autocomplete="off" onclick="submitForm();" />
When I click on the submit button, it goes to the related JavaScript file and executes the function submitForm();
I would like to change the text of the submit form to "Please wait..." until the function is completed.
Is there a way this can be done?
This is how the submitForm() function looks like:
function submitForm() {
$("#submitForm").val("Please wait...");
if (formValidation() === true) {
submitFormInfo().done(function () {
$("#submitForm").val("Submit");
});
}
}
function submitFormInfo() {
return $.ajax({
cache: false,
url: "URLHERE"
error: function (xhr) {
},
success: function (result) {
},
async: false,
processData: false
});
}
Are you having asynchronus operation in submitform() ?
if yes then you can use following line
$("#submitForm").val("Please Wait");
You can use jquery please see:-
https://jsfiddle.net/swawrm1g/3/
I have removed:-
onclick="submitForm();"
and added:-
$('#submitForm').click(function(){
$(this).val('Please Wait...');
submitForm()
});
function submitForm() {
alert('Form submitted');
};
Simple javascript is enough to do this..
<script>
function submitForm(){
document.getElementById('submitForm').value="Please wait..";
}
</script>
<input type="submit" id="submitForm" onclick="submitForm()" value="Submit">
Use the beforeSend option on your ajax call, so in your submitForm() function, you can do something like this:
function submitForm() {
var submitForm = $("#submitForm");
if (formValidation() === true) {
$.ajax({
cache: false,
url: "URLHERE",
async: false,
type: 'post',
data: { somedata: 'here' },
beforeSend: function (){
submitForm.val("Please wait...").attr("disabled", "disabled");
},
success: function (data){
// do something
},
error: function (){
// do something
},
complete: function () {
// regardless of the response status (success/error)
// the codes below will be executed.
submitForm.val("Submit").removeAttr("disabled");
}
});
}
}
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;
})
I have a form with two buttons
a) Test - on click of the button a javascript function is called to verify a couple of credentials.
b) Create - on click of the button a javascript function is called to save the form.
#Messages("playauthenticate.project.create")
I have a form tag around these two submit buttons with no action.
name, description, accessKey and secretKey are the four fields in the form.
on clicking on the create button, I want to perform jquery validation and then submit the form but the jquery validation submitHandler is not getting called in the javascript function and there are no errors in the Error Console.
When I click on the create button, the create alert is shown and then the form resets and I am able to see all the parameters entered in the URL.
$("create").click(function() {
alert("create ");
$('#projectForm').validate( {
rules: {
name: {
minlength: 6,
required: true
},
description: {
required: true,
description: true
},
accessKey: {
minlength: 10,
required: true
},
secretKey: {
minlength: 15,
required: true
}
},
focusCleanup: false,
wrapper: 'div',
errorElement: 'span',
highlight: function(element) {
$(element).parents ('.control-group').removeClass ('success').addClass('error');
},
success: function(element) {
$(element).parents ('.control-group').removeClass ('error').addClass('success');
$(element).parents ('.controls:not(:has(.clean))').find ('div:last').before ('<div class="clean"></div>');
},
errorPlacement: function(error, element) {
error.appendTo(element.parents ('.controls'));
},
submitHandler: function() {
alert("hello");
var name = $('#name').val();
var description = $('#description').val();
var accessKey = $('#accessKey').val();
var secretKey = $('#secretKey').val();
var dataString = 'name='+ name + '&description=' + description + '&accessKey=' + accessKey+ '&secretKey=' + secretKey;
//alert(dataString);
$.ajax({
type: "POST",
url: "/demo/save",
data: dataString,
success: function(data) {
$('#result').html("<h2>demo created successfully!</h2>");
},
error: function(data) {
$("#result").html("<h2>Error!</h2>");
}
})
}
});
});
JSfiddle - http://jsfiddle.net/NJxh5/3/
Thank you
.validate() is the method for initializing the plugin. It's not a method of testing the form. Testing is automatic.
Therefore, get rid of the click handler. The click event is captured automatically by the plugin. If the form is valid, the submitHandler will fire.
Otherwise, you are doing it properly by placing your ajax inside the submitHandler callback.
$(document).ready(function () {
$('#projectForm').validate({ // initialize the plugin
// rules & options
submitHandler: function(form) {
// ajax method
}
});
});
Working DEMO: http://jsfiddle.net/ACdtX/
With two different buttons and actions:
HTML:
<form id="projectForm">
....
<input type="button" class="button" value="TEST" id="test" />
<input type="button" class="button" value="Create" id="create" />
</form>
jQuery:
$(document).ready(function () {
$('.button').each(function () {
$(this).on('click', function () {
var action;
if ($(this).attr('id') == "test") {
action = 'test.php';
} else {
action = 'create.php';
}
$('#projectForm').submit();
});
});
$('#projectForm').validate({ // initialize the plugin
// rules & options
submitHandler: function(form) {
// ajax method
$.ajax({
url: action, // determined from click handler above
// ajax options
});
}
});
});