AJAX contact form

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • colt28
    New Member
    • Dec 2007
    • 9

    AJAX contact form

    Ok so I found an ajax contact form script but i can't get the b****** to work. I made a bunch of alterations to it and it didn't work so i replaced everything with the original and it still didn't work...dunno why, but anyhow. The form appears after a delay on the page in a hidden DIV. The original form just had name, email and message, but i have to add a few questions to it so i did and i also added some code from another script i found to alter the body text. I probably screwed it all up but i'm no expert so please help.

    All the code is in a single php file that's called as an include in the actual page. It displays just fine but when i go to submit it just says "please wait" and never sends an email.

    [CODE=php]<?
    if(!isset($rnd) || !isset($name) || !isset($email) || !isset($realtor ) || !isset($when) || !isset($selling )) {
    showform();
    } else {
    processform();
    }

    $Body = "";
    $Body .= "Name: ";
    $Body .= $Name;
    $Body .= "\n";
    $Body .= "Email: ";
    $Body .= $email;
    $Body .= "\n";
    $Body .= "Working with a Realtor: ";
    $Body .= $Realtor;
    $Body .= "\n";
    $Body .= "How soon they are looking to buy or rent: ";
    $Body .= $When;
    $Body .= "\n";
    $Body .= "Selling their home: ";
    $Body .= $Selling;
    $Body .= "\n";

    function processform(){
    global $name, $email, $realtor, $when, $selling, $Body;

    $email_to1 = "shadedjg@hotma il.com"; // enter your email here
    $email_from1 = $mail;
    $email_to2 = $mail;
    $email_from2 = $email_to1;
    $email_subject = "Contact Form: ".stripslashes( $subject);
    $email_message = "Please find below a message submitted by '".stripslashes ($name);
    $email_message .="' on ".date("d/m/Y")." at ".date("H:i")." nn";
    $email_message .="--------- START OF SUBMITTED MESSAGE ---------nn";
    $email_message .= stripslashes($B ody);
    $email_message .="nn--------- END OF SUBMITTED MESSAGE ---------nn";

    $confirmation_s ubject = "Thank you for your message";
    $confirmation = "This is to confirm we have received your message....";

    // SEND EMAIL TO email_to2 - confirmation
    $headers = 'From: '.$email_from2. "rn" .
    'Reply-To: '.$email_from2. "rn" .
    'X-Mailer: PHP/' . phpversion();

    mail($email_to2 , $email_subject, $confirmation, $headers);

    // SEND EMAIL TO email_to1 - message to you!!
    $headers = 'From: '.$email_from1. "rn" .
    'Reply-To: '.$email_from1. "rn" .
    'X-Mailer: PHP/' . phpversion();

    mail($email_to1 , $email_subject, $email_message, $headers);

    echo "Thank You.";
    die();
    } // end processform()

    function showform() {
    ?>
    <STYLE type="text/css">
    div.row {
    clear:both;
    }
    div.row span.label {
    float: left;
    width: 60px;
    text-align: right;
    }
    div.row span.formw {
    float: right;
    width: 220px;
    text-align: left;
    }
    div.row span.left {
    float: left;
    text-align: left;
    font-weight: bold;
    color: #fff;
    width: 49%;
    }
    div.row span.right {
    float: right;
    text-align: right;
    font-weight: bold;
    color: #fff;
    width: 49%;
    }
    div.row span.submit{
    width:280px;
    text-align:center;
    }
    #form{
    width: 300px;
    height: 500px;
    background-color: #f6f6f6;
    border: 1px dotted #666;
    padding: 2px;
    margin: 0px auto;
    position: relative;
    }
    #confirmation{
    width: 300px;
    height:220px;
    background-color: #f6f6f6;
    border: 1px dotted #666;
    padding: 2px;
    margin: 0px auto;
    text-align: center;
    font-weight: bold;
    }
    </STYLE>
    <script type="text/javascript">
    <!--
    var http = createRequestOb ject();
    var areal = Math.random() + "";
    var real = areal.substring (2,6);

    function createRequestOb ject() {
    var xmlhttp;
    try { xmlhttp=new ActiveXObject(" Msxml2.XMLHTTP" ); }
    catch(e) {
    try { xmlhttp=new ActiveXObject(" Microsoft.XMLHT TP");}
    catch(f) { xmlhttp=null; }
    }
    if(!xmlhttp&&ty peof XMLHttpRequest! ="undefined" ) {
    xmlhttp=new XMLHttpRequest( );
    }
    return xmlhttp;
    }

    function sendRequest() {
    var rnd = Math.random();
    var name = escape(document .getElementById ("name").value) ;
    var email = escape(document .getElementById ("email").value );
    var realtor = escape(document .getElementById ("realtor").val ue);
    var when = escape(document .getElementById ("when").value) ;
    var selling = escape(document .getElementById ("selling").val ue);

    try{
    http.open('POST ', 'ajax_contact.p hp');
    http.setRequest Header('Content-Type', 'application/x-www-form-urlencoded');
    http.onreadysta techange = handleResponse;
    http.send('name ='+name+'&email ='+email+'&real tor='+realtor+' &when='+when+'& selling='+selli ng+'&rnd='+rnd) ;
    }
    catch(e){}
    finally{}
    }

    function check_values() {
    var valid = document.getEle mentById("valid ").value;
    if(real !== valid) {
    alert("Anti-Bot check failed.....nPle ase enter the 4 digits as they appear.");
    return false;
    }

    var name = document.getEle mentById("name" ).value;
    var email = document.getEle mentById("email ").value;
    var realtor = document.getEle mentById("realt or").value;
    var when = document.getEle mentById("when" ).value;
    var selling = document.getEle mentById("selli ng").value;
    if(trim(name) == "" ||
    trim(email) == "" ||
    trim(realtor) == "" ||
    trim(when) == "" ||
    trim(selling) == "") {
    alert("Please complete all fields");
    } else {
    if(isEmail(emai l)) {
    document.getEle mentById("submi t").disabled=tr ue;
    document.getEle mentById("submi t").value='Plea se Wait..';
    sendRequest();
    } else {
    alert("Email appears to be invalid.nPlease check.");
    document.getEle mentById("email ").focus();
    document.getEle mentById("email ").select() ;
    }
    }
    }

    function handleResponse( ) {
    try{
    if((http.readyS tate == 4)&&(http.statu s == 200)){
    var response = http.responseTe xt;
    document.getEle mentById("confi rmation").inner HTML = response;
    document.getEle mentById("confi rmation").style .display ="";
    document.getEle mentById("form" ).style.display = "none";
    }
    }
    catch(e){}
    finally{}
    }

    function isUndefined(a) {
    return typeof a == 'undefined';
    }

    function trim(a) {
    return a.replace(/^s*(S*(s+S+)*)s *$/, "$1");
    }

    function isEmail(a) {
    return (a.indexOf(".") > 0) && (a.indexOf("@") > 0);
    }

    function botCheckInfo() {
    alert("To prevent automatic programs (bots)nfrom submitting spam through this form,nwe have added a simple validationnchec k to the form. You must enter nthese 4 digits in the box provided innorder to submit the form.");
    }
    // -->
    </script>

    <?
    } // end showform()
    ?>
    <div id="form">
    <form>
    <div class="row"><sp an class="label">N ame:</span>
    <span class="formw">< input type="text" id="name" size="30" /></span></div>
    <div class="row"><sp an class="label">E mail:</span>
    <span class="formw">< input type="text" id="email" size="30" /></span></div>
    <div class="row"><sp an class="label">A re your currently working with a Realtor?:</span>
    <span class="formw">< select id="realtor">
    <option value="Yes">Yes </option>
    <option value="No">No</option>
    </select></span></div>
    <div class="row"><sp an class="label">H ow soon are you looking to buy, sell or rent?:</span>
    <span class="formw">< select id="when">
    <option value="Now">Now </option>
    <option value="Within a few months">Within a few months</option>
    <option value="Within 6 months">Within 6 months</option>
    <option value="Within a year">Within a year</option>
    <option value="Not sure">Not sure</option>
    </select></span></div>
    <div class="row"><sp an class="label">D o you have to sell your home?:</span>
    <span class="formw">< select id="selling">
    <option value="Yes">Yes </option>
    <option value="No">No</option>
    </select></span></div>
    <div class="row"><a href="javascrip t:botCheckInfo( )">Anti-bot check</a>. Enter Digits '<b><script language="javas cript">document .write(real)</script></b>' below:</div>
    <div class="row"><in put type="text" id="valid" size="15" /></div>
    <div class="row">&nb sp;</div>
    <div class="row">
    <input type="button" value="Submit" id="submit" onClick="return check_values(); "></div>
    <div id="confirmatio n" style="display: none"></span></div>
    </form>

    </div>[/CODE]
    Last edited by acoder; Dec 10 '07, 11:03 AM. Reason: Cleaned up!
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    What's the response from the server?

    Do you get any errors?

    Comment

    • colt28
      New Member
      • Dec 2007
      • 9

      #3
      Nope. No response. It does nothing.

      Comment

      • acoder
        Recognized Expert MVP
        • Nov 2006
        • 16032

        #4
        Can you get the PHP page working as expected without using Ajax?

        Comment

        • colt28
          New Member
          • Dec 2007
          • 9

          #5
          The page works fine up until the form is submitted. I need the form to submit and close the div. I was told to use Ajax because it's apparently the only way to keep the user on the same page.

          I would be fine with possibly having the form submit and open in a new window with confirmation. I don't care what happens once it's submitted as long as the div closes and disappears. Right now the form does nothing for some reason and the div stays there.

          Is there any way to have the form submit, close the div and open in a new window perhaps?

          Comment

          • acoder
            Recognized Expert MVP
            • Nov 2006
            • 16032

            #6
            I meant the PHP page that you're calling via Ajax, ajax_contact.ph p.

            It seems, though, that you're calling the same page. I would suggest that you create a new page which only deals with the response and returns a result.

            Comment

            • colt28
              New Member
              • Dec 2007
              • 9

              #7
              The script is designed to just be an include. I tested the original on another server and it worked so i'm guessing the server my client is on is a piece of crap. So I know the script works and i've done a ton of combing and going through it. I've got it to almost work. I know it's reading the form values correctly because the validation script works. And the form disappears when I hit submit, it's just not actually sending the email now for some reason. Somewhere along the lines in adding more variables it's screwed it up.

              Here's the javascript:
              Code:
              <script type="text/javascript">
              <!--
              var http = createRequestObject();
              var areal = Math.random() + "";
              var real = areal.substring(2,6);
              
              function createRequestObject() {
              	var xmlhttp;
              	try { xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); }
                catch(e) {
                  try { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
                  catch(f) { xmlhttp=null; }
                }
                if(!xmlhttp&&typeof XMLHttpRequest!="undefined") {
                	xmlhttp=new XMLHttpRequest();
                }
              	return  xmlhttp;
              }
              
              function sendRequest() {
              	var rnd = Math.random();
              	var name = escape(document.getElementById("name").value);
              	var email = escape(document.getElementById("email").value);
              	var realtor = escape(document.getElementById("realtor").value);
              	var when = escape(document.getElementById("when").value);
              	var selling = escape(document.getElementById("selling").value);
              
              	try{
                  http.open('POST',  'ajax_contact.php');
                  http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                  http.onreadystatechange = handleResponse;
              		http.send('name='+name+'&email='+email+'&realtor='+realtor+'&when='+when+'$selling='+selling+'&rnd='+rnd);
              	}
              	catch(e){}
              	finally{}
              }
              
              function check_values() {
              	var valid = document.getElementById("valid").value;
              	if(real !== valid) {
              		alert("Ant-Bot check failed.....nPlease enter the 4 digits as they appear.");
              		return false;
              	}
              
              	var name = document.getElementById("name").value;
              	var email = document.getElementById("email").value;
              	var realtor = document.getElementById("realtor").value;
              	var when = document.getElementById("when").value;
              	var selling = document.getElementById("selling").value;
              	if(trim(name) == "" ||
              		trim(email) == "" ||
              		trim(realtor) == "" ||
              		trim(when) == "" ||
              		trim(selling) == "") {
              			alert("Please complete all fields");
              	} else {
              		if(isEmail(email)) {
              			document.getElementById("submit").disabled=true;
              			document.getElementById("submit").value='Please Wait..';
              			sendRequest();
              		} else {
              			alert("Email appears to be invalid.nPlease check.");
              			document.getElementById("email").focus();
              			document.getElementById("email").select();
              		}
              	}
              }
              
              function handleResponse() {
              	try{
                  if((http.readyState == 4)&&(http.status == 200)){
                  	var response = http.responseText;
                    document.getElementById("confirmation").innerHTML = response;
                    document.getElementById("confirmation").style.display ="";
                    document.getElementById("form").style.display = "none";
              		}
                }
              	catch(e){}
              	finally{}
              }
              
              function isUndefined(a) {
                 return typeof a == 'undefined';
              }
              
              function trim(a) {
              	return a.replace(/^s*(S*(s+S+)*)s*$/, "$1");
              }
              
              function isEmail(a) {
                 return (a.indexOf(".") > 0) && (a.indexOf("@") > 0);
              }
              
              function botCheckInfo() {
              	alert("To prevent automatic programs (bots)nfrom submitting spam through this form,nwe have added a simple validationncheck to the form. You must enter nthese 4 digits in the box provided innorder to submit the form.");
              }
               // -->
               </script>
              I don't get it. It gets through all the validation, but for some reason it won't actually send the email. I'm so close I can taste it :oP

              The php:
              Code:
              <?
              if(!isset($rnd) || !isset($name) || !isset($email) || !isset($realtor) || !isset($when) || !isset($selling)) {
              	showform();
              } else {
              	processform();
              }
              
              function processform(){
              	global $name, $email, $realtor, $when, $selling;
              
              	$email_to1 = "shadedjg@hotmail.com"; // enter your email here
              	$email_from1 = $mail;
              	$email_to2 = $mail;
              	$email_from2 = $email_to1;
              	$email_subject = "Website Submission";
              	$email_message =" on ".date("d/m/Y")." at ".date("H:i")."<br><br>";
              	$email_message .= "Name:".stripslashes($name);
              	$email_message .="Using a Realtor".stripslashes($realtor)."<br>";
              	$email_message .="When buying, selling or renting:".stripslashes($when)."<br>";
              	$email_message .="Selling:".stripslashes($selling);
              
              	$confirmation_subject = "Thank you for your message";
              	$confirmation = "This is to confirm we have received your message....";
              
              	// SEND EMAIL TO email_to2 - confirmation
              	$headers = 'From: '.$email_from2."rn" .
                 'Reply-To: '.$email_from2."rn" .
                 'X-Mailer: PHP/' . phpversion();
              
              	mail($email_to2, $email_subject, $confirmation, $headers);
              
              	// SEND EMAIL TO email_to1 - message to you!!
              	$headers = 'From: '.$email_from1."rn" .
                 'Reply-To: '.$email_from1."rn" .
                 'X-Mailer: PHP/' . phpversion();
              
              	mail($email_to1, $email_subject, $email_message, $headers);
              
              	echo "Thank You.";
              	die();
              } // end processform()
              
              function showform() {
              ?>
              Any ideas?

              Comment

              • acoder
                Recognized Expert MVP
                • Nov 2006
                • 16032

                #8
                You're closing showForm() too early. It should include the form within it.

                Comment

                • colt28
                  New Member
                  • Dec 2007
                  • 9

                  #9
                  Normally I would look into your suggestion but that can't be it. No offense of course, because you know more than i do, but i didn't change any of the code except for the variables. I checked the original and it works fine so it can't be a problem like that or the original wouldn't even work to begin with. Or am i completely missing something??

                  Comment

                  • acoder
                    Recognized Expert MVP
                    • Nov 2006
                    • 16032

                    #10
                    Originally posted by colt28
                    Normally I would look into your suggestion but that can't be it. No offense of course, because you know more than i do, but i didn't change any of the code except for the variables. I checked the original and it works fine so it can't be a problem like that or the original wouldn't even work to begin with. Or am i completely missing something??
                    Should the form display when the form is processed?

                    In your original code, you check at the top whether to process the form or show the form. showForm() finishes on line 214 after which the actual form appears. This means that whether you're processing the form or showing the form, the form will display.

                    To eliminate all possibilities, test your application without Ajax on the server that it's going to be deployed on, so that you know that it's not a problem with the PHP.

                    Comment

                    • colt28
                      New Member
                      • Dec 2007
                      • 9

                      #11
                      I finally figured it out. It was ONE character. The line where the javasript sends the variables to the php portion had a '$' instead of '&' on one of them. Prime example of why i'm not a coder :oP

                      Thanks for all your help :o) Much appreciated.

                      Comment

                      • gits
                        Recognized Expert Moderator Expert
                        • May 2007
                        • 5390

                        #12
                        *lol* ... nope ... believe me ... such errors are common ... lasty i had such a problem at work ... a colleague searched for a bug and we did together ... it lasts us two hours to find out a mistyped check if (val1 = val2) as an assignment ... we overlooked it every time ... glad to hear you found the error ;)

                        kind regards

                        Comment

                        • acoder
                          Recognized Expert MVP
                          • Nov 2006
                          • 16032

                          #13
                          Originally posted by colt28
                          I finally figured it out. It was ONE character. The line where the javasript sends the variables to the php portion had a '$' instead of '&' on one of them.
                          In your code in post #1, there's no $, but it must've accidentally been added by the time you got to post #7.
                          Originally posted by colt28
                          Prime example of why i'm not a coder :oP

                          Thanks for all your help :o) Much appreciated.
                          As gits said, it doesn't mean you're not a coder. Glad you got it working and good luck with your project.

                          Comment

                          Working...