validating an initially hidden form using jquery - php

I'm validating an initially hidden form using jquery, but the form is submitted even though the fields are empty
$(document).ready(function () {
jQuery("#name").validate({
expression: "if (VAL) return true; else return false;",
message: "* Please enter name"
});
});
I'm doing this for ajax submition of the form ..
$("#send").click(function (e) {
e.preventDefault();
var name = $('#name').val();
$.ajax({
// ajax submition
)};
});

Try this... and use the <form> id instead for the validate function.
$(document).ready(function () {
jQuery("#formid").validate({
ignore:'',
rules:{
name:{
required:true
}
},
messages:{
name:{
required:'* Please enter name'
}
}
});
});
I think you are using the newer version of jQuery validator plugin which ignores hidden elements by default.
In reply to your updated question you can just do this
$("#send").click(function (e) {
e.preventDefault();
var name = $('#name').val();
if(name.length > 0){ //if length is greater than 0 then only fire ajax else show the error
$.ajax({
// ajax submition
)};
}else
//show error
alert('Name not found');
}
}

Related

PHP - Displaying SweetAlert modal popup upon successful registration (AJAX)

I'm wanting to make it so that when my ajax code returns no errors, I get the modal. All my code is working perfectly, I just need to know how to make the modal popup once there are no errors. I have a ajax success: function but I'm not sure how this piece of code would work because at the moment, it only works when a button is clicked.
I'm using the SweetAlert JS files
My code :
The working modal when button is clicked:
<script>
!function(e){ "use strict";
var t = function(){};
t.prototype.init = function() {
e("#sa-success").click(function() {
swal("Registration Successful","Your registration was successful! Check your email and click on your activation link to be able to access your account.","success")
}
)
},e.SweetAlert=new t,e.SweetAlert.Constructor=t}(window.jQuery),function(e){"use strict";e.SweetAlert.init()}(window.jQuery);
</script>
My AJAX registration code I want to make the modal popup once msg = ' ' :
<script>
$(document).ready(function() {
jQuery.validator.addMethod("noSpace", function(value, element) {
return value.indexOf(" ") < 0 && value != "";
}, "Spaces are not allowed");
$("#registered_form").submit(function() {
if ($("#registered_form").valid()) {
var data1 = $('#registered_form').serialize();
$.ajax({
type: "POST",
url: "inc/pgs/register.php",
data: data1,
success: function(msg) {
console.log(msg);
if(msg == '') {
//setTimeout("window.location.href='login.php';",4000);
} else {
$("#result").html('<div class="alert alert-danger"><button type="button" class="close"></button>' + msg +'</div>').slideDown(100);
window.setTimeout(function()
{
$(".alert").fadeTo(500, 0).slideUp(500, function(){
$(this).remove();
});
}, 3000);
}
}
});
}
return false;
});
});
</script>
All sorted. I had to see the SweetAlert manual to see how it works. I should've checked before.
I just had to use :
swal("Registration Success!", "Your registration was successful! Check your email and click on your activation link to be able to access your account.", "success");

ajax form validation in laravel 5

I am new in laravel and need help.
These are the values I'm getting via ajax, all values are to be stored in db, but how do I validate[check] if there are existing values or not before submitting a form using ajax?
$("#submit").click(function(e){
e.preventDefault();
var url = "{!! URL::to('/') !!}";
var id="{!! #$department->id !!}";
var token = "{!! csrf_token() !!}";
var customer_id = $("#customer_id").val();
var visiting_address1 = $("#visiting_address1").val();
var department_id = $("#department_id").val();
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: url+"/customer/"+customer_id+"/popup_store",
data: { '_token':token, 'rest':'true', 'customer_id':$("#customer_id").val(), 'main_address':$("#main_address").val(),'visiting_city':$("#visiting_city").val(),'visiting_address':$("#visiting_address1").val(),'visiting_zip':$("#visiting_zip").val()},
async : false,
success : function(data) {
if(data == "success")
{
$("#addrecords").modal('hide');
}
else
alert(data);
}
});
});
First of all define you Jquery validation for you form like this:
$("#myForm").validate({
// Specify the validation rules
rules: {
name: "required",
},
// Specify the validation error messages
messages: {
name: "Please enter name",
},
submitHandler: function (form) {
// leave it blank here.
}
});
And then in your click button of submit button, write if condition to check validations:
$("#submit").click(function (e) {
if ($('#myForm').valid()) {
// your Ajax Call Code
} else {
return false;
}
});

form submission prevent return button from being pressed but bind to function

I have a form which is being posted via ajax. I would like the default action of the return button on the keyboard removed and replaced by the .click event.
here is my code posting the form:
$("#submit").click(function(){
var name = $("#name").val();
if(name ==''|| email==''|| contact==''|| gender==''|| msg==''){
//alert("Insertion Failed Some Fields are Blank....!!");
}
else{
$.post("<?php bloginfo('template_url');?>/ajax.php",{ name1: name, email1: email, contact1: contact, gender1:gender, msg1:msg},
function(data) {
$('#form')[0].reset(); //To reset form fields
});
}
});
I have then got the following to prevent the reurn key being pressed:
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
});
any idea on how i would achieve this?
Add this to your function when the return key gets pressed:
$(window).keydown(function(event) {
if (event.keyCode == 13) {
event.preventDefault();
$("#submit").click();
return false;
}
}
call the click method of the submit button.
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
$("#submit").click();
event.preventDefault();
return false;
}
});
});
http://api.jquery.com/click/#example-1

prevent form from executing if field is blank

i am trying to prevent the form from executing if the search field is blank.
html
<form id="form" action="">
<input type="text" id="lookup"><input type="submit" id="find" value="Look Up">
</form>
jquery
$('#find').click(function(){
var s = ('#lookup').attr('value');
if(s!=""){
$.ajax({
url: result/,
type:'POST',
data: s
success: function(){ //empty }
});
}
});
also tried
action="result" //form the form
$('#find').click(function(){
var s = ('#lookup').attr('value');
if(s!=""){
$("#form").submit();
}
});
Bind the submit event, and return false when the search field is blank, and true if it isn't. Returning false will prevent the form from being submitted.
$("form").submit(function() {
var s = $.trim($('#lookup').val());
if (s) {
$.ajax();
return true;
}
return false;
});
DEMO.
you can simple add do this
$('#find').click(function(){
var s = ('#lookup').attr('value');
if(s==""){
return false;
}
});
$('#find').click(function(e){
var s = ('#lookup').attr('value');
if(s!=""){
$.ajax({
url: result/,
type:'POST',
data: s
success: function(){ //empty }
});
}
e.preventDefault();
});
e.preventDefault() will stop submit button from actually submitting a form. Or you can use return false.
But suppose in your case it will be enough to do something like:
$('#find').click(function(e){
var s = ('#lookup').attr('value');
if(s==""){
e.preventDefault();
}
});
try
$('#find').click(function(){
var s = ('#lookup').val();
if(s!="" && s != undefined && s!=null){
//do your business here
}
});

How to disable form submit if the username is not available

I have checked the user name availability. The problem is, even if the username is not available, the form is posting.
Edited Code:
<SCRIPT type="text/javascript">
$(document).ready(function(){
$("#emailch").change(function() {
var usr = $("#emailch").val();
if(usr.length >= 3)
{
$("#status").html('<img src="images/loader.gif" align="absmiddle"> Checking availability...');
$.ajax({
type: "POST",
url: "includes/check.php",
data: "username="+ usr,
success: function(msg){
$("#status").ajaxComplete(function(event, request, settings){
if(msg == 'OK')
{
$("#username").removeClass('object_error'); // if necessary
$("#username").addClass("object_ok");
$(this).html(' <img src="images/tick.gif" align="absmiddle">');
}
else
{
$("#username").removeClass('object_ok'); // if necessary
$("#username").addClass("object_error");
$(this).html(msg);
}
});
}
});
}
else
{
$("#status").html('<font color="red">The username should have at least <strong>3</strong> characters.</font>');
$("#username").removeClass('object_ok'); // if necessary
$("#username").addClass("object_error");
}
});
});
</SCRIPT>
What I want is that, the form should not be posted if the user name is not available. I have tried by using return false; in IF CONDITION but it fails. Please suggest any alternate method. Any help will be appreciated.
on submit return false no matter what, if the field is good do your ajax send of the form, if its bad, error out or whatever you need
<form action="http://www.google.com" id="formId" method="post">
<input type="text" id="emailch" name="emailch" />
<input type="submit" />
</form>
<script type="text/javascript">
$(document).ready(function(){
$("#formId").submit( function() {
if( $("#emailch").val().length >= 3){
alert( 'the form is going to post via ajax here' );
}else{
alert( 'user name invalid error out or whatever you need to do.' );
}
return false;
});
});
</script>
Using return false to stop a form from being submitted doesn't really work that well in jQuery. Use event.preventDefault() instead, try something like this:
$(function() {
$('#formid').submit(function(event) {
if ($("#emailch").val().length < 3) {
event.preventDefault();
}
});
});
Set a flag (variable) in your success function to false (for instance) if the username is not available. Then check that flag in your form's onsubmit handler, and if the flag equals false, return false from that event handler, and your form will not submit.

Categories