avoid sending if any field empty Axax - javascript

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.

Related

How to prevent form submit?

I have a login form and a captcha field. I need a javascript source to check this captcha input then send post data to action but my code seems to be wrong, the e.preventDefault function doesn't work because captcha field true or false post data's still sent. please help.
This my javascript Function:
$(document).ready(function () {
$("#signupform").submit(function (event) {
var captchacode = $("#captchatexbox").val();
if (captchacode != "") {
var url = "/Account/ValidateCaptcha?Code=" + captchacode;
$.ajax({
url: url,
cache: false,
success: function (data) {
if (data == 0) {
alert("Invalid captcha");
event.preventDefault();
//Form post data still sent?
}
}
});
}
else alert("Captcha not null");
});
});
You need to move event.preventDefault(); up so it comes before the ajax call.
Use $("#signupform").submit(); in an else block to programmatically submit the form.
$(document).ready(function () {
$("#signupform").submit(function (event) {
event.preventDefault();
var captchacode = $("#captchatexbox").val();
if (captchacode != "") {
var url = "/Account/ValidateCaptcha?Code=" + captchacode;
$.ajax({
url: url,
cache: false,
success: function (data) {
if (data == 0) {
alert("Invalid captcha");
//Form post data still sent?
} else {
$("#signupform").submit();
}
}
});
}
else alert("Captcha not null");
});
});
You would need have the form event.preventDefault(); before making the ajax request.
$("#signupform").submit(function (event) {
event.preventDefault();
When the ajax request is returned, you can submit the form using:
if (data != 0) {
$("#signupform").submit();
}

e.PreventDefault and ajx submit not working together [return true] is not working

I have a function to check whether email exist, but I want to submit the form only if the email doesn't exist
So I wrote following function:
$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
return true;
$(this).submit();
}
}
});
});
Now if it return true also i cant submit the form . Please help.
i saw this question and answer e.preventDefault doesn't stop form from submitting . But no effect
Notes
even i tried
if(response.status=='true') { $("#form-1").submit(); } .
But this also not working
The return statement is returning before the form is submitted
if(response.status == 'true') {
//return true; // returns before the form is submitted
$(this).submit();
return true; // move return after submit
}
Suggestion
You are thinking about this, the wrong way, let PHP handle the checking and insert in the backend.
First Solution
In your PHP do something like
$querycheck = mysqli_query($con,"SELECT * FROM Persons");
$countrows = mysqli_num_rows($querycheck );;
if($countrows == '1')
{
echo json_encode(['message' => 'Sorry This Email Already Used']);
}
else
{
// insert statement here
echo json_encode(['message' => 'Submitted']);
}
In your JS
$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
alert(response.message); // display the message here to the user.
}
});
});
Second Solution
save the form in a variable.
$("#form-1").on("submit",function(e){
e.preventDefault();
const form = $(this); // get the current form
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
form.submit(); // submit the form here
return true;
}
}
});
});

Passing variable from a function into submit function

$('.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();
}
}

Form Validation with Jquery and AJAX

I am using AJAX with JQUERY to call a PHP script to validate a user email. But, for some reason, the form submits even when it shouldn't. What am I doing wrong? I know the error is for sure not in my PHP.
My Code:
$("#signup").submit(function() {
var error= false;
var dataString = $(this).serialize();
var email= $("#email").val().trim();
if (email != 0) {
// Run AJAX email validation and check to see if the email is already taken
$.ajax({
type: "POST",
url: "checkemail.php",
data: dataString,
async: false,
success: function(data) {
var error= false;
if (data == 'invalid') {
var invalid= 1;
}
else if (data == 'taken') {
var taken= 1;
}
if (invalid == 1) {
alert('invalid email');
error = true;
}
if (taken == 1) {
alert('email taken');
error = true;
}
if (error == true) {
return false;
}
}
});
}
});
Try updating these:
$("#signup").submit(function(e) { //<----pass the event here as "e"
e.preventDefault(); //<----stops the form submission
var error= false;
var dataString = $(this).serialize();
var email= $.trim($("#email").val()); //<----use trim this way
If you absolutely have to use AJAX for form submission, this might be a better way to do it:
$('form').submit({
$.ajax({
type:'post',
url: 'someurl.php',
data: dataString,
context: this, // this here refers to the form object
success:function(data)
{
// perform your operations here
if(something_is_wrong)
{
// show message to user
}
else
{
this.submit(); // put this code in the block where all is ok
}
}
});
return false; // makes sure the form doesn't submit
});

How to save var value outside ajax success function?

I am trying to make some form validation functions. Here is what I have:
<script>
$(document).ready(function() {
var myObj = {};
$('#username').keyup(function () {
id = $(this).attr('id');
validateUsername(id);
});
function validateUsername(id){
var username = $("#"+id).val();
$.ajax({
url : "validate.php",
dataType: 'json',
data: 'action=usr_id&id=' + username,
type: "POST",
success: function(data) {
if (data.ok == true) {
$(myObj).data("username","ok");
} else {
$(myObj).data("username","no");
}
}
});
} // end validateusername function
$('#submit').click(function(){
if (myObj.username == "ok") {
alert("Username OK");
} else {
alert("Username BAD");
}
});
}); // end doc ready
So you can see, when a key is pressed in the textbox, it checks if it's valid. The "data.ok" comes back correctly. The problem is based on the response, I define $(myObj).username. For some reason, I can't get this value to work outside the validateusername function. When clicking the submit button, it has no idea what the value of $(myObj).username is.
I need to use something like this, because with multiple form fields on the page to validate, I can do something like:
if (myObj.username && myObj.password && myObj.email == "ok")
... to check all my form fields before submitting the form.
I know I must just be missing something basic.... any thoughts?
EDIT: SOLVED
All I had to do was change var myObj = {}; to myObj = {}; and it's working like a charm. I think I've been staring at this screen waaaaay too long!
You're not accessing the data that you stored properly. Access the username value this way:
$(myObj).data("username")
Resources:
Take a look at jQuery's .data() docs.
Very simple jsFiddle that shows how to properly set and retrieve data with jQuery's .data() method.
I would store the promise in that global variable and then bind an event to the done event within your submit button click.
$(document).ready(function() {
var myObj = false;
$('#username').keyup(function () {
id = $(this).attr('id');
validateUsername(id);
});
function validateUsername(id){
var username = $("#"+id).val();
myObj = $.ajax({
url : "validate.php",
dataType: 'json',
data: 'action=usr_id&id=' + username,
type: "POST",
success: function(data) {
$('#username').removeClass('valid invalid');
if (data.ok == true) {
$('#username').addClass('valid');
}
else {
$('#username').addClass('invalid');
}
}
});
} // end validateusername function
$('#submit').click(function(){
// if myObj is still equal to false, the username has
// not changed yet, therefore the ajax request hasn't
// been made
if (!myObj) {
alert("Username BAD");
}
// since a deferred object exists, add a callback to done
else {
myObj.done(function(data){
if (data.ok == true) {
alert("Username BAD");
}
else {
alert("Username OK");
}
});
}
});
}); // end doc ready
you may want to add some throttling to the keyup event though to prevent multiple ajax requests from being active at once.

Categories

Resources