ajax - Submitting multiple buttons with AJAX but getting first value only - php

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>

Related

Form submission according to ajax condition is not working

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
});

Force selection with JQuery autocomplete

I know this question has been asked before, but I wasn't able to find any answers that are up to date or functional (at least for my application).
My JQuery autocomplete box is using a mysql database as its source. I want the user to be able to type to get recommendations, but then is forced to select from the dropdown choices before they can submit the form.
My Javascript:
<script type="text/javascript">
$.widget( 'ui.autocomplete', $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var that = this;
$.ui.autocomplete.currentItems = items;
$.each( items, function( index, item ) {
that._renderItemData( ul, item );
});
}
});
$.ui.autocomplete.currentItems = [];
$(function() {
$("#college").autocomplete({
source: "search.php",
minLength: 5
});
});
var inputs = {college: false};
$('#college').change(function(){
var id = this.id;
inputs[id] = false;
var length = $.ui.autocomplete.currentItems.length;
for(var i=0; i<length; i++){
if($(this).val() == $.ui.autocomplete.currentItems[i].value){
inputs[id] = true;
}
}
});
$('#submit').click(function(){
for(input in inputs){
if(inputs.hasOwnProperty(input) && inputs[input] == false){
alert('incorrect');
return false;
}
}
alert('correct');
$('#college_select_form').submit();
});
</script>
My form:
<form action="choose.php" method="post" id="college_select_form" name="college_select_form">
<input type="text" id="college" name="college" class="entry_field" value="Type your school" onclick="this.value='';" onfocus="this.select()" onblur="this.value=!this.value?'Type your school':this.value;" /><input type="submit" id="submit" name="submit" class="submitButton" value="Go" title="Click to select school" />
</form>
Search.php:
<?php
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e) {
echo $e->getMessage();
}
$return_arr = array();
if ($conn)
{
$ac_term = "%".$_GET['term']."%";
$query = "SELECT * FROM college_list where name like :term";
$result = $conn->prepare($query);
$result->bindValue(":term",$ac_term);
$result->execute();
/* Retrieve and store in array the results of the query.*/
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
array_push($return_arr, array('label' => $row['name'], 'value' => $row['name']));
}
}
/* Free connection resources. */
//$conn = null;
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
?>
So what would be the best approach to doing this? The only solution I can think of is using PHP to verify that the textbox's value matches a value in the database, but I'm not sure how to implement that with my current code.
You should always check it in "choose.php" (server-side) since the user can disable the JavaScript and post whatever they want in the inputs of your form
$college = mysql_real_escape_string($_GET['college']);
if ($college != "" || $college != null || $college != -1)
{
//DO STUFF
}
NOTE: YOU SHOULD ALWAYS USE "mysql_real_escape_string" to prevent SQL Injection!
more info: http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php
So accordingly in search.php change the
$ac_term = "%".$_GET['term']."%";
to
$ac_term = "%". mysql_real_escape_string($_GET['term']) ."%";
You can also check the form before the user submit to just make it more user friendly (users don't want to wait couple of seconds for the page to gets refreshed with errors on it!)
so maybe something like this would help: Submit Event Listener for a form
function evtSubmit(e) {
// code
e.preventDefault();
// CHECK IT HERE!
};
var myform = document.myForm;
myform.setAttribute('action', 'javascript:evtSubmit();');
In my project i handled it by checking on focus-out , if the text entered in the autocomplete field actually matches my dropdown options.If not i will simply remove it.
change: function(event, ui) {
if (!ui.item) {
this.value = '';
}
}
See my full example here-Jquery auto comp example
it has an embeded fiddle,you can check the fiddle directly also
http://jsfiddle.net/9Agqm/3/light/
Add this code to your JavaScript before you instantiate your autocomplete object:
$.widget( 'ui.autocomplete', $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var that = this;
$.ui.autocomplete.currentItems = items;
$.each( items, function( index, item ) {
that._renderItemData( ul, item );
});
}
});
$.ui.autocomplete.currentItems = [];
This will make it so whenever the menu appears, you have a list of current items the user can choose from stored in $.ui.autocomplete.currentItems. You can then use that to check against when you are submitting your form. Of course the way you implement this part is up to you depending on how dynamic your form is, but here is an example that requires hard-coding a list of input fields and making sure they all have ids.
//create an object that contains every input's id with a starting value of false
var inputs = {college: false};
//for each input, you will have a function that updates your 'inputs' object
//as long as all inputs have id's and they all are using autocomplete,
//the first line could be written as: $('input').change(function(){ and the
//function would only need to be written once. It is easier to maintain
//if you use seperate id's though like so:
$('#college').change(function(){
var id = this.id;
inputs[id] = false;
var length = $.ui.autocomplete.currentItems.length;
for(var i=0; i<length; i++){
if($(this).val() == $.ui.autocomplete.currentItems[i].value){
inputs[id] = true;
}
}
});
//when you submit, check that your inputs are all marked as true
$('#submit').click(function(){
for(input in inputs){
if(inputs.hasOwnProperty(input) && inputs[input] == false){
return false; //one or more input does not have correct value
}
}
//all inputs have a value generated from search.php
$('#myform').submit();
});
UPDATE
The only difference between our two examples (one that works and one that doesn't) is that you are binding other events to your input element, onclick and onblur. So by changing our listener from change to blur as well mostly fixes the problem. But it creates a new problem when the enter/return key is pressed to submit the form. So if we add a listener for that specific event then everything works out ok. Here is what the code looks like now:
var validateInfo = function(elem){
var id = elem.id;
inputs[id] = false;
var length = $.ui.autocomplete.currentItems.length;
for(var i=0; i<length; i++){
if($(elem).val() == $.ui.autocomplete.currentItems[i].value){
inputs[id] = true;
}
}
}
$('#college').on('blur', function(){
validateInfo(this);
}).on('keydown', function(e){
if(e.which == 13){ //Enter key pressed
validateInfo(this);
}
});
Add a hidden input element to your form:
<input type="hidden" name="selectedvalue" id="selectedvalue" />
Add a select event handler to your autocomplete, that copies the selected value to the hidden input:
$("#college").autocomplete({
source: "search.php",
minLength: 5,
select: function (event, ui) {
$('#selectedvalue').val(ui.item.value);
}
});
Then just ignore the auto-complete form input in posted data.
As this is javascript, your only concern should be if an item is selected from the autocomplete list. This can simply be done by setting a variable to true on select and false on change. That is enough to prevent regular users from continuing without selecting a school. To prevent abuse you need to check the value server side after posting. All normal user will pass that check.
If I understand the question correctly, this is something I have encountered before. Here is some code pretty much lifted straight out of another project. I have used a local datasource here but the project this is lifted from uses remote data so there won't be a difference:
var valueSelected = '';
$('#college').autocomplete({
source: ['collegeA', 'collegeB', 'collegeC']
}).on('autocompletechange autocompleteselect', function (event, ui) {
if (!ui.item) {
valueSelected = '';
} else {
$('#submit').prop('disabled', false);
valueSelected = ui.item.label;
}
}).on('propertychange input keyup cut paste', function () {
if ($(this).val() != valueSelected) {
valueSelected = '';
}
$('#submit').prop('disabled', !valueSelected);
});
This will programatically enable and disable the submit button depending on whether a value has been selected by the user.
Fiddle here

Ajax call not working on enter keypress, works only for click function

I have a ajax method of calling data from php file, i learned it from one of a blog, now it works file for submit button click function, but when i press enter the variables get shown in address bar and ajax process is not executed, Can any one please help me doing it on a press enter method....
This is my code:-
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
$("input[name='search_user_submit']").click(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = { "cv" : cv, "cvtwo" : cvtwo }; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "../elements/search-user.php";
$.post(url, data, function(data) {
$("#SearchResult").html(data).show();
});
});
});
});//]]>
</script>
I have tried it by taking an if condition along with keypress event still its not working:-
if (e.keyCode == 13) { // Do stuff }
else { // My above code }
//In this also it seems that i am doing something wrong.
Can anybody please enlighten me oh how to do it.
My input field is:-
<input type="text" name="searchuser_text" id="newInput" maxlength="255" class="inputbox MarginTop10">
My submit button is:-
<input class="Button" name="search_user_submit" type="button" value="Search">
You can try with event.preventDefault(); for enter keypress.
Thanks.
When you type enter there is executed default onSubmit handler for a form. You can use submit jquery function to handle both enter and click on submit button.
$("form").submit(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = { "cv" : cv, "cvtwo" : cvtwo }; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "../elements/search-user.php";
$.post(url, data, function(data) {
$("#SearchResult").html(data).show();
});
return false;
});
return false in this function will prevent submit of the form.

Submit button not sending form data to mysql - jquery issue

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;
});

.submit() return false causes weird (to me) behavior

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;
}
});
});

Categories