Solved

ajax form sumbit

Posted on 2016-11-27
3
30 Views
Last Modified: 2016-11-29
Hello Experts,

For some reason even when all the required fields are left empty the form is being submitted. I re-checked the script below couple of times and yet i am not sure why the form submission executes when the required fields are left empty or are not valid.
Can anyone please help me?


$(document).ready(function() {
	
	var form = $('#enquiry-form');
			
	var requiredInput = $("#enquiry-form input[inputRequired], #enquiry-form textarea[inputRequired]");
	var validEmail = new RegExp(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);	
	
	
	// fields validation function
	var validateRequired = function(evt) {		
	 
		$(requiredInput).each(function() {
		
			if (($.trim($(this).val() )=== "") || ($.trim($(this).val()).length <= 2)) {
			
				$(this).addClass("error");
			
				if ($(this).is('#first_name')) {					  
					$(this).parent().find(".placeholder").text("Please enter your name");					
				} else if ($(this).is('#last_name')) {
					$(this).parent().find(".placeholder").text("Please enter your last name");				
				} else if ($(this).is('#email')) {				 
					$(this).parent().find(".placeholder").text("Please enter your email address");	
				}
				
				evt.preventDefault();		
				
			} else {
				$(this).removeClass("error");
				$(this).parent().find(".placeholder").text("");
			}
		});
	};
	// end fields validation function
	
	// email validation function
	
	var validateEmail = function(evt) {
		
		if($(this).val().match(validEmail)) {
						
			$(this).removeClass("error");
		} else {
			$(this).addClass("error");
			$(this).parent().find(".placeholder").text("Please enter a valid email address");
			evt.preventDefault();
		}
	};
	// end email validation function	
		
	$(requiredInput).blur(validateRequired);
	$("#email").blur(validateEmail);
	
			
	$(form).on("submit", function(evt) {
		evt.preventDefault();	
		
		validateRequired.call($(requiredInput),evt);
		
		if (validateRequired.call($(requiredInput),evt) && validateEmail.call($('email'),evt)) {		
			formError();		
		} else {
			submitForm();		
		}		
	});	
	
	function submitForm() {
		
		var formData = $(form).serialize();
		
		var first_name = $("#first_name").val();
               var last_name = $("#last_name").val();
               var email = $("#email").val();
		var oid = '0000';
		var lead_source = 'Exclusive....';
		
		$.ajax({
			type: "POST",
			url: "https://www.salesforce.com/......",
			dataType: "json",
			data: formData,
			
			complete: function() {
				 $(form).css("opacity", 0.5);
				 $(".enquiry-confirmation").show();
        	}
			
		});
			
		
	} // end of submitForm function
	
	function formError() {
		// printing some error text
	}
	
});
	
	

Open in new window

0
Comment
Question by:Refael
3 Comments
 
LVL 9

Accepted Solution

by:
Karen earned 250 total points
ID: 41903444
First thing I notice is that you are not returning anything from your functions to tell the calling routine whether they were successful or not.
So your code will always hit the 'else' part of the condition.
Something like this:

	var validateRequired = function(evt) {		
		var allValid = true;                              // *******************
		$(requiredInput).each(function() {
			if (($.trim($(this).val() )=== "") || ($.trim($(this).val()).length <= 2)) {
			        allValid = false;                 // *******************
				$(this).addClass("error");
			
				if ($(this).is('#first_name')) {					  
					$(this).parent().find(".placeholder").text("Please enter your name");					
				} else if ($(this).is('#last_name')) {
					$(this).parent().find(".placeholder").text("Please enter your last name");				
				} else if ($(this).is('#email')) {				 
					$(this).parent().find(".placeholder").text("Please enter your email address");	
				}				
				evt.preventDefault();						
			} else {
				$(this).removeClass("error");
				$(this).parent().find(".placeholder").text("");
			}
		});
		return AllValid;          // *******************
	};
	var validateEmail = function(evt) {
		if($(this).val().match(validEmail)) {						
			$(this).removeClass("error");
			return true;          // *******************
		} else {
			$(this).addClass("error");
			$(this).parent().find(".placeholder").text("Please enter a valid email address");
			evt.preventDefault();
			return false;          // *******************
		}
	};
			
	$(form).on("submit", function(evt) {
...
// I think you want your selector here to be #email instead of email		
		if (validateRequired.call($(requiredInput),evt) && validateEmail.call($('#email'),evt)) {		
			// both returned 'true' so can submit the form
			submitForm();		
		} else {
			// there was at least one problem, so do not submit the form
			formError();		
		}		
	});	

Open in new window

0
 
LVL 1

Assisted Solution

by:Andrew Derse
Andrew Derse earned 250 total points
ID: 41906480
You are also calling the values way to late to be validated...those need to be the very first step.

Also it would be great to break out the functions into smaller chunks like this...it's not 100% correct, but it's going to get you started in the right direction:
function prepForm() {
    var form = $('#enquiry-form');
    
    var formData = $(form).serialize();
    var first_name = $("#first_name").val();
    var last_name = $("#last_name").val();
    var email = $("#email").val();
    var oid = '0000';
    var lead_source = 'Exclusive....';
    
    var requiredInput = $("#enquiry-form input[inputRequired], #enquiry-form textarea[inputRequired]");
    var validEmail = new RegExp(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);


    // fields validation function
    var validateRequired = function(evt) {

        $(requiredInput).each(function() {

            if (($.trim($(this).val() )=== "") || ($.trim($(this).val()).length <= 2)) {

                $(this).addClass("error");

                if ($(this).is('#first_name')) {
                    $(this).parent().find(".placeholder").text("Please enter your name");
                } else if ($(this).is('#last_name')) {
                    $(this).parent().find(".placeholder").text("Please enter your last name");
                } else if ($(this).is('#email')) {
                    $(this).parent().find(".placeholder").text("Please enter your email address");
                }

                evt.preventDefault();

            } else {
                $(this).removeClass("error");
                $(this).parent().find(".placeholder").text("");
            }
        });
    };
    // end fields validation function

    // email validation function

    var validateEmail = function(evt) {

        if($(this).val().match(validEmail)) {

            $(this).removeClass("error");
        } else {
            $(this).addClass("error");
            $(this).parent().find(".placeholder").text("Please enter a valid email address");
            evt.preventDefault();
        }
    };
    // end email validation function	

    $(requiredInput).blur(validateRequired);
    $("#email").blur(validateEmail);


    $(form).on("submit", function(evt) {
        evt.preventDefault();

        validateRequired.call($(requiredInput),evt);

        if (validateRequired.call($(requiredInput),evt) && validateEmail.call($('email'),evt)) {
            formError();
        } else {
            submitForm( formData );
        }
    });
}
function submitForm( formData ) {
    
    $.ajax({
        type: "POST",
        url: "https://www.salesforce.com/......",
        dataType: "json",
        data: formData,

        complete: function() {
            $(form).css("opacity", 0.5);
            $(".enquiry-confirmation").show();
        }

    });


} // end of submitForm function

function formError() {
    // printing some error text
}

$(document).ready(function() {
    prepForm();
});
	
	

Open in new window

0
 

Author Closing Comment

by:Refael
ID: 41906525
Karen and Andrew thank you so much!
Learning from your code and your comments helps me to be a better coder :-)
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Requirements JQuery 1.6+ HTML CSS Introduction This article was inspired by an EE question (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_28372511.html) on how to make a page show some balloons animate up a page…
Introduction If you're like most people, you have occasionally made a typographical error when you're entering information into an online form.  And to your consternation, the browser remembers the error, and offers to autocomplete your future entr…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now