Problem with onsubmit="some_function();return false;"

Discussion in 'JavaScript' started by LumberJake, Mar 28, 2008.

  1. #1
    Hi, I have a really irritating problem I can't get my head around.

    I wrote (badly) some javascript functions to validate user input on a signup form. in the onsubmit event of the form i have specified that i want process_form() to run, then to return false. (onsubmit="process_form();return false"), so the form is never submitted.

    The thing that is really annoying is, this works sometimes, The desired result comes and goes, seemingly without rhyme or reason. sometimes it will validate it with the javascript function then submit, sometimes it will just submit the form before any client side validation and the php script validates it, and sometimes it does what i want, which is to validate using javascript then stop.

    
    <div id="signup" class="form">
        <form action="signup.php" method="post" onsubmit="process_form(); return false;">
            <fieldset>
                <legend>Sign Up</legend>
                <label for="input_username">Username:</label>
                <input id="input_username" name="username" class="text" type="text" size="30" />
                <label for="input_password">Password:</label>
                <input id="input_password" name="password" class="text" type="password" size="30" />
                <label for="input_con_password">Confirm Password:</label>
                <input id="input_con_password" name="con_password" class="text" type="password" size="30" />
                <label for="input_email">E-mail address:</label>
                <input id="input_email" name="email" class="text" type="text" size="30" />
                <input type="submit" name="submit" class="submit_button" value="Submit!"/>
            </fieldset>
        </form>
        <div id="errors"></div>
    </div>
    Code (markup):
    The javascript i am using.

    var XMLHttpFactories = [
    	function () {return new XMLHttpRequest()},
    	function () {return new ActiveXObject("Msxml2.XMLHTTP")},
    	function () {return new ActiveXObject("Msxml3.XMLHTTP")},
    	function () {return new ActiveXObject("Microsoft.XMLHTTP")}
    ];
    
    function ajaxObject() {
    	var xmlhttp = false;
    	for (var i=0;i<XMLHttpFactories.length;i++) {
    		try {
    			xmlhttp = XMLHttpFactories[i]();
    		}
    		catch (e) {
    			continue;
    		}
    		break;
    	}
    	return xmlhttp;
    }
    
    function process_form()
    {
    	var username = document.getElementById('input_username');
    	var password = document.getElementById('input_password');
    	var con_password = document.getElementById('input_con_password');
    	var email = document.getElementById('input_email');
    	
    	check_username(username);
    	check_password(password);
    	check_con_password(con_password);
    	check_email(email);
    	
    	if(document.getElementById('errors').style.display == 'none')
    		submit_form(username.value + '/' + password.value + '/' + con_password.value + '/' + email.value);
    }
    
    function submit_form(uri)
    {
    	alert('here');
    	inputs = document.getElementByTagName('input');
    	for(i = 0; i <= inputs.length; i++)
    	{
    		inputs[i].disabled = true;	
    	}
    	ajaxRequest = ajaxObject();
    	ajaxRequest.onreadystatechange = function()
    	{
    		//To be done
    	}
    	ajaxRequest.open("GET", "ajax_functions/take_signup/" + uri, true);
    	ajaxRequest.send(null);
    }
    
    function remove_children_from_node(node)
    {
        if(node.hasChildNodes())
    	{
            while(node.childNodes.length >= 1)
    		{
                node.removeChild(node.firstChild);       
            } 
        }
    }
    
    function check_username(obj)
    {
    	if(obj.value != '')
    	{
    		remove_error('username_empty');
    		ajaxRequest = ajaxObject();
    		ajaxRequest.onreadystatechange = function()
    		{
    			if(ajaxRequest.readyState == 4)
    			{
    				if(parseInt(ajaxRequest.responseText))
    				{
    					if(obj.className != 'text_error')
    						obj.className = 'text_error';
    					append_error('Username is unavailable. Please try another.', 'username_taken');
    				}
    				else
    				{
    					if(obj.className != 'text_validated')
    						obj.className = 'text_validated';
    					remove_error('username_taken');
    				}
    			}
    		}
    		ajaxRequest.open("GET", "ajax_functions/check_username/" + obj.value, true);
    		ajaxRequest.send(null);
    	}
    	else
    	{
    		if(obj.className != 'text_error')
    			obj.className = 'text_error';
    		append_error('You have not entered a username.', 'username_empty');
    	}
    }
    
    function check_password(obj)
    {
    	if(obj.value.length < 6)
    	{
    		if(obj.className != 'text_error')
    			obj.className = 'text_error';
    		append_error('Password must be longer than 5 characters.', 'pass_too_short');
    	}
    	else
    	{
    		if(obj.className != 'text_validated')
    			obj.className = 'text_validated';
    		remove_error('pass_too_short');
    	}
    	
    	var pwcobj = document.getElementById('input_con_password');
    	if(pwcobj.value != '')
    		check_con_password(pwcobj);
    }
    
    function check_con_password(obj)
    {
    	if(obj.value != '')
    	{
    		remove_error('no_confirm');
    		var pass_one = document.getElementById('input_password');
    		if(obj.value != pass_one.value)
    		{
    			if(obj.className != 'text_error')
    				obj.className = 'text_error';
    			append_error('Passwords do not match.', 'passwords_different');
    		}
    		else
    		{
    			if(obj.className != 'text_validated')
    				obj.className = 'text_validated';
    			remove_error('passwords_different');
    		}
    	}
    	else
    	{
    		if(obj.className != 'text_error')
    			obj.className = 'text_error';
    		append_error('You have not entered a confirmation password','no_confirm')	
    	}
    }
    
    function check_email(obj)
    {
    	objRegExp = /^([a-z0-9_\.\-])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+$/i;
    
    	if(!objRegExp.test(obj.value))
    	{	
    		obj.className = 'text_error';
    		append_error('Email address is invalid.','invalid_email');
    	}
    	else
    	{
    		obj.className = 'text_validated';
    		remove_error('invalid_email');
    	}
    }
    
    function append_error(error_text, error_id)
    {
    	if(document.getElementById(error_id) == null)
    	{
    		var error_div = document.getElementById('errors');
    		if(!error_div.hasChildNodes())
    		{
    			var ul = document.createElement('ul');
    			ul.id = 'error_list';
    		}
    		else
    		{
    			ul = error_div.firstChild;
    		}
    		
    		var new_li = document.createElement('li');
    		new_li.id = error_id;
    		var new_error = document.createTextNode(error_text);
    		new_li.appendChild(new_error);
    		ul.appendChild(new_li);
    		error_div.appendChild(ul);
    		if(error_div.style.display != 'block')
    			error_div.style.display = 'block';
    	}
    }
    
    function remove_element(el_id)
    {
    	var el = document.getElementById(el_id)
    	if(el != null)
    	{
    		el.parentNode.removeChild(el);
    	}
    }
    
    function remove_error(error_id)
    {
    	remove_element(error_id);
    	remove_ul_if_empty();
    }
    
    function remove_ul_if_empty()
    {
    	var error_list = document.getElementById('error_list');
    	if(!error_list.hasChildNodes())
    	{
    		error_list.parentNode.removeChild(error_list);
    		document.getElementById('errors').style.display = 'none';
    	}
    }
    Code (markup):
    I am aware that this is terrible code (i am a complete beginner) and that the majority, if not all needs restructuring and/or recoding. Criticism welcome.

    Thanks in advance to anyone who checks it out.

    P.s I thought about using a "button" input with the onclick event used to validate, but then i don't think people would be able to press return to submit the form, am i right?
     
    LumberJake, Mar 28, 2008 IP
  2. So1

    So1 Peon

    Messages:
    45
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #2
    use
    <input type="button" name="submit" class="submit_button" value="Submit!" onclick="javascript:process_form();">
    instead of
    <input type="submit" name="submit" class="submit_button" value="Submit!"/>

    <form name="MYFORM" action="signup.php" method="post">
    instead of
    <form action="signup.php" method="post" onsubmit="process_form(); return false;">

    When form processed and there are no errors, submit id through Javascript: document.MYFORM.submit();
     
    So1, Mar 29, 2008 IP
  3. singh.ajit05

    singh.ajit05 Peon

    Messages:
    83
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    function process_form()
    {
    var username = document.getElementById('input_username');
    var password = document.getElementById('input_password');
    var con_password = document.getElementById('input_con_password');
    var email = document.getElementById('input_email');

    check_username(username);
    check_password(password);
    check_con_password(con_password);
    check_email(email);

    if(document.getElementById('errors').style.display == 'none')
    submit_form(username.value + '/' + password.value + '/' + con_password.value + '/' + email.value);
    return false;
    }
     
    singh.ajit05, Mar 29, 2008 IP
  4. LumberJake

    LumberJake Peon

    Messages:
    4
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Thanks for taking the time to reply guys.

    @So1 : I don't want to submit the form _ever_, it will be processed using javascript, then sent off to the server using XMLHttpRequest and further validated, then entered into the database. (if i ever get it working) :confused:

    @singh.ajit05: I have tried onsubmit="return process_form()"

    (function)
    ..
    ..
    return false
    (/function)

    Doesn't seem to work either!
     
    LumberJake, Mar 29, 2008 IP
  5. So1

    So1 Peon

    Messages:
    45
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #5
    this method'll not ever submit the form. Form'll be submitted via javascript. It'll be something like document.getElementById('id_of_your_form').submit(); If u define NAME of the form <form name="FORM"> then js-code'll be document.FORM.submit(); So, u can submit ur form taking into consideration some conditions for submitting. U can do what u need before submit. For example:
    
    function func()
    {
    // doing something
    if (errors) {/*processing exceptions here */}
    else if (we_ready_to_send_data) { /* send AJAX request and processing result using callback-function or specifyc function .. etc */ }
    else if (we_dont_ready_to_send_data_but_we_need_to_submit) { document.FORM.submit(); }
    else { /* smoking sigarettes and drinking coffee */ }
    }
    
    Code (markup):
    what the problem to use .submit() for ur goal?
     
    So1, Mar 30, 2008 IP
  6. LumberJake

    LumberJake Peon

    Messages:
    4
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    document.form.submit() submits the form. I want the form to be stopped from submitting, without fail. The form never needs to be submitted in the usual way, ie page refresh/posted data. It will be sent using ajax.
     
    LumberJake, Mar 31, 2008 IP