[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

ajax form sumbit

Posted on 2016-11-27
3
Medium Priority
?
115 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 9

Accepted Solution

by:
Karen earned 1000 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 2

Assisted Solution

by:Andrew Derse
Andrew Derse earned 1000 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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article you'll learn how to use Ajax calls within your CodeIgniter application. To explain this, I'll illustrate how to implement a simple contact form to allow visitors to send you an email through your web site.
Introduction Knockoutjs (Knockout) is a JavaScript framework (Model View ViewModel or MVVM framework).   The main ideology behind Knockout is to control from JavaScript how a page looks whilst creating an engaging user experience in the least …
The viewer will learn how to dynamically set the form action using jQuery.
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)

656 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