Adding 1 to div onsubmit - javascript

i have a form that i submit to a database using ajax, there a div on the page which has a database binding which counts the total number of records submit on page refresh. now what i want to do is onsubmit of the form, i should add 1 to the binding in the div which counts the total number of records submitted
<div id="count_div"></div>
<form id="form2" name="form2" method="POST" action="<%=MM_editAction%>">
<input name="comment" type="text" id="comment" size="50" />
<input name="imageField3" type="image" id="imageField3" src="imgs/buttons/comment.png" align="bottom" />
<input name="wardrobe" type="hidden" id="wardrobe" value="1" />
<input name="comme" type="hidden" id="comme" value="2" />
<input name="comfn" type="hidden" id="comfn" value="3" />
<input name="photo_id" type="hidden" id="photo_id" value="4" />
<input name="ctype" type="hidden" id="ctype" value="picture" />
<input name="resp_email" type="hidden" id="resp_email" value="4" />
<input type="hidden" name="MM_insert" value="form2" />
</form>
AJAX
<script>
$(document).ready(function(){
$("#form2").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "int_p_cmt.asp",
data: data
}).success(function() {
$("#msg_div").append("<div class='messages' style='border:1px purple solid; padding:2px; margin:5px;'>Your comment has been saved </div>");
setTimeout(function() {
$(".messages").fadeOut(function(){
$(".messages").remove();
});
}, 1000);
$("input[type=text]").val("");
});
});
});
</script>

if what I understood is correct: you want to increment th value of the "count_div" div then try this:
$(document).ready(function(){
$("#form2").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "int_p_cmt.asp",
data: data
}).success(function() {
$("#msg_div").append("<div class='messages' style='border:1px purple solid; padding:2px; margin:5px;'>Your comment has been saved </div>");
setTimeout(function() {
$(".messages").fadeOut(function(){
$(".messages").remove();
});
}, 1000);
$("#count_div").html(parseFloat($("#count_div").html())+1);
$("input[type=text]").val("");
});
});
});

UPDATED:
<script>
$(document).ready(function(){
$("#form2").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "int_p_cmt.asp",
data: data
}).success(function() {
window.counter=parseInt($('#count_div').html());
window.counter++;
$('#count_div').html(window.counter);
$("#msg_div").append("<div class='messages' style='border:1px purple solid; padding:2px; margin:5px;'>Your comment has been saved </div>");
setTimeout(function() {
$(".messages").fadeOut(function(){
$(".messages").remove();
});
}, 1000);
$("input[type=text]").val("");
});
});
});
</script>

Related

Form validation in ajax requires only the first input in the class to be filled

I'm trying to do validation for my form. I want to make it so if any item with class "required" is empty the form won't be submitted. Right now this is the case only for the first item in the class. For example, I have 3 inputs with class "required" - name, surname, address. The form is sent when I fill in only name, but surname and address are still empty.
Similar problem with $('.required').addClass('error'); - it should have a red border only in the empty field, but it has it on all the fields with "required" class. Is there a way to fix it?
$(function() {
$('#form').on('submit', function(e) {
e.preventDefault();
if ($('.required').val() === '') {
$('#add').addClass('error');
$('.required').addClass('error');
$('#text').html("Fill in the form.");;
} else {
$.ajax({
type: "post",
url: 'php/php.php',
data: new FormData(this),
processData: false,
contentType: false,
success: function() {
document.getElementById("text").innerHTML = "success";
document.getElementById("add").style.border = "2px solid green";
},
error: function() {
document.getElementById("text").innerHTML = "error";
document.getElementById("add").style.border = "2px solid red";
}
});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<p id="text">Placeholder</p>
<form id="form" method="POST" action="php/php.php">
<input type="text" name="Name" id="name" class="required"><br>
<ol>
<li>
<input type="number" name="x1" class="required">
<input type="text" name="xa1" class="required">
<be>
</li>
<li>
<input type="number" name="x2">
<input type="text" name="xa2"><br>
</li>
<input type="submit" name="Add" id="add">
</form>
$('.required') return a collection of jQuery DOM element, so you need to loop through this collection. Try this solution
$(function () {
$('#form').on('submit', function (e) {
e.preventDefault();
let alllfine = true;
$('.required').each(function () {
if ($(this).val() == '') {
$('#text').html("Fill in the form.");
$('#add').addClass('error');
$(this).addClass('error');
$(this).css('border', '1px solid red');
alllfine = false;
} else {
$(this).css('border', '1px solid black');
}
})
if (alllfine) {
$.ajax({
type: "post",
url: 'php/php.php',
data: new FormData(this),
processData: false,
contentType: false,
success: function () {
document.getElementById("text").innerHTML = "success";
document.getElementById("add").style.border = "2px solid green";
},
error: function () {
document.getElementById("text").innerHTML = "error";
document.getElementById("add").style.border = "2px solid red";
}
});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<p id="text">Placeholder</p>
<form id="form" method="POST" action="php/php.php">
<input type="text" name="Name" id="name" class="required"><br>
<ol>
<li>
<input type="number" name="x1" class="required">
<input type="text" name="xa1" class="required">
<be>
</li>
<li>
<input type="number" name="x2">
<input type="text" name="xa2"><br>
</li>
<input type="submit" name="Add" id="add">
</form>
You need to test each of the fields returned
const $req = $('.required');
const valid = $req.filter(function() {
const thisValid = this.value.trim() !== "";
$(this).toggleClass('error',!thisValid);
return thisValid }).length === $req.length;
if (valid) {
// ajax here
}
But why not just use required attribute?
$(function() {
$('#form').on('submit', function(e) {
// we will only see this if required fields are filled in
console.log("ajax here")
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<p id="text">Placeholder</p>
<form id="form" method="POST" action="php/php.php">
<input type="text" name="Name" id="name" class="required"><br>
<ol>
<li>
<input type="number" name="x1" required>
<input type="text" name="xa1" required>
</li>
<li>
<input type="number" name="x2">
<input type="text" name="xa2"><br>
</li>
</ol>
<input type="submit" name="Add" id="add">
</form>

Multiple checkbox submit php form with 1 click

Is there a way to improve this? Can't find a way to improve..
var $submit = $('#submit-form');
$submit.off('click').on('click', function(e) {
e.preventDefault();
var checkedBOX = $('#checkboxes').find('input:checked');
var servers = [];
$.each(checkedBOX, function(k, v) {
var v = $(v);
servers.push(v.val());
v.prop("checked", false);
});
var doneCount = 0;
$.each(servers, function(key, server) {
$.ajax({
type: "POST",
url: window.location.href,
data: $('#form').serialize() + '&server=' + server + '&submit=',
success: function (data) {
doneCount++;
if (doneCount >= servers.length) {
window.location.reload();
}
}
})
});
});
Can't figure it out what is the best way to make it faster..
Could anyone help me out here?
try this way , remove loop
$(document).on('submit','#submit-form',function(e){
e.preventDefault();
var checkedBOX = $('#checkboxes').find('input:checked');
var servers = [];
$("input:checkbox[name=checkbox]:checked").each(function(){
servers.push($(this).val());
});
console.log(servers);
$.ajax({
type: "POST",
url: window.location.href,
data: $('#submit-form').serialize() + '&server=' + servers + '&submit=',
success:function(data){
window.location.reload();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST" id="submit-form">
<input type="text" name="name" placeholder="NAME"/>
<br/>
<input type="text" name="email" placeholder="EMAIL"/>
<br/>
<input type="checkbox" name="checkbox" value="1" />
<input type="checkbox" name="checkbox" value="2" />
<input type="checkbox" name="checkbox" value="3" />
<input type="checkbox" name="checkbox" value="4" />
<br/>
<button type="submit">SUBMIT</button>
</form>

Why my javascript is calling a postback and i don't have error?

When I press on my edit button I call a webservice function and it return a list of question parameter and it's working the function return the right value for each edit button but after returning the value I have a post back and all my html input that I fill in this function they are clear again, why?
JavaScript and jQuery:
$(document).ready(function () {
$('.divPreview').on("click", ".editbtn", function () {
var idQ = 0;
idQ = $(this).val();
var Did = { 'Qid': idQ };
alert(idQ);
$.ajax({
type: "POST",
async: false,
url: "/WebService.asmx/GetQuestion",
data: JSON.stringify(Did),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: function (r) {
alert(r.responseText);
},
failure: function (r) {
alert(r.responseText);
}
});
function OnSuccess(response) {
var question = response.d;
$(".dropdown_fields").html('<select id="dplQuestionType" class="dropdown_selector"><option value="radio">Radio Button</option> <option value="checkbox">Check Box</option></select>');
$(".input_field").html('<p>Q1:<input id="txtQuestion" type="text" /></p> <p> Answer Choices:</p><div><input id="hdnC1" type="hidden" value="0" /><input id="txtC1"type="text" name="mytext[]" /><input id="cbActive1" type="checkbox" /></div><div><input id="hdnC2" type="hidden" value="0" /><input id="txtC2" type="text" name="mytext[]" /><input id="cbActive2" type="checkbox" /></div>');
$(".OtherOption").html('<input id="btnAddField" class="btnAddField" type="button" value="Add Choices"/><br>Page Number<input id="txtPageNumber" type="text" /> Question Order: <input id="txtOrder" type="text" /><br/><p><input id="cbCommonField" type="checkbox" />Add a Common Field</p><br/>Is Required<input id="cbIsRequire" type="checkbox" />Is Active<input id="cbIsActive" type="checkbox" /><br/>Hint:<textarea id="txtaHint" rows="2" cols="20"></textarea> ');
$(".ButtonField").html('<p><input id="btnSave" type="button" value="Save" onclick="GetQuestionInfo()" /> <input id="btnCancel" class="btnCancel" type="button" value="Cancel" /></p>');
document.getElementById("btnAddQuest").style.visibility = 'hidden';
document.getElementById("txtOrder").value = question.qst_Order;
document.getElementById("txtPageNumber").value = question.qst_PageNumber;
document.getElementById("cbIsRequire").value = question.qst_Order;
document.getElementById("cbIsActive").value = question.qst_Order;
document.getElementById("txtaHint").value = question.qst_Hint;
document.getElementById("dplQuestionType").value = question.qst_Type;
document.getElementById("hdnQuestionID").value = question.qst_Id;
alert(question.qst_txt);
}
});
});
You aren't actually doing a ajax request you are simply doing a normal post request from a form, to do a ajax request prevent the default submit using e.preventDefault();
$('.divPreview').on("click", ".editbtn", function (e) {
e.preventDefault();

Alert not working in firefox but working in chromium

jquery:
$("document").ready(function(){
alert('This is working');
$(".add_new").click(function() {
$(".table").hide();
$("#frm").show();
});
$(".insert_form").submit(function(){
var sending_data = {
"action": "insert"
};
sending_data = $(this).serialize() + "&" + $.param(sending_data);
$.ajax({
type: "POST",
url: "test.php", //Relative or absolute path to response.php file
data: sending_data,
success: function(return_data) {
alert(return_data); //This is not working.
}
});
});
});
test.php
<?php
echo $_POST['action'];
?>
HTML:
<form method="post" id="frm" style="display:none;" class="insert_form">
<input type="text" value="" required="required" placeholder="Enter your Name" name="user_name" />
<input type="submit" value="Submit" />
<input type="reset" value="clear" />
</form>
After submitting i have to display message. I am just testing using alert() but the alert box is appearing.Please Help.

Send Ajax message setTimeOut m delay between actions

Hi i have been trying to add even delay() or setTimeOut to this simple send message, but i think i do not understand quite well how does this works, i have been "wrapping" the functions but everytime i got a lots of syntax erros, if i "fix" them i got nothing but all actions done one after other, even if i set delay(8000) no delay is reflected actually
this is the script for send message
$.ajax({
type: "POST",
url: "sendtofriend.php",
data: dataString,
success: function() {
$('#message').css("display", "none");
$('#messagein').css("display", "block");
$('#messagein').html("<div id='messageinin'></div>");
$('#messageinin').html("<h2><%= t('generales.thankks') %></h2>")
.append("<p><%= t('generales.msgsent') %>.</p>")
.fadeIn(1500, function() {
$('#messagein').append("<img id='checkmark' src='images/check.png' />");
});
$('#message').fadeIn(1500, function() {
$('#messagein').css("display", "none");
$('#message').css("display", "block");
});
}
});
return false;
});
});
i have tried a lot of stuff, something like this for example
$.ajax({
type: "POST",
url: "sendtofriend.php",
data: dataString,
success: function() {
$('#message').css("display", "none");
$('#messagein').css("display", "block");
$('#messagein').html("<div id='messageinin'></div>");
$('#messageinin').html("<h2><%= t('generales.thankks') %></h2>")
.append("<p><%= t('generales.msgsent') %>.</p>")
.delay(8000)
.fadeIn(1500, function() {
$('#messagein').append("<img id='checkmark' src='images/check.png' />");
});
$('#message').fadeIn(1500, function() {
$('#messagein').css("display", "none");
$('#message').css("display", "block");
});
}
});
return false;
});
});
My goal is #message to dissapear when confirmation div '#messagein' is visble, and then dissapear the confirmation and reapper the form to submit another message.
this is the HTML
<div id='messagein'></div>
<div id='message'>
<form action="" method="post" id="sendfriendd">
<div id="inpumail" >
<!-- <input type="text" name="" id="youremailaddress" size="40" value="<%= t('generales.tucorreoo') %>" class="text-input" /> -->
<input type="text" name="youremailaddress" id="youremailaddress" size="40" value="<%= t('generales.tucorreoo') %>" class="text-input" onblur="if(this.value == '') { this.style.color='#ccc'; this.value='<%= t('generales.tucorreoo') %>'}" onfocus="if (this.value == '<%= t('generales.tucorreoo') %>') {this.style.color='#000'; this.style.fontStyle='normal'; this.value=''}" style="color: rgb(120, 120, 120); font-style: normal;"/>
<label class="error" for="youremailaddress" id="youremailaddress_error">This field is required.</label>
</div>
<br>
<div id="inpumail2" >
<input type="text" name="friendsemailaddress" id="friendsemailaddress" size="40" value="<%= t('generales.amigcorreoo') %>" class="text-input" onblur="if(this.value == '') { this.style.color='#ccc'; this.value='<%= t('generales.amigcorreoo') %>'}" onfocus="if (this.value == '<%= t('generales.amigcorreoo') %>') {this.style.color='#000'; this.style.fontStyle='normal'; this.value=''}" style="color: rgb(120, 120, 120); font-style: normal;"/>
<label class="error" for="friendsemailaddress" id="friendsemailaddress_error">This field is required.</label>
</div>
<br>
<input type="submit" name="Submit" value=" <%= t('generales.enviarcorreoo') %> " class="enterrenvi">
</form>
The function delay doesn't work in this example (after append) since it only affects jquery animations. setTimeout should do the job when used properly.
try removing the delay and changing:
$('#message').fadeIn(1500, function() {
$('#messagein').css("display", "none");
$('#message').css("display", "block");
});
into:
setTimeout(function() {
$('#message').fadeIn(1000);
$('#messagein').fadeOut(1000); //animate display none
},5000); //timeout 5 secs

Categories