My jquery validation script is below. When i click the submit button it does not submit the form data to mysql. The submit button is called submit. If I remove the jquery validation script it submits to mysql so it is an issue with the validation script.
Jquery Validation script:
$(function() {
function validate(id) {
var enabled = ($("input[name='attendance" + id + "']:checked").val() == 'Yes');
if (enabled) {
//Please select option is selected
if ($("#food" + id)[0].selectedIndex == 0 || $("#drink" + id)[0].selectedIndex == 0) {
alert('Please select color');
return false;
}
}
return true;
};
$("input[name^='attendance']").click(function(e) {
var id = this.name.replace('attendance', '');
$("#food" + id + ", #drink" + id).prop("disabled", this.value == 'No');
validate(id);
});
$("input:submit").click(function(event) {
event.preventDefault();
var retVal = false;
$.each([1, 2], function(i, val) {
retVal = (validate(val) || retVal);
});
if (retVal) {
$('list').submit();
}
});
});
submit button:
<input type="submit" name="submit" id="submit" value="Submit" />
form data:
<form name="colour" action="" method="post" id="list">
The selector in the submit() is incorrect. You're looking for the form by its id, list. Your selector is looking for tags called <list>.
if(retVal){$('list').submit();}
// Should be
if(retVal){$('#list').submit();}
Update: if it won't submit in IE:
if (retVal) {
document.getElementById('list').submit();
}
Update 2:
Instead of binding this to the submit button's .click(), bind it to the form's .submit() and return true or false:
// Bind to the form's .submit()
$("#list").submit(function(event) {
event.preventDefault();
var retVal = false;
$.each([1, 2], function(i, val) {
retVal = (validate(val) || retVal);
});
// return the true/false to the submit action
// false will prevent submission.
return retVal;
});
Related
I have a form submission page, call a function at the time of form submission.Include an ajax.Form submission occur or not according to the condition in ajax.Ajax msg have two values 1 and 0,one value at a time.My requirement is when msg==1 form not submit and msg==0 submit form.But now in both cases form is not submitting.
My code is given below.Anybody give any solution?
main page
<form action="addCustomer_basic.php" method="post"
name="adFrm" id="myform" >
<input name="name" type="text"
class="txtfld" id="name"
value=">" style="width:250px;"/>
<input name="email" type="text"
class="txtfld" id="email" value="" style="width:250px;"/>
<input name="submit" type="submit" value="Submit" />
</form>
<script language="JavaScript">
$(function() {
$("#myform").submit(function(e) {
var $form = $(this);
var cust_name = $form.find('[name="name"]').val();
e.preventDefault();// prevent submission
var email = $form.find('[name="email"]').val();
$.ajax({
type: "POST",
url: 'ajx_customer_mailid.php',
data:'cust_name='+cust_name + '&email=' + email,
success: function(msg)
{
alert(msg);
if(msg==1)
{
alert("Email Id already excist in database");
return false;
}
else
{
self.submit();
}
}
});
});
});
</script>
ajx_customer_mailid.php
<?php
require_once("codelibrary/inc/variables.php");
require_once("codelibrary/inc/functions.php");
$cust_id=$_POST['cust_name'];
$email=$_POST['email'];
$se="select * from customer where name='$cust_id' and email='$email'";
$se2=mysql_query($se);
if($num>0)
{
echo $status=1;
}
else
{
echo $status=0;
}
?>
I've checeked your code, without ajax, and just set directly the msg to 1 or to 2.
See my code, now you can simulate it:
$("#myform").submit(function(e) {
var $form = $(this);
e.preventDefault();// prevent submission
var msg = 2;
if (msg === 1) {
alert("Email Id already excist in database");
return false;
} else {
$form.submit(); //This causes Too much recursion
}
});
There are some errors in it.
So, self.submit(); is bad:
TypeError: self.submit is not a function
self.submit();
You need to rewrite it to $form.submit();
But in that case, if the form needs to submit, you will get an error in your console:
too much recursion
This is because, if it success, then it fires the submit again. But, because in the previous case it was succes, it will be success again, what is fires the submit again, and so on.
UPDATE:
Let's make it more clear what happens here. When you submit the form, after you call e.preventDefault() what prevents the form to submit. When ajax need to submit the form, it triggers the submit(), but you prevent it to submit, but ajax condition will true again, so you submit again, and prevent, and this is an inifinte loop, what causes the too much recursion.
NOTE:
if($num>0) Where the $num is come from? There are no $num anywhere in your php file. You also do not fetch your row of your sql query.
Use mysqli_* or PDO functions instead mysql_* since they are deprecated.
Avoid sql injection by escaping your variables.
So you need to use like this:
$se = "select * from customer where name='$cust_id' and email='$email'";
$se2 = mysql_query($se);
$num = mysql_num_rows($se2); //NEED THIS!
if ($num > 0) {
echo $status = 1;
} else {
echo $status = 0;
}
But i am suggest to use this:
$se = "SELECT COUNT(*) AS cnt FROM customer WHERE name='".mysql_real_escape_string($cust_id)."' and email='".mysql_real_escape($email)."'";
$se2 = mysql_query($se);
$row = mysql_fetch_assoc($se2); //NEED THIS!
if ($row["cnt"] > 0) {
echo $status = 1;
} else {
echo $status = 0;
}
By the time your ajax call finishes, submit handler already finished so the submit continues, it's async you know, so the function makes the ajax call and continues executing. You can do something like this http://jsfiddle.net/x7r5jtmx/1/ What the code does is it makes the ajax call, then waits until the ajax success updates the value of a variable, when the value is updated, if the value is 1, no need to do anything, as we already stopped the form from submittin. If the value is 0, then trigger a click on the button to re-submit the form. You can't call submit inside the submit handler, but you can trigger click on the button. You obviously need to change the ajax call, just set msg inside your success.
var data = {
json: JSON.stringify({
msg: 0 //change to 1 to not submit the form
}),
delay: 1
}
var msg = null;
var echo = function() {
return $.ajax({
type: "POST",
url: "/echo/json/",
data: data,
cache: false,
success: function(json){
msg = json.msg;
}
});
};
$( "#myform" ).submit(function( event ) {
echo();
var inter = setInterval(function(){
console.log("waiting: " + msg);
if (msg != null){
clearInterval(inter);
}
if (msg == 0){
$( "#myform" ).off(); //unbind submit handler to avoid recursion
$( "#btnn" ).trigger("click"); //submit form
}
}, 200);
return false; //always return false, we'll submit inside the interval
});
So. I have a Form with a lot of checkboxes. Along with that I have a piece of javascript code that is supposed to save the state of every checkbox when the user presses submit. My short and irritating problem is two things.
Question: I want to save Checkbox state to cookie ONLY when I submit the form, right now it saves if I mark a checkbox and reload the page, without submitting. Im working with Javascript and Cookies, two things that Im quite new to. So Im very greatful for all help. Here is my code that I got from here:
function getStorage(key_prefix) {
if (window.localStorage) {
return {
set: function(id, data) {
localStorage.setItem(key_prefix+id, data);
},
get: function(id) {
return localStorage.getItem(key_prefix+id);
}
};
} else {
return {
set: function(id, data) {
document.cookie = key_prefix+id+'='+encodeURIComponent(data);
},
get: function(id, data) {
var cookies = document.cookie, parsed = {};
cookies.replace(/([^=]+)=([^;]*);?\s*/g, function(whole, key, value) {
parsed[key] = unescape(value);
});
return parsed[key_prefix+id];
}
};
}
}
jQuery(function($) {
var storedData = getStorage('com_mysite_checkboxes_');
$('div.check input:checkbox').bind('change',function(){
storedData.set(this.id, $(this).is(':checked')?'checked':'not');
}).each(function() {
var val = storedData.get(this.id);
if (val == 'checked') $(this).attr('checked', 'checked');
if (val == 'not') $(this).removeAttr('checked');
if (val == 'checked') $(this).attr('disabled','true');
if (val) $(this).trigger('change');
});
});
So I want to save to cookie only on submit basically.
Bind to the submit event of the form instead of the change event of all the checkboxes.
Try this in place of your second function:
jQuery(function($) {
// bind to the submit event of the form
$('#id-of-your-form').submit(function() {
// get storage
var storedData = getStorage('com_mysite_checkboxes_');
// save checkbox states to cookie
$('div.check input:checkbox').each(function() {
// for each checkbox, save the state in storage with this.id as the key
storedData.set(this.id, $(this).is(':checked')?'checked':'not');
});
});
});
jQuery(document).ready(function() {
// on load, restore the checked checkboxes
$('div.check input:checkbox').each(function() {
// get storage
var storedData = getStorage('com_mysite_checkboxes_');
// for each checkbox, load the state and check it if state is "checked"
var state = storedData.get(this.id);
if (state == 'checked') {
$(this).attr('checked', 'checked');
}
});
});
I am having an issue where I am trying to pass a submit buttons values along with the form to ajax but for some reason the only value that passes no matter which button I push is the first button. There is more to the form but I am just showing the buttons.
<form>
<input type="submit" name"finalize_invoice" id="finalize_invoice" value="Delete" />
<input type="submit" name"finalize_invoice" id="finalize_invoice" value="Save" />
<input type="submit" name"finalize_invoice" id="finalize_invoice" value="Finalize" />
</form>
$(document).ready(function(){
$("form#submit").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var invoice_temp_id = $('#invoice_temp_id').attr('value');
var man_part_number = $('#man_part_number').attr('value');
var customer = $('#customer').attr('value');
var date = $('#date').attr('value');
var shipdate = $('#shipdate').attr('value');
var shipvia = $('#shipvia').attr('value');
var ponumber = $('#ponumber').attr('value');
var rep = $('#rep').attr('value');
var invoicenotes = $('#invoicenotes').attr('value');
var serial_number = $('#serial_number').attr('value');
var skid = $('#skid').attr('value');
var finalize_invoice = $('#finalize_invoice').attr('value');
$.ajax({
type: "POST",
url: "includes/createfinalinvoice.php?",
data: "invoice_temp_id="+ invoice_temp_id+
"&man_part_number="+ man_part_number+
"&customer="+ customer+
"&date="+ date+
"&shipdate="+ shipdate+
"&shipvia="+ shipvia+
"&ponumber="+ ponumber+
"&rep="+ rep+
"&invoicenotes="+ invoicenotes+
"&serial_number="+ serial_number+
"&skid="+ skid+
"&finalize_invoice="+ finalize_invoice+
$( this ).serialize(),
success: function(data){
if (data == 1) {
var thiserror = 'You may not have any blank fields, please make sure there is a serial number in each field';
alert(thiserror);
}
if (data == 2) {
var thiserror = 'Your serial number(s) do not match with the Manufacture Part Numbers, please double check your list';
alert(thiserror);
}
if (data == 3) {
var thiserror = 'Some of your serial numbers are not located in the database, please make sure you entered the correct serial number';
alert(thiserror);
}
if (data == 4) {
var thiserror = 'This item has already been sold to another customer. Please report this to administration';
alert(thiserror);
}
if (data == 5) {
var thiserror = 'Everything went OK, you may continue and view the processed invoice';
alert(thiserror);
}
if (data == 6) {
var thiserror = 'There are no default prices setup for this customer matching the Manufacture Part Numbers. Please check and make sure they all exist before processing this list';
alert(thiserror);
}
if (data == 7) {
window.location = ('/admin/?mmcustomers=1&viewinvoice=1');
}
}
});
return false;
});
});
You have three submit buttons with identical ids of finalize_invoice. ids must be unique however. This is the reason, jquery selects the first button only, no matter which one was clicked. If you want to send the request with the clicked button, bind a function to the button's click event
$('form#submit input[type="submit"]').click(function() {
...
var finalize_invoice = $(this).attr('value');
$.ajax(...);
...
return false;
}
As #thaJeztah suggested, suppressing the submit event on form
$('form#submit').submit(function() {
return false;
});
<form>
<input type="button" name"del_button" id="del_btn" value="Delete" />
<input type="button" name"save_button" id="save_btn" value="Save" />
<input type="button" name"finalize_button" id="finalize_btn" value="Finalize" />
</form>
<script>
$(document).ready(function(){
var clicked_btn = '';
$('form').submit(function(){ return false; });
$('form input[type=button]').click(function(){
clicked_btn = $(this).attr('id');
yourSubmitFunction(clicked_btn);
return false;
});
}
</script>
I have a form with number of submit type as images. Each image has a different title. I need to find out the title of the clicked image. But my click function inside form submit is not working.
My form is:
<form action='log.php' id='logForm' method='post' >
<?
for($j=1;$j<=5;$j++)
{
?>
<input type="image" src="<?=$img;?>" title="<?=$url;?> id="<?="image".$j?> class="images" />
<?
}
?>
</form>
Jquery:
$("#logForm").submit(function(e)
{
$(".advt_image").click(function(event) {
var href=event.target.title;
});
var Form = { };
Form['inputFree'] = $("#inputFree").val();
// if($("#freeTOS").is(":checked"))
Form['freeTOS'] = '1';
$(".active").hide().removeClass('active');
$("#paneLoading").show().addClass('active');
var url="http://"+href;
$.post('processFree.php', Form, function(data)
{
if(data == "Success")
{
$("#FreeErrors").html('').hide();
swapToPane('paneSuccess');
setTimeout( function() { location=url }, 2500 );
return;
}
swapToPane('paneFree');
$("#FreeErrors").html(data).show();
});
return false;
});
How can I get the title value of clicked image inside this $("#logForm").submit(function())?
How can I use the id of clicked image for that?
You can use event.target property
$("#logForm").submit(function(e)
alert($(e.target).attr('title'));
});
http://api.jquery.com/event.target/
[UPDATE]
I just realized it wouldn't work. I don't think there is a simple solution to this. You have to track the click event on the input and use it later.
jQuery submit, how can I know what submit button was pressed?
$(document).ready(function() {
var target = null;
$('#form :input[type="image"]').click(function() {
target = this;
alert(target);
});
$('#form').submit(function() {
alert($(target).attr('title'));
});
});
[Update 2] - .focus is not working, but .click is working
http://jsfiddle.net/gjSJh/1/
The way i see it, you have multiple submit buttons. Instead of calling the function on submit, call it on the click of these buttons so you can easily access the one the user chose:
$('input.images').click(function(e) {
e.preventDefault(); //stop the default submit from occuring
alert($(this).attr('title');
//do your other functions here.
});
// Runtime click event for all elements
$(document).on('vclick', '.control', function (e) { // .control is classname of the elements
var control = e.target;
alert(e.currentTarget[0].id);
});
if you are not getting proper message in alert, just debug using Firebug.
Check following code you can get the title of clicked image.
Single click
$(document).ready(function()
{
$('#logForm').submit(function(e){
$(".images").click(function(event) {
alert(event.target.title);
});
return false;
});
});
Double click
$(document).ready(function()
{
$('#logForm').submit(function(e){
$(".images").dblclick(function(event) {
alert(event.target.title);
});
return false;
});
});
add following ondomready in your rendering page
$(document).ready(function(){
$("form input[type=image]").click(function() {
$("input[type=image]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
});
Now in your form's submitt action add follwing behaviour and yupeee!... you got it!....
$("#logForm").submit(function(e)
{
var title = $("input[type=image][clicked=true]",e.target).attr("title");
.....
.....
});
What I'm trying to get is to count which checkboxes in article list are selected, and I'm writing selected to "toDel" jquery variable.
Then, if "toDel" remains empty, I'd like to stop submiting the form, and if there is any, I'm proceeding by adding "toDel" value to hidden field value.
If selected it all works fine, but once if I click button and no chechboxes are selected, "return false" somehow stops, and I when new checkbox is selected, I can't get into "correct" part of the code.
I've checked here, and figured out that I can't use "return false" so I tried with validator variable, but it behaves the same.
$(document).ready(function(){
$("#jqdeleteselected").on("click", function(){
var toDel='';
$('.jqchkbx').each(function() {
if ($(this).attr('checked')) {
toDel += ($(this).attr('value')+',')
}
});
console.log(toDel);
$("#send").submit(function() {
var valid = true;
if (toDel != '') {
$('#boxevi').val(toDel);
console.log('filled');
}
console.log('empty');
valid = false;
});
return valid;
});
});
<form method="POST" action='.$_SERVER['REQUEST_URI'].' name="send" id="send">
<input type="hidden" id="boxevi" name="boxevi" />
<input type="submit" id="jqdeleteselected" value="Obriši označene">
<input type="submit" name="addnew" value="Dodaj novi artikl" /></form><br /></div>';
You only need to handle submit event:
$(document).ready(function(){
$("#send").submit(function() {
var toDel='';
$('.jqchkbx').each(function() {
if ($(this).attr('checked')) {
toDel += ($(this).attr('value')+',')
}
});
console.log(toDel);
if (toDel != '') {
$('#boxevi').val(toDel);
console.log('filled');
}else{
console.log('empty');
return false;
}
});
});
You only need to handle submit and you can use :checked selector to speed up your check
$(document).ready(function(){
$("#send").submit(function() {
var toDel='',
$this = $(this),
checkd = $(".jqchkbx:checked");
checkd.each(function() {
toDel += $(this).val() + ',';
});
console.log(toDel);
if (checkd.length > 0) {
$('#boxevi').val(toDel);
console.log('filled');
}else{
console.log('empty');
return false;
}
});
});