This is a simple ajax form I have found on the Internet. It works well except for the fact that after submitting the form, the form fields information is not cleared. I am running out of ideas and I'd appreciate some guidance. Thank you.

In the code below, the form validation is not important (contact.inc.php). I have not plugged in the necessary info in order to keep the form as simple as possible.

Below are 2 files. Contact.php (has the script and css) and contact.inc.php (validates the form input)

1. Contact.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Simple AJAX Contact Form</title>
<script type="text/javascript">
    var http = false;
    if(navigator.appName == "Microsoft Internet Explorer") {
        http = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else {
        http = new XMLHttpRequest();
    }
    function checkform(name, email, subject, content) {
        http.abort();
        http.open("GET", "contact.inc.php?name=" + name + "&email=" + email + "&subject=" + subject + "&content=" + content, true);
        http.onreadystatechange=function() {
            if(http.readyState == 4) {
                document.getElementById('ajaxresponse').innerHTML = http.responseText;
            }
            if(http.readyState == 1) {
                document.getElementById('ajaxresponse').innerHTML = '<img src="loading.gif" alt="Loading" />';
            }
        }
        http.send(null);
    }
</script>
<style type="text/css">
body, td {
    font-family: Lucida Grande, Lucida Sans Unicode, sans-serif;
    font-size: 12px;
    color: #444;
}
input, textarea {
    background: #EEE;
    border: 1px solid #DDD;
    padding: 3px;
    color: #666;
    font-size: 12px;
    font-family: Lucida Grande, Lucida Sans Unicode, sans-serif;
    width: 200px;
}
input.button {
    width: 100px;
    border: 1px solid #CCC;
    cursor: pointer;
}
input:hover, textarea:hover {
    border: 1px solid #ECFF9F;
    background: #FEFEFE;
}
input:focus, textarea:focus {
    border: 1px solid #C3DF53;
    background: #FEFEFE;
}
div#ajaxresponse {
    margin-bottom: 10px;
    min-height: 15px;
}
span#error {
    color: #CF5A5A;
}
span#success {
    color: #6D8F1A;
}
</style>
</head>
<body>

<h2>Simple AJAX Contact Form</h1>
<div id="ajaxresponse"></div>
<form action="" method="post">
    <table>
        <tr>
            <td>Name</td>
            <td><input type="text" name="name" id="name" /></td>
           </tr>
        <tr>
            <td>Email</td>
            <td><input type="text" name="email" id="email" /></td>
          </tr>
        <tr>
            <td>Subject</td>
            <td><input type="text" name="subject" id="subject" /></td>
          </tr>
        <tr>
            <td>Message</td>
            <td><textarea cols="" rows="" name="message" id="message"></textarea></td>
          </tr>
        <tr>
            <td><input type="reset" value="Reset Form" class="button" /></td>
            <td><input type="button" value="Send Message" class="button" onClick="checkform(document.getElementById('name').value, document.getElementById('email').value, document.getElementById('subject').value, document.getElementById('message').value)" /></td>
          </tr>
      </table>
</form>
</body>
</html>

2. Contact.inc.php

<?php
    /* CONFIG
    ----------*/
    // WEBMASTERS EMAIL
    $target = "jdestruel@example.com";
    // WEBMASTERS NAME
    $targetname = "Jean-Claude";
    // ENABLE SUBJECT PREFIX (true or false)
    $subjprefixe = true; // SET TO FALSE TO DISABLE PREFIX
    // SUBJECT PREFIX
    $subjprefix = "";
    
    /* VARIABLES
    -------------*/
    $name = $_GET['name'];
    $email = $_GET['email'];
    $subject = $_GET['subject'];
    $content = $_GET['content'];
    
    /* CHECKING DETAILS
    --------------------*/
    if(empty($name) && empty($email) && empty($subject) && empty($content)) {
        echo '<span id="error">Please fill in all fields.</span>';
    }
    elseif(empty($name)) {
        echo '<span id="error">Please enter a name</span>';
    }
    elseif(empty($email)) {
        echo '<span id="error">Please enter an email</span>';
    }
    elseif(empty($subject)) {
        echo '<span id="error">Please enter a subject</span>';
    }
    elseif(empty($content)) {
        echo '<span id="error">Please enter message</span>';
    }
    elseif(!preg_match( "/^([a-zA-Z0-9])+([a-zA-Z0-9._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9._-]+)+$/", $email)) {
        echo '<span id="error">Please enter a valid email.</span>';
    }
    elseif(strlen($name) < 3) {
        echo '<span id="error">Your name can not be smaller than 3 characters.</span>';
    }
    elseif(strlen($email) < 9) {
        echo '<span id="error">Your email can not be smaller than 9 characters.</span>';
    }
    elseif(strlen($subject) < 3) {
        echo '<span id="error">Your subject can not be smaller than 3 characters.</span>';
    }
    elseif(strlen($content) < 20) {
        echo '<span id="error">Your message can not be smaller than 20 characters.</span>';
    }
    else {
        /* EMAIL
        ---------*/
        $headers  = 'MIME-Version: 1.0' . "rn";
        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn";
        $headers .= 'To: ' . $targetname . ' <' . $target . '>' . "rn";
        // TARGET EMAIL AS SENDER TO MAKE SURE IT'S NOT IN THE SPAM FOLDER
        $headers .= 'From: ' . $name . ' <' . $target . '>' . "rn";
        $headers .= 'Reply-To: ' . $name . ' <' . $email . '>' . "rn";
        if($subjprefixe == true) {
            $subject = $subjprefix . " " . $subject;
        }
        $message = '
        <html>
        <head>
            <title>' . $subject . '</title>
            <style type="text/css">
                body, td {
                    font-family: Lucida Grande, Lucida Sans Unicode, sans-serif;
                    font-size: 12px;
                    color: #444;
                    background: #EEE;
                }
            </style>
        </head>
        <body>
            <p>
                <b>Sender:</b> ' . $name . ' <' . $email . '><br />
                <b>Subject:</b> ' . $subject . '<br />
                <b>Message:</b><br />' . nl2br($content) . '
            </p>
            <p>--<br />Message sent at ' . date("d/m/Y H:i:s") . '</p>
        </body>
        </html>
        ';
        if(mail($target, $subject, $message, $headers)) {
            echo '<span id="success">Message Sent</span>';
        }
        else {
            echo '<span id="error">Something went wrong while sending the email.</span>';
        }
    }
?>

Much appreciated

Recommended Answers

All 11 Replies

In the code append few lines of code in this manner that clears the information entered in the text fields if the successfull form submission is made,remember if successful form submission is made.

[B]
function clearInputs()
{
document.getElementById('name').value="";
document.getElementById('email').value="";
document.getElementById('subject').value="";
document.getElementById('message').value="";
}
[/B]

And call

[B]clearInput function[/B]  like this after successful submission
[B]
if(http.readyState == 4) {
document.getElementById('ajaxresponse').innerHTML = http.responseText;

clearInputs();
}
[/B]

If you want to clear the input even if form submission was not successful then call it here,it will work great,it doesn't depend on the result whether successful or unsuccessful,it will clear the input fields. :)

[B]
<input type="button" value="Send Message" class="button" onClick="checkform(document.getElementById('name').value, document.getElementById('email').value, document.getElementById('subject').value, document.getElementById('message').value); clearInputs();" /> 

[/B]

:) good luck

Hi,

Thanks a lot from the code, I've learned a lot and it works; but....now when I enter incorrect information, such as email = abc#abc.com for instance and press "Send message", instead of displaying the error message for a chance to correct it, it clears the form entirely. I know this is what I ask :-); but, now, I have a different issue -> displaying error messages, if any, and not clearing the form so that I can correct them when I click "Send message".

I've tried to call the function after ... bottom of my code above

if(mail($target, $subject, $message, $headers)) {
echo '<span id="success">Message Sent</span>';
-> right here; but it didn't work.

This is what I have... neither options work. I can display the error messages and not clear the fields so that the good inputs stays as is and it gives me a chance to edit the wrong ones; but, when I click "Send message"... it displays "Message sent"; but, the fields are not cleared.

Much appreciated any help!

Option 1:...

$sentemail = true; 
if(mail($target, $subject, $message, $headers)) {
   echo '<div align=center><span id="success">Message sent</span></div>';                
   if($sentemail == true) {  
      echo '<script>clearInputs();</script>';    
   }  
   $sentemail = false; 	  
...

and..

if(http.readyState == 4) {
document.getElementById('ajaxresponse').innerHTML = http.responseText;
}

Option 2:

$sentemail = true; 
if(mail($target, $subject, $message, $headers)) {
   echo '<div align=center><span id="success">Message Sent</span></div>';                		
}

..and ...

if(http.readyState == 4) {
document.getElementById('ajaxresponse').innerHTML = http.responseText;
	if($sentemail == true) {  
	echo '<script>clearInputs();</script>';    
	}  
	$sentemail = false; 			                
}

...

Do you mean to say that you want to do some validation and error checking too?

If this is the case ,then do not call your php file that sends mail in this way.

Write a JavaScript function that checks for any errors,if that JavaScript returns true then call the php through that java script

If it returns false,then show errors or validation messages.

:)

And sorry for the late reply,as I was enjoying India Pakistan cricket match...

Hope your team won!

In the original code I sent... contact.inc.php, the fields are validated and display a message if incorrect, it's only when everything is kosher that by clicking on the "Send Message" displays "Message Sent" and that the fields should be cleared. Sorry if I wasn't explicit enough.

Is there any way to use a "variation" of the contact.inc.php without having to write a js validation function?

Any help is much appreciated.

The present form puts the response text in the div

You are using a roundabout method , why not directly check using js its not that tough .

A variation would be to avoid ajax and try having submit redirect to same page . If all are proper you clear form or initialize from according to conditions - else display back with the from with only the correct fields

Thanks for the quick reply and the re-formatting from the moderator -> this makes it a lot clearer.

I'm new to js and ajax and the reason why I wanted to use ajax was the possibility of refreshing only the form fields without having to refresh the entire page. So I found this form and thought it would be an easy "thing" to just mod it; but, if I have to write an entire js script instead, I may hang up my hat OR if you know of a link where I can work from something, I don't mind sweating it through to get started :-)

Thanks for all your feedback.

This is the javascript that you can use to validate your form
Add only the validate_form ( ) funtion in your already defined <script>..</script> tags or simply write it above your checkform() funtion

<script type="text/javascript">


function validate_form ( )
{
    var msg="Please fill in details...";
    var flag=0;
    //Declaration of msg variable

    //Checking for all fieelds, whether they contain values or not
    //If left blank and clicked on your submit button,it will show alert message
    //Showing that the certain required fields are left as empty...
    if ( document.getElementById('name').value == "" )
    {
        msg=msg + "\n--> Your name";
        flag=1;
    }
    if(document.getElementById('email').value == "" )
    {
         msg=msg + "\n--> Your Email";
        flag=1;
    }
    //Below given block of code checks for email validation
    if(document.getElementById('email').value != "" )
    {
        
      var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
      var address = document.getElementById("email").value;
      if(reg.test(address) == false) {
       msg=msg + "\n--> Invalid Email";

       flag=1;
    
    }
    if ( document.getElementById('subject').value == "" )
    {
         msg=msg + "\n--> Your Subject";
         flag=1;
    } 
    if(document.getElementById('message').value == "" )
    {
         msg=msg + "\n--> Your Message";
        flag=1;
    }



   
   if(flag==1)
   {
       alert(msg);
       return false;
   }
   else
   { 
        return true;
   }
}

</script>

And a bit of change in this code...

function checkform(name, email, subject, content) {
http.abort();
if(validate_form ()) //This if condition checks for validation
{                    //And if true is returned then only the form will be submitted
                     //using ajax 
http.open("GET", "contact.inc.php?name=" + name + "&email=" + email + "&subject=" + subject + "&content=" + content, true);
http.onreadystatechange=function() {
if(http.readyState == 4) {
document.getElementById('ajaxresponse').innerHTML = http.responseText;
}
if(http.readyState == 1) {
document.getElementById('ajaxresponse').innerHTML = '<img src="loading.gif" alt="Loading" />';
}
}
http.send(null);
}
}

Now the last important thing to do is to comment the Validation code of your Contact.inc.php,or remove the if conditions just because no need to check for any errors that side. If correct data is there,then only that .php file will be called

Hope it helpss....


Mark is as solved it it helps,so it can help others...

Whao! Thanks a million. I'll try it this weekend and I'll let you know how it went.

Yep,do let me know :D

this is what i am looking for.. woot~!

thanks a lot guys.. i was just passing by and this will really help me..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.