Ajax request being submitted multiple times - javascript

Im working on fixing some validation to my forms. The validation works, problem is that when no validation error occur, the form submits as many times the user tried to submit. It is like the requests stacks up on a pile.
Forms has this submit button that calls my ajax function create_new_stuff
<input id='submitButton' onclick='create_new_stuff()' name='submit' type='submit' value='create' />
The function
function create_new_stuff(){
$("#createForm").submit(function(event){
event.preventDefault();
event.returnValue = false;
var input_value = $("#createValue").val();
if(input_value === "" || null){
console.log("Wrong input value");
return;
}
else{
var request;
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: "/new_stuff.php",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
console.log("Stuff created!", response);
create_new_stuff_form();
var successDiv = $("<div class='success'>Stuff was created</div>");
$("#responseMessages").html(successDiv);
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
"The following error occured: "+
textStatus, errorThrown
);
});
}
});
}

instead of adding onclick event to submit button, add onsubmit event to form.
<form onsubmit= 'create_new_stuff()'>
</form>

<input id='submitButton' onclick='return create_new_stuff()' name='submit' type='submit' value='create' />
And return false when you don't want to submit the form from your javascript function.

Change button type submit to button or change onclick to onsubmit

Prevents the event from bubbling up by:
event.stopPropagation();

Every time you click on Submit button the onclick calls the create_new_stuff() method to do the required stuff. If you think to do this on form submit or button click both shall show the same behaviour. You can try something like this:
HTML
<label for="formelement">Enter Value Here:</label>
<input type="text" id="formelement" name="formelement">
<input type="submit" id="submitbutton" value="Submit">
JS
$("#submitbutton").on('click', function(e) {
e.preventDefault();
$('#submitbutton').attr('disabled',true);
var x = $("#formelement").val();
if(x=="" || null)
{
console.log("Wrong Input..!!");
return;
}
else {
console.log("Hello" + " " +x);
}
});
Working Demo : DEMO
And you can put a loader here to show server action being done.!!!

I think the best solution specifically for the situation when you are trying to use same code for different forms and you have to use separate function for form submission instead of direct submission
$("#this_is_form_id_string").on('submit', function(e){ });
you can do the trick
function submit_forms(form_id){
var avoid_duplicate_form_submission = 0;
$("#"+form_id).submit(function(e){
e.preventDefault();
avoid_duplicate_form_submission++;
if(avoid_duplicate_form_submission === 1){
// All your code....
}
});
}

Related

Validate automatically on button press

Hi I am using JQuery Form validator to validate a form, and using knockout js to call a function using a button, What I want is that when the button is clicked the the knockout js function should be called, and also at the same time check if all the fields are validated if not, it should just do nothing till all the fields are validated.
Link for the jquery validator form http://www.formvalidator.net/#advanced_programmatically
Here is a field and the button that calls the function.
<input type="text" name="birthday" data-validation="date" data-validation-format="yyyy-mm-dd" placeholder="yyyy-mm-dd" data-validation-help="You must be more than 20 years old" class="form-control" value="<?php if (isset($user['Birthday'])) {echo $user['Birthday'];} ?>">
<div data-bind="ifnot: (loggedIn() == 'true')">
<button data-bind="click : openUpTwoStepAuth " type="submit" id="openUpTwoStepAuth" class="btn registerbtn">
<?php echo lang("register_continue_btn"); ?>
</button>
</div>
And here is the knockout js function that tries to call the validation as soon as the button is clicked, but in my case it does not check the validation and goes on with the ajax call.
self.openUpTwoStepAuth = function(){
$('#openUpTwoStepAuth').validate(function(valid, elem) {
if(!valid){
return;
}
});
self.emailtokenconfirmation(false);
self.tokenError(null);
self.showTwoStepAuth();
$.ajax({
type: 'POST',
url: BASEURL + 'index.php/myprofile/sendEmailForTwoStepAuth/',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON({customerEmail : self.customerEmail()})
})
.done(function(data) {
if(data.success){
self.emailtokenconfirmation(true);
}else{
self.tokenError(data.result);
}
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert("Error code thrown: " + errorThrown);
})
.always(function(data){
});
}
It works fine if its just a normal button calling the submit function with this piece of code
<script>
$.validate({
modules : 'toggleDisabled',
disabledFormFilter : 'form.toggle-disabled',
showErrorDialogs : false
});
</script>
but for me I want to call a js function and at the same time check the validation of the field.
This seems to be already answered here
Knockout + Jquery Validate
Use submitHandler in validate to call your view model function on successful validation.

JS Validate plugin prevent submit form

Hello this is my code i am trying to prevent form submit when button is clicked, and load ajax. but form continue to submits, I tried to add preventDefault, and onsubmit false parametar but no luck. Is there anyone to help me to fix this problem
$(function() {
$('#submitTest').click(function(e){
var form_test = $('#test_forma').serialize();
e.preventDefault;
jQuery.extend(jQuery.validator.messages, {
required: "Odgovor je obavezan",
});
$( "#test_forma" ).validate({
onsubmit: false,
submitHandler: function(form) {
form.preventDefault();
// e.preventDefault();
if(('#test_forma').valid()) {
$.ajax({
type: "POST",
url: " <?php echo base_url().'home/test';?> ",
data: {form_test:form_test},
beforeSend: function() {
// setting a timeout
$('#g_upozorenje').html('<img src="<?php echo base_url().'images/loading.gif';?>"/>');
},
success: function(response) {
$.each(response.answers, function(i, item){
// if(('#test_odgovori_' + i).val()) == response[i].IdPitanja)
if(response.answers[i].provera ==1) {
$('#test_odgovori_'+response.answers[i].Id).css('color','green');
} else {
$('#test_odgovori_'+response.answers[i].Id ).css('color','green');
$('.test_odgovori_'+response.answers[i].IdPitanja+':checked').next().css('color','red');
}
$('#procenat').html('Odgovorili ste tačno na '+response.result + '% pitanja')
$('#rezultati').dialog();
});
}
});
}
}
});
});
});
You need to use preventDefault as a method and D is uppercase
e.preventDefault();
http://api.jquery.com/event.preventdefault/
You've got to return false;.
Take a look at this example:
<form onsubmit="javascript:doSomething();return false;">
<input type="submit" value="click me">
</form>
Or look here.
e.preventDefault(); is written correctly with brackets, and I think they should be the first after the opening brackets. And try to fire the preventDefault on the form submit and not the click on the button. There are several possibilities to submit a form without pressing the button, you wouldn't handle now.
You need to stop the form from submitting, not preventing default action of the button.
Instead target the form's submit event:
$("form").submit(function (e) {
e.preventDefault(); // this will prevent from submitting the form.
...
Or even use jQuery's on event handler for better performance:
$("form").on('submit', function (e) {
e.preventDefault(); // this will prevent from submitting the form.
...

jQuery.post() has a side-effect of changing my URL parameters

I have a page with multiple forms. When the users fill in one of the forms, I want to send it to a server. However, I need the browser to keep displaying the original page, so that the users can submit other forms, if they wish to. Hence I cannot use the "action" attribute in the form and a "submit" type of button.
After consulting the jQuery.post docs, I arrived to the following solution:
<html>
<head>
<link rel="stylesheet" href="jquery-ui-1.11.3/jquery-ui.css">
<script src="jsFiles/jquery-2.1.3.min.js"></script>
</head>
<body>
<form id="form">
Name:<br> <input type="text" name="name"> <br>
Email:<br> <input type="text" name="email"> <br>
<button id="button" onclick="submitForm();"> Submit </button>
</form>
<script>
function submitForm() {
var postData = $('#form').serialize();
var jqxhr = $.post("SaveForm.jsp", postData ,function() {
})
.done(function() {
alert("The form was submitted successfully");
})
.fail(function() {
alert("Error submitting the form.");
})
}
</script>
</body>
</html>
The above code does what I want it to do, but it has a very peculiar and disruptive side-effect of modifying my URL to include the parameters I'm posting.
So when I fill in my name and email, I'm "redirected" to myself, but with the name and email parameters appearing in the URL:
http://localhost:8080/Prototype/TestPost.html?name=Lev&email=Storytime%40gmail.com
Now, I definitely do not want "name=Lev&email=Storytime%40gmail.com" to be a part of my URL. These parameters are also not intended for TestPost.html but rather to SaveForm.jsp, so it's all very wrong.
I also want to mention that SaveForm.jsp works as expected. It receives the parameters, saves them to the database and returns a success response.
What am I missing?
Thanks.
EDIT
Thanks, everybody. I could not avoid the refresh using the "return false" statement, so I had to use jQuery's "on click" option. I also don't understand how using ajax explicitly would make any difference, since jQuery's documentation seems to say that the post is just a syntactic sugar for Ajax.
The complete code which worked for me was:
<html>
<head>
<link rel="stylesheet" href="jquery-ui-1.11.3/jquery-ui.css">
<script src="jsFiles/jquery-2.1.3.min.js"></script>
</head>
<body>
<form id="form" method="post">
Name:<br> <input type="text" name="name"> <br>
Email:<br> <input type="text" name="email"> <br>
<button id="button"> Submit </button>
</form>
<script>
$( document ).ready(function() {
$("#button").click(function( event ) {
event.preventDefault();
var postData = $('#form').serialize();
var jqxhr = $.post("SaveForm.jsp", postData ,function() {
}).done(function() {
alert("The form was submitted successfully");
}).fail(function() {
alert("Error submitting the form.");
})
});
});
</script>
</body>
</html>
If you don't especify the method attribute on the form it will be GET by default, that's why you get the URL params. Also, because you aren't not stopping the default action, your form is being submitted (the reloading effect), so I recommend you the following code to help you:
<script>
$(function() { //executes js code after html has been loaded
$("#button").on("click", function(e) {
e.preventDefault(); //avoids to reload the page
var postData = $('#form').serialize();
var jqxhr = $.post("SaveForm.jsp", postData ,function() {
}).done(function() {
alert("The form was submitted successfully");
})
.fail(function() {
alert("Error submitting the form.");
})
}
});
</script>
And remove the onclick at the button to have a cleaner HTML:
<button id="button"> Submit </button>
If you do not want to use jQuery's on click and still stick to the submit function you can just add return false; in the end to prevent the form from submitting.
Like below
function submitForm() {
var postData = $('#form').serialize();
var jqxhr = $.post("SaveForm.jsp", postData ,function() {
})
.done(function() {
alert("The form was submitted successfully");
});
.fail(function() {
alert("Error submitting the form.");
})
return false;
}
Hope this helps.
I guess, you are not submitting the form by ajax.
Add return false;, to that it does not redirect and submit via ajax.
function submitForm() {
var postData = $('#form').serialize();
var jqxhr = $.post("SaveForm.jsp", postData, function() {})
.done(function() {
alert("The form was submitted successfully");
})
.fail(function() {
alert("Error submitting the form.");
})
return false;
}

Trying to get Captcha working alongside my validation

I have managed to validate my textboxes using JS but know I need to allow the captcha to work alongside the validation.
<script>
function validateForm() {
var x = document.forms["reg"]["User"].value;
var letters = "#";
if (x.match(letters))
{
alert("Can't Have Email Address As USERNAME!");
return false;
}
return true;
}
First Form
<form name="reg" action="DBLogin.php" onsubmit="return validateForm()" method="post">
Captcha:
<form action="validate.php" method="post">
Enter Image Text
<input name="captcha" type="text">
<img src="captcha.php" /><br>
<input name="submit" type="submit" value="Register">
</form>
Is there a way of having the captcha work alongside my JS validation?
Thank you
use ajax to validate the captcha. and when he submits the form send an ajax request to verify captcha.
give a submit button only to the captcha form.
<form id ="captcha-form" >
Enter Image Text
<input name="captcha" type="text">
<img src="captcha.php" /><br>
<input name="submit" type="submit" value="Register">
</form>
main form :
<form id="main-form" name="reg" action="DBLogin.php" method="post">
<!-- this shoulnt have an submit button -->
now use a js code to first verify the captcha and validate form
$("#captcha-form").submit(function(event){
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// fire off the request to /form.php
request = $.ajax({
url: "validate.php",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
if(response == "true")
{
validateform();
}
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// handle error
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
// prevent default posting of form
event.preventDefault();
});
now the validate function
function validateForm() {
var x = document.forms["reg"]["User"].value;
var letters = "#";
if (x.match(letters))
{
alert("Can't Have Email Address As USERNAME!");
}
$("#main-form").submit();
}
as RiggsFolly has pointed out this is not recommended. as this would defeat the purpose of captcha.

trying to post with jquery ajax without leaving the page

Im following this question trying to post to a php page and have it perform an action on the data the problem is it seems to just refresh the page and not sure what its doing. In the network tab in element inspector my php page never appears.
Here is my code:
js:
<script>
$(function () {
$("#foo").submit(function(event){
// variable to hold request
var request;
// bind to the submit event of our form
// abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
$inputs.prop("disabled", true);
// fire off the request to /form.php
request = $.ajax({
url: "/DormDumpster/session/login-exec.php",
type: "post",
data: json
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// log a message to the console
console.log("Hooray, it worked!");
alert("hello");
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error(
"The following error occured: "+
textStatus, errorThrown
);
alert("bye");
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
// prevent default posting of form
event.preventDefault();
});
});
html:
<form id = "foo" method="post" >
<fieldset id="inputs">
<input id="email" type="email" name="login" placeholder="Your email address" required> <br>
<input id="password" type="password" name="password" placeholder="Password" required>
</fieldset>
<fieldset id="actions"">
<input type="submit" id="submit" name "Submit" value="Log in"">
<label><input type="checkbox" checked="checked"> Keep me signed in</label>
</fieldset>
</form>
php
$email = clean($_POST['login']);
$password = clean($_POST['password']);
Any Ideas to what I am doing wrong or how to figure out what im doing wrong.
You are probably trying to attach the event listener prior to the form being available in the DOM - thus your form won't be found and no event listener will be attached. Try wrapping your code in a DOM-ready callback, to make sure that your form is in the DOM before trying to select it.
$(function () {
$("#foo").submit(function(event){
// All your code...
});
});
More on why and when to use DOM-ready callbacks here.
i think you have to wrap your submit function inside doc ready:
$(function(){
// here your form submit
});
It is always good to note what arguments you are passing as parameters and to check if it is valid within that function or property.
$(function(ready) {
$.ajax({
type: "POST",
url: "/DormDumpster/session/login-exec.php",
data: { name: "John", location: "Boston" },
dataType: "JSON"
})
}
Data to be sent to the server. It is converted to a query string, if
not already a string. It's appended to the url for GET-requests.
- from http://api.jquery.com/jQuery.ajax/

Categories