Passing variable from a function into submit function - javascript

$('.report_filter input') get value of selected radio box sending the variable to function report_operation, from there on I hide some fields based on the selection
$(".js-ajax-php-json") ajax form submission, I want to get inside the .submit the var value. There I could do some if empty field return false to stop the form from submitting. For instance if field name="number" is empty and the var value is 1 return false; This can't be made by a simple form validator, its a quite dynamic form.
I just have no idea how to do that
$('.report_filter input').on('ifChecked', function(event){
var val = $(this).val();
raport_operation(val);
});
$(".js-ajax-php-json").submit(function(){
var data = {
"action": "test1"
};
data = $(this).serialize() + "&" + $.param(data);
alert(raport_operation());
// if ($("#number").val() == "" and val == 1) {
// alert('you did not fill out one of the fields');
// return false;
// }
$.ajax({
type: "POST",
dataType: "json",
url: "api/response.php",
data: data,
success: function(data) {
draw_graph(data);
$(".the-return").html(data);
//alert("Form submitted successfully.\nReturned json: " + data["json"]);
}
});
return false;
});
function raport_operation(query){
//alert(val);
if(query==1){ //number
//alert(1);
$('#segment_optional').hide('slow');
$('#segment_number').show('slow');
$('#segment_optional').show('slow');
$('#segment_customer').hide('slow');
$('#segment_listType').hide('slow');
$('#segment_customer').val('');
$('#reportdate_to').val('');
$('#reportdate_from').val('');
// $('#segment_general').hide();
}
}

Related

Unable to prevent form when a condition is met

I am working on a form I wish to validate via jQuery $.ajax. The form should only be submitted if a certain condition, data == 1
var preventSubmit = function() {
return false;
var form = $(this),
name = form.find('#name').val(),
email = form.find('#email').val(),
comment = form.find('#comment').val();
$.ajax({
type: "POST",
url: absolute_store_link + '/ajax/comments-filter',
data: {
name: name,
email: email,
comment: comment
},
success: function(data) {
// if data is equal to 1,
// submit form
if (data == 1) {
return true;
}
}
});
};
$("#comment_form").on('submit', preventSubmit);
The submit happens regardless if the condition is met or not.
Where is my mistake?
If I use e.preventDefault();, how can I "undo" it in case if data is equal to 1?
You won't be able to allow the submission of the form with a return value of true because the ajax is happening asynchronously (by the time it completes the function has already finished executing). What you can do is always prevent the form from submitting in the preventSubmit function, then submit it programmatically.
var preventSubmit = function() {
var form = $(this),
name = form.find('#name').val(),
email = form.find('#email').val(),
comment = form.find('#comment').val();
$.ajax({
type: "POST",
url: absolute_store_link + '/ajax/comments-filter',
data: {
name: name,
email: email,
comment: comment
},
success: function(data) {
// if data is equal to 1,
// submit form
if (data == 1) {
form.off();//remove bound events (this function)
form.submit();//manually submit the form
}
}
});
return false;//the return needs to be at the end of the function and will always prevent submission
};
$("#comment_form").on('submit', preventSubmit);
Anything after the return false; will never be executed.
Also, you should be doing form validation on the front-end rather than the back-end. With that being said, you should not remove the validation from the back-end.
One more thing, try doing HTML5 form validation first as that's your first line of defence.
You're looking at something on the lines of:
var validateForm = function(e) {
// prevent the default form action to allow this code to run
e.preventDefault();
var isValid = false,
form = $(this),
name = form.find('#name').val(),
email = form.find('#email').val(),
comment = form.find('#comment').val();
// Validation goes here
// ...
// isValid = true;
if (isValid) {
$.ajax({
type: "POST",
url: absolute_store_link + '/ajax/comments-filter',
data: {
name: name,
email: email,
comment: comment
},
success: function(data) {
// do something with the response. Maybe show a message?
form.submit();
}
});
}
};

input field not changes on change of dropdown if i insert input field value on form

Input field value change on change of drop down but if i change input field value in form then on change of drop down input field value doesnt change .. this is jquery..
$('#Add-DSR-Form').on( 'change', 'tbody td select.cylinder_id', function () {
var $row = $(this).parents("tr"),
index = $row.attr('data-item-index');
var CylinderID = $(this).val();
if(CylinderID < 1)
{
$row.find('[id="Rate[]"]').attr('value', "").end();
grandTotal();
return false;
}
else
{
var Action = 'GetCylinderDetail';
var dataString = 'Action='+ Action +'&CylinderID='+ CylinderID;
$.ajax({
type: "POST",
url: "includes/loader_functions.php",
data: dataString,
cache: false,
success: function(result)
{
//alert(result);
//alert(JSON.parse(result));
var obj = JSON.parse(result);
$row.find('[id="Rate[]"]').attr('value', obj.CylinderPrice).end();
grandTotal();
return true;
}
});
}
});

avoid sending if any field empty Axax

In my form I have various fields including (input and selects) in which I want to check any empty field and prevent ajax call if any of the field is empty and focus on empty fields. so far I am trying this way, It alerts but also makes an ajax call.
$('#submit').click(function() {
$('input').each(function() {
if (!$(this).val()) {
alert('Some fields are empty');
return false;
}
});
event.preventDefault(); // using this page stop being refreshing
$.ajax({
type: 'POST',
url: "<?php echo site_url(''); ?>/shipment/create_shipment",
data: $('form').serialize(),
cache: false,
success: function(data) {
$('#F_id').val('');
$('#v_id').val('');
$('#shp_no').val('');
$('#shipDate').val('');
$('#sup').val('');
$('#sup-quantity').val('');
$('#box').val('');
$('#box-quantity').val('');
$("#sup").prop('disabled', true);
$("#sup-quantity").prop('disabled', true);
$("#box").prop('disabled', true);
$("#box-quantity").prop('disabled', true);
$('.alert-success').fadeOut(200).show();
$('.alert-danger').fadeOut(200).hide();
/// alert('form was submitted');
},
error: function(data) {
$('.alert-success').fadeOut(200).hide();
$('.alert-danger').fadeOut(200).show();
}
});
});
The return false returns from the each function and not the click function.
Try having a bool variable denoting valid, and return false if not.
var valid = true;
e.prevent.preventDefault(); // e being event variable in submit
$('input').each(function() {
if(!$(this).val()){
alert('Some fields are empty');
valid = false;
return false;
}
});
if(!valid) return false;
//.....
Hope this helps.

Check the value of a text input field with ajax

I have a website where the log ins are screen names. On the create user form I want to be able to have ajax check if a screen name exists already as it is typed into the form.
This is the HTML form input field
<label for="screenName">Screen Name:
<input type="text" class="form-control" name="screenName" id="screenName" size="28" required>
<div class="screenNameError"></div>
A message should be displayed in the <div class="screenNameError"></div>line if the username matches the database.
This is my Jquery code for this.
$(document).ready(function(){
if ($('#screenName').length > 0){
var screenName = $("input").keyup(function(){
var value = $(this).val();
return value;
})
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + screenName,
success: function (r) {
$('.screenNameError').html(r);
}
})
}
});
This is the PHP file that gets called to make the DB query
$screenName = $_POST['Screen_Name'];
$screenNameSQL = "SELECT Screen_Name FROM Users WHERE Screen_Name = '$screenName'";
$result = $my_dbhandle->query($screenNameSQL); //Query database
$numResults = $result->num_rows; //Count number of results
$resultCount = intval($numResults);
if($resultCount > 0){
echo "The username entered already exists. Please a different user name.";
}
For some reason my Jquery is not firing when I type the username in the form :/
Thanks in advance
Try changing your jQuery to this -
$(document).ready(function() {
$('#screenName').keyup(function() {
var value = $(this).val();
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + value,
success: function(r) {
$('.screenNameError').html(r);
}
});
});
});
However you probably want to minimise the number of ajax requests being made so I would advise putting your ajax request into a setTimeout functon and clearing it with each subsequent keypress. -
$(document).ready(function() {
var ajaxRequest;
$('#screenName').keyup(function() {
var value = $(this).val();
clearTimeout(ajaxRequest);
ajaxRequest = setTimeout(function(sn) {
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + value,
success: function(r) {
$('.screenNameError').html(r);
}
});
}, 500, value);
});
});
if ($('#screenName').length > 0){
You should change it with
if ($('#screenName').val().length > 0){
OR
var name = $('#screenName').val();
if(name.length >0) {...
not sure about the syntax...
Add an event on keyup like this :
Edit
$("#screenName").on("keyup",function(){
var screenName=$(this).val();
if(screenName!='')
{
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + screenName,
success: function (r) {
$('.screenNameError').html(r);
}
})
}
});
JsFiddle
Your ajax call should be inside the keyup handler.

Validate form and some inputs at same time

Here I have a form and I need to validate form. I have select2 input fields and this fields I cant validate with parsley plugin so I write my code...
Problem is how to at same time check if validate = true and select2 inputs ===null...
I write:
$(function() {
$('#myForm').submit(function(e) {
e.preventDefault();
if ( $(this).parsley('validate') ) {
if ($("#parcele").select2("data")== null || $("#vrsta_rada").select2("data")== null) {
$('#parerror').show();
console.log('nema dalje');
} else {
var zemljiste = $("#parcele").select2("data").naziv;
var id_parcele = $("#parcele").select2("data").id;
var vrsta_rada = $("#vrsta_rada").select2("data").text;
$.ajax({
url: "insertAkt.php",
type: "POST",
async: true,
data: { naziv:$("#naziv").val(),parcele:zemljiste,vrsta_rada:vrsta_rada,opis:$("#opis").val(),pocetak:$("#pocetak").val(),zavrsetak:$("#zavrsetak").val(),status:$("#status").val(),id_parcele:id_parcele,}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#myModal').modal('hide');
drawVisualization();
console.log('USPEH');
console.log(data);
},
error: function (data) {
console.log(data);
console.log('GRESKA NEKA');
}
});
}
}
});
});
but as you can see my code first check form validation after that select2 inputs so how I can at same time check form and select2 inputs fields?
By using && operator you can check both condition at the same time
if ( ($(this).parsley('validate')) && ($("#parcele").select2("data") === null)) {
}

Categories

Resources