submit individual form in twitter bootstrap wizard - javascript

I am using twitter bootstrap from wizard, and i want to submit 4 form in wizard,
http://vadimg.com/twitter-bootstrap-wizard-example/examples/basic-formvalidation.html#
Below is my code on each next button press,
onNext: function (tab, navigation, index) {
if(index == 1) {
if(form_header.valid() === true) {
$('#report_header_fm').submit(function(){
console.log('test123');
$.ajax({
type: "POST",
url: baseURL + "index.php/addNewReport",
data: $("#report_header_fm").serialize(),
success: function(data)
{
console.log('test');
}
}); //Ajax end
});
}
else
{
return false;
}
}
handleTitle(tab, navigation, index);
},
I have form with 5 inputs and id=report_header_fm,
Now when i click on next, i can see form validation occurs but form does not get submitted, Note- I am not clicking on submit button but there is next button--
<input type="submit" class="btn green-haze" value="Save">
So what i want is to submit a form when clicked on next, here validation occurs when click on next but submit is not happening,
I could not see 'test123' in console,
In short, how do i submit form without hitting submit button?
Thanks,

Here is a list of things you can change here to make it work, hopefully. Try it out.
onNext: function (tab, navigation, index) {
var wizard = this;
if(index == 1) {
if(form_header.valid() === true) {
//below line are not needed, so comment it out
//$('#report_header_fm').submit(function(){
console.log('test123');
$.ajax({
type: "POST",
url: baseURL + "index.php/addNewReport",
data: $("#report_header_fm").serialize(),
success: function(data)
{
console.log('test');
//At this point you will need to call the show method with index of tab you want to move to.
wizard.show(2);
}
}); //Ajax end
//});
// this would run before the ajax completes
return false;
} else {
return false;
}
}

onNext: function (tab, navigation, index) {
if(index == 1) {
if(form_header.valid() === true) {
$.ajax({
type: "POST",
url: baseURL + "index.php/addNewReport",
data: $("#report_header_fm").serialize(),
success: function(data)
{
console.log('test');
this.show(2);
}
});
} else {
return false;
}
}

onNext: function (tab, navigation, index) {
if(index == 1) {
if(form_header.valid() === true) {
console.log('test123');
$.ajax({
type: "POST",
url: baseURL + "index.php/addNewReport",
data: $("#report_header_fm").serialize(),
success: function(data)
{
console.log('test');
//index of tab
// this will move to next tab only after getting successful response
$('#rootwizard').bootstrapWizard('show',1);
}
}); //Ajax end
//required so that control does not move to next tab unless response is fetched
return false;
} else {
return false;
}
}

Related

jQuery prevent submit of form inside of if statement

Sorry if there are some mistakes, but I am a total noob and I am also posting for the first time on StackOverflow.
I am trying to configure a submit form, that controls if the inserted PIN is right, and if so goes on with the submission. I did some online research and found out that with jQuery we can use to function event.preventDefault(), I tried to insert it inside my AJAX request but it looks like it doesn't stop the form from being saved.
The code looks like these:
function verifyOTP() {
$(".error").html("").hide();
$(".success").html("").hide();
var otp = $("#contomovimentato").val();
var PIN = $("#PINvalue").val();
var input = {
"otp" : otp,
"PIN" : PIN,
"action" : "verify_otp"
};
if (otp != null) {
$.ajax({
url : 'm_ajaxpinr.php',
type : 'GET',
dataType : "json",
data : input,
success : function(response) {
$("." + response.type).html(response.message)
$("." + response.type).show();
},
error : function() {
alert("ss");
}
});
} else {
$(".error").html('XPIN non valido.')
$(".error").show();
error : function(event) { event.preventDefault(); };
}
//if I insert "return false;" here the submit is always blocked
}
I checked on atom if the parenthesis are right and it looks like it is.
Any ideas how I should use the preventDefault()?
I also checked if the output of m_ajaxpinr.php is correct, and it is. I also tried like these but it still didn't work...
if (otp != null) {
$.ajax({
url : 'm_ajaxpinr.php',
type : 'GET',
dataType : "json",
data : input,
success : function(response) {
$("." + response.type).html(response.message)
$("." + response.type).show();
$("form").submit(function(event) {
if (response.type == 'success')
{
alert(response.type);
}
else if (response.type == 'error')
{
alert(response.type);
event.preventDefault();
}
});
as said in comment above ajax call is asynchronous, you need to complete cancel default action for the form or put event.preventDefault(); on the top function, then submit it in success function if it valid otp.
.val() will not return null, it return empty if no input.
$('#myForm').on('submit', verifyOTP);
function verifyOTP(e) {
e.preventDefault(); // note this
$(".error").html("").hide();
$(".success").html("").hide();
var otp = $("#contomovimentato").val();
var PIN = $("#PINvalue").val();
var input = {
"otp": otp,
"PIN": PIN,
"action": "verify_otp"
};
if (otp) { // mean not null, undefined, empty, false, 0
$.ajax({
//url: 'm_ajaxpinr.php',
url: 'https://httpbin.org/anything/test',
type: 'GET',
dataType: "json",
data: input,
success: function(response) {
$("." + response.type).html(response.message)
$("." + response.type).show();
if(response.args.otp == 1234){
console.log('valid otp, continue submission')
$('#myForm').off('submit'); // remove submit event
$('#myForm').submit(); // then submit the form
}
else{
console.log('invalid pin,\nvalid pin: 1234');
}
},
error: function() {
console.log("server error, submission cancelled");
}
});
} else {
$(".error").html('XPIN non valido.')
$(".error").show();
console.log("otp maybe empty, submission cancelled");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
<input id="contomovimentato">
<button>submit</button>
</form>

Ajax submit an ajax loaded form

I load replies to comments asynchronously in php like in youtube comments.
The ajax handler for forms (ie reply forms) loaded like this is not working. e.preventDefault() is not working. The forms are submitted to the action page itself and page is redirected to action url. If i edit a reply. It works but page is redirected to the action url. This happens only for the ajax loaded replies. The same handler is used for regular comments and it works fine.
A comment :
A comment with loaded replies :
When a reply is edited it just goes to /path/to/submit.php and shows the value of json output like this
result on submitting a reply form
Ajax to show or hide replies:
//load or hide replies
function loadmore(id) {
var val = $('#' + id).data("value");
var count = $('#' + id).data("count");
$.ajax({
type: 'post',
url: '/path/to/submit.php',
data: {
replyof: val
},
success: function(response) {
var content = document.getElementById("show" + val);
content.innerHTML = response;
var clicknum = $('#' + id).data("clicknum");
$('#' + id).data("clicknum", 2);
if (!$("#show" + val).is(":hidden") && clicknum != 1) {
document.getElementById(id).innerHTML =
' View all ' + count + ' replies <i class="fas fa-angle-down"></i>';
$("#show" + val).hide();
} else {
document.getElementById(id).innerHTML =
'Hide all replies <i class="fas fa-angle-up"></i>';
$('#show' + val).show();
}
}
});
}
I use the same class for comments as well as replies and ajax submit the form to the same page /path/to/submit.php using
eg
<form class="replyform" action="/path/to/submit.php">
...
<button type="submit">Delete</button>
...
</form>
The form handler
$(".replyform").submit(function(e) {
var URL = $(location).attr('href');
$.ajax({
async: true,
type: "POST",
url: $(this).attr('action'),
data: $(this).closest('form').serialize(),
success: function(data) {
if (data.result === 1) {
window.location = "/login";
} else if (data.result === 2) {
alert('Some error occured.Please try Later');
} else if (data.result === 3) {
replyer(data.comment);
$('body').load(URL);
} else {
$('body').load(URL);
}
},
dataType: "json"
});
e.preventDefault();
});
The .replyform render by ajax so use on instead of traditional way
$(document).on("submit", ".replyform",function(e) {
var URL = $(location).attr('href');
$.ajax({
async: true,
type: "POST",
url: $(this).attr('action'),
data: $(this).closest('form').serialize(),
success: function(data) {
if (data.result === 1) {
window.location = "/login";
} else if (data.result === 2) {
alert('Some error occured.Please try Later');
} else if (data.result === 3) {
replyer(data.comment);
$('body').load(URL);
} else {
$('body').load(URL);
}
},
dataType: "json"
});
e.preventDefault();
});
I think your calling your form wrong. You need an id attribute. I don't think you can call it by it's class name like that.
<form id="myForm" class="replyform" action="/path/to/submit.php">
...
<button type="submit">Delete</button>
...
</form>
$("#myForm").submit(function(e) {
...rest of script.

Bootstrap Formwizard - Prevent to scroll to next step if each page form submitting ajax response gets error

I am using twitter bootstrap form wizard to submit data on each page with validation. Now i want to prevent, scroll to next step if ajax response gets error while submitting data. Below is my code,
'onNext': function(tab,navigation,index){
//scrollTo('#wizard',-100);
if(index == 1){
var $valid = $('#register_form').valid();
if(!$valid){
$validator.focusInvalid();
return false;
}
else
{
var options = $('form[name=register_form]').find('input, textarea, select').filter('.fw1').serialize();
var data = options + '&step=1';
$.ajax({
type: 'POST',
url: 'employeeEntryProcess.php',
data: data,
success: function(data){
this.show(2);
},
error: function(){
return false;
}
});
}
}
},
Thanks,
Its working after changes. Thanks to all for helping.
'onNext': function(tab,navigation,index){
if(index == 1){
var $valid = $('#register_form').valid();
if(!$valid){
$validator.focusInvalid();
return false;
}
else
{
var options = $('form[name=register_form]').find('input, textarea, select').filter('.fw1').serialize();
var data = options + '&step=1';
$.ajax({
type: 'POST',
url: 'employeeEntryProcess.php',
data: data,
success: function(response){
$('#wizard').bootstrapWizard('show',1);
},
error: function(){
alert('Error');
}
});
}
}
return false;
},
The only way to do this is to always return false so that it doesn't scroll to next step automatically, and then manually scrolling to the next step in the success function of the AJAX request (so that it would only proceed if it was successful). You may want to put an animation for the duration of the AJAX request as otherwise it would look like nothing is happening.

Only send post/get if form values has changed

I want to prevent multiple ajax calls (user holds enter key down or multi presses submit or other)
I'm thinking, the best way is to use a var with the previous form post values and compare them at each click/submit.. Is it the same? : Then do nothing
But I don't know how to go about it
Here is my javascript/jquery:
$('form').submit(function() {
$theform = $(this);
$.ajax({
url: 'validate.php',
type: 'POST',
cache: false,
timeout: 5000,
data: $theform.serialize(),
success: function(data) {
if (data=='' || !data || data=='-' || data=='ok') {
// something went wrong (ajax/response) or everything is ok, submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
} else {
// ajax/response is ok, but user input did not validate, so don't submit
console.log('test');
$('#jserrors').html('<p class="error">' + data + '</p>');
}
},
error: function(e) {
// something went wrong (ajax), submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
}
});
return false;
});
Not very creative with naming vars here:
var serial_token = '';
$('form').submit(function() {
$theform = $(this);
if ($(this).serialize() === serial_token) {
console.log('multiple ajax call detected');
return false;
}
else {
serial_token = $(this).serialize();
}
$.ajax({
url: 'validate.php',
type: 'POST',
cache: false,
timeout: 5000,
data: $theform.serialize(),
success: function(data) {
if (data=='' || !data || data=='-' || data=='ok') {
// something went wrong (ajax/response) or everything is ok, submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
} else {
// ajax/response is ok, but user input did not validate, so don't submit
console.log('test');
$('#jserrors').html('<p class="error">' + data + '</p>');
}
},
error: function(e) {
// something went wrong (ajax), submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
}
});
return false;
});
You could combine this with a timeout/interval function which aborts the submit, but the code above should just compare the data in the form
If you have some kind of submit button, just add a class 'disabled' to it when you start the ajax call, and check if it is present before trying to make the call. Remove the class when the server gives a response. Something like:
...
$theform = $(this);
$button = $theform.find('input[type=submit]');
if ($button.hasClass('disabled')) {
return false;
}
$button.addClass('disabled');
$.ajax({
....
},
complete: function () {
$button.removeClass('disabled');
}
});
...

jQuery appends # at the end of url even if I return false;

I have this code which I plastered with return false; so that it wouldn't append the # at the end of a url after it executes, but it still does that. Any idea what I am doing wrong and how/where is best to return false?
// Called right away after someone clicks on the vote up link
$('.vote_up').mouseup(function()
{
$("#loading").show();
var problem_id = $(this).attr("data-problem_id");
vote(problem_id , 1);
//Return false to prevent page navigation
return false;
});
$('.vote_down').mouseup(function()
{
$("#loading").show();
problem_id = $(this).attr("data-problem_id");
vote ( problem_id , -1 );
//Return false to prevent page navigation
return false;
});
// Global function
var vote = function(problem_id , vote)
{
var dataString = 'problem_id=' + problem_id + '&vote=' + vote;
// The person is actually logged in so lets have him vote
$.ajax({
type: "POST",
url: "/auth/check_login.php",
dataType: "json",
success: function(data)
{
$.ajax({
type: "POST",
url: "/problems/vote.php",
data: dataString,
success: function(html)
{
$("#loading").hide();
if ( html == "not_logged_in" )
{
queue.login = false;
//set the current problem id to the one within the dialog
$problemId.val(problem_id);
// Try to create the popup that asks user to log in.
$("#loginpopup").dialog( {title: 'Please Login To Vote'} ); // title: 'Login Dialog'
// prevent the default action, e.g., following a link
return false;
}
else
if ( html == "already_voted" )
{
// Display a dialog box saying that the user already voted
$('<div>You already voted this way on this problem.</div>').dialog( {title: 'Already Voted'});
// show div which says un-important, hide div which says important
$("#support").hide();
$("#dont_support").show();
return false;
}
else
if ( html == "error_getting_vote" )
{
$('<div />').html('Error getting existing votes.').dialog();
}
else
{
if ( vote == -1 )
{
$("#support").show();
$("#dont_support").hide();
}
else
{
$("#support").hide();
$("#dont_support").show();
}
// Now make a call to AJAX to get the count of votes
$.ajax({
type: "POST",
url: "/problems/get_vote_count.php",
data: dataString,
success: function(html)
{
var class_name = ".votes_"+problem_id;
$(class_name).text(html);
return false;
}
});
return false;
}
},
error: function(html)
{
$("#loading").hide();
return false;
} // End of error case
}); // Closing inner AJAX call.
},
error: function(data)
{
$("#loading").hide();
$("#loginpopup").dialog( {title: 'Please Login To Vote'} );
return false;
} // End of error
}); // End of outer AJAX.
return false;
};
You should bind the event listener to the click event instead of mouseup. When mouseup is triggered, the default behaviour has already occurred, and cannot be cancelled any more.
$('.vote_down').click(function(e) {
e.preventDefault();
// Rest of code
PS. Judging by your code, you've got separate pages to vote:
AJAX request - Is logged in?
AJAX request - Vote
This model is very insecure, if the voting page does not contain some kind of authentication. Users can easily bypass the login page by creating an artificial request to the voting page.
You should merge the login, and voting page.
Change your link syntax from <a href="#"> to <a href="javascript:void(0);" /> without changing your js code.

Categories