Form submitted though Ajax is submitting multiple times - javascript

When I submit this form though Ajax, Ajax posts it multiple times, sometimes posting it up to 10 times, even though the submit button is only clicked once. I don't understand why it is doing this. Any help would be great!
Here is my code:
<script type="text/javascript">
var messageDelay = 2000;
$( init );
function init() {
$('#messageform').show().submit( submitForm );
$('#rtypeshow').hide();
$('a[href="#messageform"]').click( function() {
$('#content').fadeTo( 'slow', .2 );
$('#messageform').fadeIn( 'slow', function() {
$('#senderName').focus();
} )
return false;
} );
$(document).ready(function (){
$("#messagetable").load("messagetable.php");
$("#etype").change(function() {
if ($(this).val() != "0") {
$("#rtypeshow").show();
$('#datepicker').attr('required', 'required');
}else{
$("#rtypeshow").hide()
$("#allowed").hide;
$('#datepicker').removeAttr('required');
$('#allowed1').removeAttr('required');
}
});
});
$(document).ready(function (){
$("#rtype").change(function() {
var selection = $(this).val();
if (selection == "1") {
$("#allowed").show();
$('#allowed1').attr('required', 'required');
}else{
$("#allowed").hide();
$('#allowed1').removeAttr('required');
}
});
});
}
function submitForm() {
var messageform = $(this);
if ( !$('#ename').val() || !$('#message').val() ) {
$('#incompleteMessage').fadeIn().delay(messageDelay).fadeOut();
messageform.fadeOut().delay(messageDelay).fadeIn();
} else {
$('#sendingMessage').fadeIn();
messageform.fadeOut();
$.ajax( {
url: messageform.attr( 'action' ) + "?ajax=true",
type: messageform.attr( 'method' ),
data: messageform.serialize(),
success: submitFinished
} );
}
return false;
}
function submitFinished( response ) {
response = $.trim( response );
$('#sendingMessage').fadeOut();
if ( response == "success" ) {
$('#successMessage').fadeIn().delay(messageDelay).fadeOut();
$('#ename').val( "" );
$('#message').val( "" );
$('#datepicker').val( "" );
$('#allowed1').val( "" );
$('#allowed2').val( "" );
$('#allowed3').val( "" );
$('#allowed4').val( "" );
$("#messagetable").load("messagetable.php");
$('#content').delay(messageDelay+500).fadeTo( 'slow', 1 );
$('#messageform').show().submit( submitForm );
} else {
$('#failureMessage').fadeIn().delay(messageDelay).fadeOut();
$('#messageform').delay(messageDelay+500).fadeIn();
}
}
</script>
<form id="messageform" action="message_forward.php" method="post">
<p>
<label for="ename">Event Name</label>
<input name="ename" type="text" id="ename" required="required">
</p>
<p>
<label for="message">Message</label>
<span id="sprytextarea1">
<textarea name="message" id="message" required="required"></textarea>
<span id="countsprytextarea1"> </span><span class="textareaRequiredMsg">A value is required.</span><span class="textareaMaxCharsMsg">Exceeded maximum number of characters.</span></span></p>
<p>
<label for="etype">Response Required</label>
<select name="etype" size="2" id="etype">
<option value="0" selected="selected">No</option>
<option value="1">Yes</option>
</select>
</p>
<div id="rtypeshow" style="display:none;">
Event Resender End Date:
<span id="sprytextfield1">
<input name="datepicker" type="text" id="datepicker" size="10">
MM/DD/YYYY <span class="textfieldInvalidFormatMsg">Invalid format.</span></span><br>
Send Response To: <select name="eforward" id="eforward">
<?php
do {
?>
<option value="<?php echo $row_Recordset1['cphone']?><?php echo $row_Recordset1['provider']?>"><?php echo $row_Recordset1['fullname']?>-SMS Message via Cell Phone</option>
<option value="<?php echo $row_Recordset1['email']?>"><?php echo $row_Recordset1['fullname']?>-Email Message</option>
<?php
} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
$rows = mysql_num_rows($Recordset1);
if($rows > 0) {
mysql_data_seek($Recordset1, 0);
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
}
?>
</select><br>
<label for="question">Question for responses</label>
<input type="text" name="question" id="question" maxlength="18"><br>
<label for="rtype">Response Type</label>
<select name="rtype" size="3" id="rtype">
<option value="0" selected="selected">Standard Yes/No Response</option>
<option value="1">Create Responses</option>
<option value="2">Get Users Own Response</option>
</select>
<div id="allowed" style="display:none;">
<h4>Response Options</h4>
<label for="allowed1">Option 1</label>
<input type="text" name="allowed1" id="allowed1" maxlength="12" placeholder="Required">Max Length = 12
<label for="allowed2"><br>
Option 2</label>
<input type="text" name="allowed2" id="allowed2" maxlength="12" placeholder="Optional">Max Length = 12
<br>
<label for="allowed3">Option 3</label>
<input type="text" name="allowed3" id="allowed3" maxlength="12" placeholder="Optional">Max Length = 12
<label for="allowed4"><br>
Option 4</label>
<input type="text" name="allowed4" id="allowed4" maxlength="12" placeholder="Optional">Max Length = 12
</div>
</div>
<input name="submit" type="submit" value="Send Messages">
</form>
Additional Comments:
Sending a message a second time seems to make it even worse then if the page is refreshed before sending another message.

It looks like your code is attaching the submitForm function multiple times to the submit handler.
In your submitFinished function you attach the handler again:
$('#messageform').show().submit( submitForm );
You can check this by refreshing the page then submitting the form. If it only submits once after refresh then multiple times after that you know that is the problem.

Related

How not to open a window if the form fields are not filled?

I have this submit button on my form with a jQuery action to open a window depending on the users choice. However, I just want the window to open if the fields are filled. I have this code and I want to merge it with an if.
$(function() {
$('#chkveg').multiselect({
includeSelectAllOption: true
});
$('#btnget').click(function() {
window.open($('#chkveg').val());
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="http://formmail.kinghost.net/formmail.cgi" method="POST">
<input name="nome" type="text" class="nome" id="nome" required width="100%" placeholder="Nome:">
<input name="cpf" type="text" class="cpf" id="cpf" placeholder="CPF:">
<div style="clear:both"></div><br/>
<input name="nascimento" type="text" class="nascimento" id="nascimento" placeholder="Data de nascimento:">
<select id="chkveg">
<option value="https://pag.ae/7ULKPL7TH">Associados Ancord + C.Dados = R$700,00</option>
<option value="https://pag.ae/7ULKQ8Zm2">Associados Ancord = R$800,00</option>
<option value="https://pag.ae/7ULKQLB9m">Associados Entidades Apoiadoras + C.Dados = R$800,00</option>
</select>
<input id="btnget" class="submit-btn" type="submit" value="INSCREVER-SE">
</form>
For exemple:
IF (#FORM).REQUIRED = TRUE {
(#BUTTON).WINDOWOPEN
}
Thanks
Because you using a submit button you will need to return false, in case if you don't want to do anything. Before that, you need also to check if your required field are empty or not. (i.e. $(your field).val() === "" then it's empty, if all you need have, then call the window.open() function.
Note: you can merge multiple fields for checking ie: $(".your_field1, .your_field2, .your_field3").val() === "" however this is an OR operation.
One possible solution:
$(function() {
$('#btnget').click(function() {
let isEmpty = false;
$('#data_form input,textarea,select').filter(':visible').each(function(i) {
if ($(this).val() === "") {
isEmpty = true;
return false;
}
});
if (isEmpty) {
return false;
}
window.open($('#chkveg').val());
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="data_form" action="http://formmail.kinghost.net/formmail.cgi" method="POST">
<input name="nome" type="text" class="nome" id="nome" required width="100%" placeholder="Nome:">
<input name="cpf" type="text" class="cpf" id="cpf" placeholder="CPF:">
<div style="clear:both"></div><br/>
<input name="nascimento" type="text" class="nascimento" id="nascimento" placeholder="Data de nascimento:">
<select id="chkveg">
<option value="https://pag.ae/7ULKPL7TH">Associados Ancord + C.Dados = R$700,00</option>
<option value="https://pag.ae/7ULKQ8Zm2">Associados Ancord = R$800,00</option>
<option value="https://pag.ae/7ULKQLB9m">Associados Entidades Apoiadoras + C.Dados = R$800,00</option>
</select>
<input id="btnget" class="submit-btn" type="submit" value="INSCREVER-SE">
</form>
If you want only for the required fields, than use filter('[required]:visible') instead of filter(':visible').

How to do for loop for display all errors at once in JavaScript?

I am currently working on JavaScript form validation. For individual it is applying all errors but my task is to loop all element at once and display error at once. Is there any solution?
<form action="" id="register" onsubmit="return validation()">
Name<input type="text" id="name">
<p id="error"></p>
Email<input type="text" id="email">
<p id="error"></p>
Password<input type="text" id="password">
<p id="error"></p>
<input type="submit" name="submit" value="Submit">
</form>
<script>
function validation() {
if (document.getElementById('name').value=="") {
document.getElementById("error").innerHTML="Please fill your name";
}
and so.. on..
}
</script>
Can anyone help me how to for loop all errors to display at once when user click submit buttton?
First of all, create an error box. This can be done using a simply div.
<div id="error-box" style="color: red"></div>
Second, you don't need to chain infinite if statements. You can use the fantastic and wonderful for loop!
function validation() {
var inputs = document.forms['myForm'].getElementsByTagName('input').length;
for (i = 0; i <= inputs; i++) {
if (document.forms['myForm'][i].value == "") {
document.getElementById("error-box").innerHTML="Please fill " + document.forms['myForm'][i].name;
}
}
}
This will create an array of inputs and read one by one. If any field is empty, it will return an error into your error box. If not, execution continues.
Or you can use jQuery and Validation plugin. Check here for more info. A simple jQuery form validation script
Happy coding!
First the id should be unique in same document so you have to replace duplicate ones by classes, e.g :
Name<input type="text" id="name">
<p class="error"></p>
Email<input type="text" id="email">
<p class="error"></p>
Password<input type="text" id="password">
<p class="error"></p>
Then just show the error message of the input in the related .error paragraph :
function validation() {
if ($('#name').val()==="") {
$('#name').next(".error").html("Please fill your name");
}
}
Hope this helps.
$('#register').on('submit', function(){
var submit = true;
if ($('#country').val()==='-1'){
$('#country').next(".error").html("Please fill your country");
submit = false;
}else
$('#country').next(".error").html("");
if ($('#name').val()===""){
$('#name').next(".error").html("Please fill your name");
submit = false;
}else
$('#name').next(".error").html("");
if ($('#email').val()===""){
$('#email').next(".error").html("Please fill your email");
submit = false;
}else
$('#email').next(".error").html("");
if ($('#password').val()===""){
$('#password').next(".error").html("Please fill your password");
submit = false;
}else
$('#password').next(".error").html("");
if ($('[name="check"]:checked').length===0){
$('[name="check"]:last').next(".error").html("Please check one at least");
submit = false;
}else
$('[name="check"]').next(".error").html("");
return submit;
})
.error{
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" name="register" id="register">
Country
<select name="country" id="country">
<option value="-1">Select country please</option>
<option value="usa">USA</option>
<option value="austriala">Austriala</option>
<option value="india">India</option>
</select>
<p class="error"></p>
Name <input type="text" id="name">
<p class="error"></p>
Email <input type="text" id="email">
<p class="error"></p>
Password <input type="text" id="password">
<p class="error"></p>
Checkboxes
<br>
<input type="checkbox" name="check" value="check_1">check 1
<br>
<input type="checkbox" name="check" value="check_2">check 2
<br>
<input type="checkbox" name="check" value="check_3">check 3
<p class="error"></p>
<input type="submit" name="submit" value="Submit">
</form>
Hmm. How about a native way? :)
function select( cssSelector ){ return document.querySleectorAll( cssSelector ) };
var inputs = select( '#register input' ); // selects array of all child inputs
//setup all validations within an object
var validations = {
name: function( nameText ){
//shorthand if-statements, expand if you need to
return ( nameText === "" ) ? "error, cannot be empty" : "ok";
},
password: function( passText ){
return ( passText.length < 8 )? "too short" : "ok";
}
};
//iterate over all inputs
for( var elem in inputs ){
if( validations[ inputs[ elem ].id ] ){ // if validation rule exists..
console.log( "input nr " + elem + "tested\n" +
"id = " + inputs[ elem ].id + "\n" +
"outcome: " + validations[ inputs[ elem ] ] );
}
}
I have not tested this so there might be typos

How to use a checkbox to show more options of a form and change the action attribute of the form?

Hi I am creating a website that has a form to search rooms. I wanted to make it so a checkbox, when clicked, show new options AND change the action ="" attribute of the form.
<form class="form-horizontal" action="reservation?action=listRooms" method="POST">
<label for="">Date </label>
<div class="datepicker ll-skin-nigran hasDatepicker">
<input class="form-control" type="text" placeholder="14/03/2016" name="dateReservation" id="date" required="required"/>
</div>
<br />
<div>
<input type="checkbox" name="choice-for" id="choice-form">
<label for="choice-for">Show More Options.</label>
<div class="reveal-if-active">
<label for="">Slots</label>
<select name="slot" name ="slot" id="slot" >
<option value="">Choose a slot </option>
<option value="8h-9h30">8h00-9h30</option>
<option value="9h30-11h">9h30-11h00</option>
<option value="11h-12h30h">11h00-12h30h</option>
<option value="12h30-14h">12h30-14h00</option>
<option value="14h-15h30">14h00-15h30</option>
<option value="15h30-17h">15h30-17h00</option>
<option value="17h-18h30">17h00-18h30</option>
</select>
<br />
<label for="">Display Screens</label>
<input class="form-control" type="text" placeholder=" 26 pouces" name="screen" id="screen" />
<br />
<label for="">CPU</label>
<input class="form-control" type="text" placeholder="Intel Core i5 " name="processor" id="processor" />
<br />
<label for="">RAM</label>
<input class="form-control" type="text" placeholder=" 2Go de RAM ?" name="ram" id="ram" />
<br />
<input type="submit" value="Réserver" class="btn btn-primary" />
</div>
I tried then to use a javascript(JQuery) script to satisfy my expectations:
<script>
$(function() {
$( "#date" ).datepicker({ dateFormat: 'dd/mm/yy' });
});
$("#choice-form").change(function() {
//there i need to know when the checkbox is changed dynamically so the attribute can change too.
$("#form-horizontal).attr("reservation?action=listRooms");
});
var FormStuff = {
init: function() {
this.applyConditionalRequired();
this.bindUIActions();
},
bindUIActions: function() {
$("input[type='radio'], input[type='checkbox']").on("change", this.applyConditionalRequired);
},
applyConditionalRequired: function() {
$(".require-if-active").each(function() {
var el = $(this);
if ($(el.data("require-pair")).is(":checked")) {
el.prop("required", true);
} else {
el.prop("required", false);
}
});
}
};
FormStuff.init();
</script>
Try this:
$("#choice-form").change(function() {
// If checkbox checked
if ( $('#choice-form').is(':checked') ) {
// Set new form action
$('#form-horizontal').attr('action', 'reservation?action=listRooms');
// Reveal additional options
$('.reveal-if-active').show(); // or call .css() with appropriate options
}
});
Ok, let's say you want to add the id(you can use name as well) and value to the action parameter from the form...
$(document).on('click','.checkboxClass',function(){
var id = $(this).attr('id');
var val = $(this).val();
var selectedVal = '&'+id+'='+val;
var methodUrl = $('form.form-horizontal').attr('action');
if($(this).is(':checked')){
methodUrl+= selectedVal;
}
else{
methodUrl = methodUrl.replace(selectedVal,'');
}
$('form.form-horizontal').attr({'action':methodUrl});
});
Now let's say you have a checkbox with the id="myId" and value="myValue", if you check it, the action parameter will become action="reservation?action=listRooms&myId=myValue"
Is this what you asked for?

DIV does not show on link with variables

For some reason a certain div will now show up when i click a button. I'm fairly new to JS so can't really figure out why is it only on that one. Basically the order should be
Click on Add Shots -> Show Games and Rounds ( Works Fine) -> Click Submit -> Show Targets on each round (Works Fine) -> Click Target -> Show Fill in form (the "fillshotsdiv") (NOT working).
Below is my code. What am i missing?
JS
<script>
$(function() {
$(".but").on("click",function(e) {
e.preventDefault();
$(".contentfill").hide();
$("#"+this.id+"div").show();
});
});
function refreshTargets() {
var load = $.get('functions.php',{gameShots:"<?php echo $_GET['gameShots']; ?>", roundShots:"<?php echo $_GET['roundShots']; ?>",function:"drawTargets"});
$(".targetinfo").html('Refreshing');
load.error(function() {
console.log("Mlkia kaneis");
$(".targetinfo").html('failed to load');
// do something here if request failed
});
load.success(function( res ) {
console.log( "Success" );
$(".targetinfo").html(res);
});
load.done(function() {
console.log( "Completed" );
});
}
</script>
HTML
<div id="addshotsdiv" class="contentfill">
<form action="">
<select name="gameShots" class="gameShot">
<script>
refreshGameDel();
</script>
</select>
<select name="roundShots" class="roundShot">
<option value="nothing">-----</option>
<option value="Round 1">Round 1</option>
<option value="Round 2">Round 2</option>
</select>
<button type="submit" >Submit</button>
</form>
</div>
<div class="targetinfo">
<script>
refreshTargets();
</script>
</div>
<div id="fillshotsdiv" class="contentfill">
<form method="post" action="addScoreToRound.php?targetNo=<?php echo $_GET['targetNo'];?>&gameNo=<?php echo $_GET['gameNo'];?>&roundName=<?php echo $_GET['roundName']; ?>">
<table border="1">
<tr><th>Shot Number</th><th>Arrow 1</th><th>Arrow 2</th><th>Arrow 3</th></tr>
<tr><td>1</td><td><input type="text" name="arrow_1_1"></td><td><input type="text" name="arrow_1_2"></td><td><input type="text" name="arrow_1_3"></td></tr>
<tr><td>2</td><td><input type="text" name="arrow_2_1"></td><td><input type="text" name="arrow_2_2"></td><td><input type="text" name="arrow_2_3"></td></tr>
<tr><td>3</td><td><input type="text" name="arrow_3_1"></td><td><input type="text" name="arrow_3_2"></td><td><input type="text" name="arrow_3_3"></td></tr>
<tr><td>4</td><td><input type="text" name="arrow_4_1"></td><td><input type="text" name="arrow_4_2"></td><td><input type="text" name="arrow_4_3"></td></tr>
<tr><td>5</td><td><input type="text" name="arrow_5_1"></td><td><input type="text" name="arrow_5_2"></td><td><input type="text" name="arrow_5_3"></td></tr>
<tr><td>6</td><td><input type="text" name="arrow_6_1"></td><td><input type="text" name="arrow_6_2"></td><td><input type="text" name="arrow_6_3"></td></tr>
<tr><td>7</td><td><input type="text" name="arrow_7_1"></td><td><input type="text" name="arrow_7_2"></td><td><input type="text" name="arrow_7_3"></td></tr>
<tr><td>8</td><td><input type="text" name="arrow_8_1"></td><td><input type="text" name="arrow_8_2"></td><td><input type="text" name="arrow_8_3"></td></tr>
<tr><td>9</td><td><input type="text" name="arrow_9_1"></td><td><input type="text" name="arrow_9_2"></td><td><input type="text" name="arrow_9_3"></td></tr>
<tr><td>10</td><td><input type="text" name="arrow_10_1"></td><td><input type="text" name="arrow_10_2"></td><td><input type="text" name="arrow_10_3"></td></tr>
</table>
<button type="submit">Submit</button>
</form>
</div>
PHP that refreshTargets calls is
if($_GET['function']=="drawTargets")
{
$gameNo = $_GET['gameShots'];
$roundName = $_GET['roundShots'];
$sql=mysql_query("SELECT * FROM tbl_Round WHERE match_id='$gameNo' && round_name='$roundName'")
or die(mysql_error());
while ($row = mysql_fetch_array($sql)) {
echo '<p><button class="but" id="fillshots" type="button">'.$row["target_name"].'- Player'.$row['player_id'].'</button></p>';
}
}
You need to use event delegation on your click handler because .but is a dynamically inserted element:
$('.targetinfo').on('click', '.but', function(e) {
e.preventDefault();
$('.contentfill').hide();
$('#' + this.id + 'div').show();
});

Radio button validaton

I am trying to get a couple of radio buttons to validate using JavaScript/HTML, but I am having problems. The piece of script I am having trouble with is as follows -
if ( ( RegistrationForm.sexm[0].checked == false ) && ( RegistrationForm.sexf[1].checked == false ))
{
alert( "Please select your sex" );
return false;
}
Basically I want it to return an alert if neither radio button options are selected. At the moment when submitted the form is refreshing itself and not providing any alerts. Any advice would be appreciated!
The relevant HTML I have been provided to work with is -
<form id="RegistrationForm" onsubmit="ValidateForm()" action="">
<fieldset>
<legend>Registration Form</legend>
<label for="username">User Name: </label>
<input type="text" class="input" id="username"/><br />
<label for="password">Password: </label>
<input type="password" class="input" id="password"/><br />
<label for="repassword">Re-Type Password: </label>
<input type="password" class="input" id="repassword"/><br />
<label for="email">Email Address: </label>
<input type="text" class="input" size="30" id="email"/><br />
<label>Age: </label>
<select id ="age" name="age">
<option value=""> --- </option>
<option value="0-18">0-18</option>
<option value="18-30">18-30</option>
<option value="30-50">30-50</option>
<option value="50+">50+</option>
</select><br/>
<label for="sexm">Sex:</label>
<input type="radio" id="sexm" name="sex" value="male" />Male<br/>
<label for="sexf"> </label>
<input type="radio" id="sexf" name="sex" value="female" />Female<br/>
<input type="checkbox" name="agree" id="agree" value="agree"/>
<label for="agree">I accept the terms and cond.</label> <br/>
<label> </label>
<input type="submit" value="Submit" class="button" />
</fieldset>
</form>
Try this code in your javascript <script> tag
function ValidateForm () {
if ( ( document.getElementById("sexm").checked == false ) && ( document.getElementById("sexm").checked == false ))
{
alert( "Please select your sex" );
return false;
} else {
return true;
}
}
Replace it with your code
if ( ( RegistrationForm.sexm[0].checked == false ) && ( RegistrationForm.sexf[1].checked == false ))
{
alert( "Please select your sex" );
return false;
}
Use a for loop to check whether your user has selected any value or not, if not, than throw an alert and use return false to prevent your form being submitted.
Demo
var ischecked = null;
var radios = document.getElementsByName('sex');
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
ischecked = radios[i];
}
}
if(ischecked==null) {
alert('Please choose your Sex');
return false;
}
Save the above code in the function, and call it on submit of your form.
Demo 2 (Validate on submit)
Note: You need to use onsubmit="return ValidateForm();"
try this ...
<script type="text/javascript">
function validate()
{
var o = document.getElementById('sexm');
var t = document.getElementById('sexf');
if ( (o.checked == false ) && (t.checked == false ) )
{
alert ("please select your sex" );
return false;
}
return true;
}
</script>

Categories