Jump to content

validate form with ajax


.josh

Recommended Posts

okay i initially posted this question at ajaxfreaks.com but it seems nobody really ever goes over there.. I guess it just hasn't quite caught on yet [img src=\"style_emoticons/[#EMO_DIR#]/huh.gif\" style=\"vertical-align:middle\" emoid=\":huh:\" border=\"0\" alt=\"huh.gif\" /] well i personally do not think my bug is with the ajax script so i thought maybe i'd post it here and see if anybody can help.

so like, i'm learning some ajax to include on my website, so i'm making this register form validation script. the javascript is setup where the submit button will show only if all of the required fields are filled, and the user/email is valid.

The ajax part works fine. onblur calls the ajax functions to check if my user/email exists in the database and it does, and the correct stuff is returning and displaying.

all of the other required fields work fine. they are highlighted if you skip them, and they stop being highlighted if you fill something out... except for the user/email fields.

For some reason, even though the proper message is returned from the validate_sql.php and it is displayed properly, javascript is not showing them as validly filled out fields, and therefore the submit button is not showing.

here is a linkie to my script:

[a href=\"http://www.chroniclesofwar.com/test/testform.php\" target=\"_blank\"]http://www.chroniclesofwar.com/test/testform.php[/a]

try for instance using 'crayonviolent' in the user name field. it will say that it is already taken, and the box will highlight red. so if you go back and enter in a name that is not taken, it will output '!error' meaning the name is okay. but the box stays red, and the submit form will not show.

[code]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<title>Untitled</title>
<!-- *** CSS ********************************* -->
<style type="text/css">
#userfield, #emailfield{
    color: #000000;
    float:left;
}
#user_container, #email_container{
    float:left;
}
.error{
    border: 2px solid #FF0000;
    background-color:#FEDADB;
}
.skipped{
    border: 2px solid #FF0000;
    background-color:#00CCFF;
}
.noclass{    
    color: #000000;
}
#submitholder{    
    color: #000000;
}
</style>
<!-- *************** end css ******************-->
</head>

<script lang='javascript'>
<!-- *****************javascript ****************-->

var problemArray = new Array();

function dispSubmit(field,action){
    if(problemArray.length != 0){
        for(var i = 0; i < problemArray.length; i++){
            if(problemArray[i] == field){    
                place = i;
                break;
            }else{
                place = -12;
            }
        }
    }else{
        place = -50;
    }
    if(action == "add" && place < 0){
        problemArray.splice(problemArray.length,0,field);
    }else if(action == "remove" && place >= 0){
        problemArray.splice(place,1);
    }
     <!--DISPLAY ERROR OR SUBMIT BUTTION-->
    if(problemArray.length != 0){
        document.getElementById('submitholder').innerHTML = "There seems to be a problem with one or more of your fields";
    }else{
        document.getElementById('submitholder').innerHTML = '<input type="submit" name="Submit" value="Submit" />';
    }
}


<!--TRIM ALL LEADING AND FOLLOWING WHITESPACE IN A STRING-->
function trimString (str) {
  return str.replace(/^s+/g, '').replace(/s+$/g, '');
}

<!--HIGHLIGHT EMPTY FIELDS THAT ARE REQUIRED-->
function hiliteRequired(startValFROM,place){
    <!--DEFINE THE ID'S OF THE REQUIRED FIELDS-->
    var requiredFields = new Array()
        requiredFields[0] = "userfield"
        requiredFields[1] = "emailfield"
        requiredFields[2] = "testfield"
        requiredFields[3] = "testoption"
    
    var pos = requiredFields.length;
    for(var i = 0; i < requiredFields.length; i++){
        if(requiredFields[i] == startValFROM){
            pos = i;
        }else{
            if (pos > place){
                pos = place;
            }else{
                pos = pos;
            }
        }
    }
    <!--HIGHLIGHT EMPTY FIELDS-->
    for(var x = 0; x < pos; x++){
        if(trimString(document.getElementById(requiredFields[x]).value) == ""){
            document.getElementById(requiredFields[x]).className = 'skipped';
            dispSubmit(requiredFields[x],'add');
        }else if(document.getElementById(requiredFields[x]).className != "error"){
            document.getElementById(requiredFields[x]).className = 'noclass';
            dispSubmit(requiredFields[x],'remove');
        }
    }
    <!--FIX FOR IF THE USER WERE TO NAVIGATE THE FORM IN REVERSE-->
    for(var y = 0; y < requiredFields.length; y++){
        if(trimString (document.getElementById(requiredFields[y]).value) != "" && document.getElementById(requiredFields[y]).className != "error"){
            document.getElementById(requiredFields[y]).className = 'noclass';
            dispSubmit(requiredFields[y],'remove');
        }
    }
}

<!-- **************** AJAX *********************** -->

function createRequestObject() {
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        ro = new XMLHttpRequest();
    }
    return ro;
}

var http = createRequestObject();

function validateForm(txtfield){
    var url = 'validate_sql.php?field=';
    var url2;
    var username = document.getElementById('userfield').value;
    var email = document.getElementById('emailfield').value;
    
    if (txtfield == "userfield"){
        url2 = txtfield+unescape("%26userfield=")+username;
    }else if(txtfield == "emailfield"){
        url2 = txtfield+unescape("%26emailfield=")+email;
    }

    url += url2;
    http.open('get', url);
    http.onreadystatechange = handleResponse;
    http.send(null);
}

function handleResponse() {
    if(http.readyState == 4){
        var response = http.responseText;
        var UPDATE = new Array();
        <!--LOOP THROUGH THE RESPONSES-->
                if(response.indexOf('|' != -1)) {
            UPDATE = response.split('|');
            if(UPDATE[1] != '!error'){
                document.getElementById(UPDATE[0]).className = 'error';
                document.getElementById(UPDATE[0]+'_container').innerHTML = UPDATE[1];
                dispSubmit(UPDATE[0],'add');
            }else if(UPDATE[1] == '!error'){
                if(document.getElementById(UPDATE[0]).className != 'skipped'){
                    document.getElementById(UPDATE[0]).className = 'noclass';
                }
                document.getElementById(UPDATE[0]+'_container').innerHTML = "";
                if(trimString(document.getElementById(UPDATE[0]+'_container').value) != ""){
                    dispSubmit(UPDATE[0],'remove');
                }
            }
        }
    }
}
<!-- **********************END AJAX ******************-->


</script>                
<body>

<form action="" method="get">
<table width="776" border="0" cellspacing="3" cellpadding="3">
  <tr>
    <td width="258">Username: *req* </td>
    <td width="497"><input type="text" name="user" id="userfield" onblur="validateForm('userfield');" onfocus="hiliteRequired('userfield')" /><div id="userfield_container"></div></td>
  </tr>
  <tr>
    <td>Email: *req* </td>
    <td><input type="text" name="email" id="emailfield" onblur=" validateForm('emailfield');" onfocus="hiliteRequired('emailfield')" /><div id="emailfield_container"></div></td>
  </tr>
  <tr>
    <td>What color is your shirt?: </td>
    <td><input type="text" name="textfield" onfocus="hiliteRequired('color',2)"  />    </td>
  </tr>
  <tr>
    <td>required (but not defined): </td>
    <td><input type="text" name="test" id="testfield" onfocus="hiliteRequired('testfield')" /></td>
  </tr>
  <tr>
    <td>required drop down: </td>
    <td>
    <select name="testoption" id="testoption" onfocus="hiliteRequired('testoption')">
      <option value=""></option>
      <option value="test">test</option>    
    </select>    </td>
  </tr>
  <tr>
    <td>not required: </td>
    <td><input type="text" name="test" id=”testfield2” onfocus="hiliteRequired('testfield2',5)" /></td>
  </tr>
  <tr>
    <td> </td>
    <td><div id="submitholder"></div></td>
  </tr>
</table>
</form>

</body>
</html>
[/code]
Link to comment
Share on other sites

  • 1 month later...
The error is in the ajax part, I copied your code and removed the ajax part and seems to work (not sure if it's right, but the error problem is gone).

One of the problem may be in this statement
[code]
                document.getElementById(UPDATE[0]+'_container').innerHTML = "";
                if(trimString(document.getElementById(UPDATE[0]+'_container').value) != ""){
                    dispSubmit(UPDATE[0],'remove');
                }
[/code]

I don't think you need the _container in the getElementById(UPDATE[0]+'_container').value since you checking the field and not the container.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.