SitePoint Sponsor

User Tag List

Results 1 to 14 of 14

Hybrid View

  1. #1
    SitePoint Member
    Join Date
    Jul 2007
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Simply Javascript - Ajax contact_form not working page329

    I am having a lot of trouble with the Contact form AJAX seamless submission project in the Simply Javascript book by Kevin Yank and Cameron Adams Chapter 8.

    One of the main reasons I purchased the book was to find out more about AJAX and was pleased to find this generic form submission section that uses the Contact form as an example. I have been pulling my hair out trying to get this form to work and am not getting anywhere.

    The only changes to the form I am doing is changing the form action to action="form_mailer.cfm" my ColdFusion page which is simply inserting the form data into a database. The problem I am having is that I keep getting the "The server was unable to be contacted" javascript alert coming up.

    My form_mailer.cfm page is a really simple coldfusion insert page, code below.

    Code:
    <!--- Set default value for checkbox if not checked --->
    <cfparam name="form.contactNewsletter" default="No">
    <cfquery datasource="MyDB" name="FormInsert"> 
    insert into ContactForm(contactName, contactEmail, contactType, contactMessage, contactNewsletter, contactMethod)
    values ('#form.contactName#','#form.contactEmail#','#form.contactType#','#form.contactMessage#','#form.contactNewsletter#','#form.contactMethod#')
    </cfquery>
    I added the Content type header thinking this could be the problem but now it just submits the form as a normal form, no ajax!. It enters the data in the database table no problem, so I know my ColdFusion page is working fine.

    Code:
    requester.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    requester.open("POST", form.getAttribute("action"), true);
    requester.onreadystatechange = function()
    I have tried using both Firefox and IE version 6 and they both do the same things so it doesn't seem to be a browser issue. Using AJAX for seamless form submission is what I need to be able to do, so I'm very frustrated at not being able to get this to work!

    Any others having this problem? or suggestions for fixing would be appreciated.

  2. #2
    SitePoint Wizard gRoberts's Avatar
    Join Date
    Oct 2004
    Location
    Birtley, UK
    Posts
    2,439
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Can we see the full Ajax code or an example of the page your trying to use?

    As "The server was unable to be contacted" indicates the page your trying to access doesn't exist, have you even set what page to access using AJAX?


  3. #3
    SitePoint Member
    Join Date
    Jul 2007
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well it would be breaching copyright to post the js code from the book.

    The whole point of this Contact form is that it is written as a generic ajax form handler, the only part you have to do is the processing page which can do whatever you want, email, insert into database etc my page simply enters the form data into a database table (see page code above).

    The ajax script gets the action page from the form.getAttribute("action"), part of the script you don't need to hard code the processing page into the ajax script. The fact that the form when submitted without ajax enters the data into the database surely means that the page exists?

    My only thoughts now are that maybe I need to use a looping insert statement in my ColdFusion processing page instead of the standard one I am using for regular form inserts.

    The example in the book uses core.js, contact_form.js and the contact_form.html all you are supposed to do is build a process page.

    Has anyone else got this Contact Form to work?

    Cheers

  4. #4
    SitePoint Wizard gRoberts's Avatar
    Join Date
    Oct 2004
    Location
    Birtley, UK
    Posts
    2,439
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    So you can guarentee that getAttribute('action') is always returning the correct URL? A form may deal with the URL differently to AJAX.

    Could be worth alerting the action that is being used by the ajax code before using it, just to see whats happening.


  5. #5
    SitePoint Member
    Join Date
    Jul 2007
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    php page works but not cf page

    Ok it works with the form_mailer.php code page. This is all that is in the php page.

    Code:
    <?php
    header("Content-type: text/html");
    ?>
    which I realise is just a mock php page that in the real world would send off an email. So I changed my coldfusion page to send an email instead.

    Here is my form_mailer.cfm page

    Code:
    <cfmail to="myname@somewhere.com.au"
    		from="#form.contactEmail#"
    		subject="Testing AJAX Form" 
    		server="127.0.0.1">
    Name: #form.contactName#
    Email: #form.contactEmail#
    </cfmail>
    Pretty straight forward cfm page to send the users name and email address, but now it gives me "the server cannot be contacted' message again.

    The weird thing is that if I take all the code out of my cfm page and it's just totally blank, it works! Well it doesn't do anything of course but it displays the successfully sent message! using ajax.

    I must be missing something here.

  6. #6
    SitePoint Author Kevin Yank's Avatar
    Join Date
    Apr 2000
    Location
    Melbourne, Australia
    Posts
    2,571
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Here's the relevant JavaScript code:
    Code:
          requester.onreadystatechange = function()
          {
            clearTimeout(form._timer);
            
            if (requester.readyState == 4)
            {
              if (requester.status == 200 || requester.status == 304)
              {
                ContactForm.writeSuccess(form);
              }
              else
              {
                ContactForm.writeError("The server was unable to be contacted.");
              }
            }
          };
    You'll note that the error message you're seeing is displayed when the Ajax request produces an HTTP response code other than 200 or 304. Your first step in debugging this problem, then, should be to find out what HTTP response code is being returned.

    The easiest way to find this out is to use a JavaScript debugger like Firebug (as described later in the book). Alternatively, you can just insert an alert function call that displays the status code in a message box:
    Code:
          requester.onreadystatechange = function()
          {
            clearTimeout(form._timer);
            
            if (requester.readyState == 4)
            {
              if (requester.status == 200 || requester.status == 304)
              {
                ContactForm.writeSuccess(form);
              }
              else
              {
                alert(requester.status);
                ContactForm.writeError("The server was unable to be contacted.");
              }
            }
          };
    Kevin Yank
    CTO, sitepoint.com
    I wrote: Simply JavaScript | BYO PHP/MySQL | Tech Times | Editize
    Baby’s got back—a hard back, that is: The Ultimate CSS Reference

  7. #7
    SitePoint Member
    Join Date
    Jul 2007
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Kevin,

    Many thanks for trying to help me get this sorted!

    The response code is 500 which I think is internal server error.

    I have been trying out a lot of ajax recently and I don't have a problem with any of it running with my local ColdFusion server, so I am stumped as to what this error is all about.

    Just so you know what I am doing here is the form page.

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" lang="en-US">
      <head>
        <title>Contact Form</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    
        <link rel="stylesheet" href="plain.css" type="text/css" />
        <link rel="stylesheet" href="contact_form.css" type="text/css" />
        <!--[if lte IE 7]>
            <link rel="stylesheet" href="contact_form.ie.css" type="text/css" />
        <![endif]-->
        <script type="text/javascript" src="core.js"></script>
        <script type="text/javascript" src="contact_form.js"></script>
      </head>
      <body>
        <h1>Contact Form</h1>
        <form id="contactForm" action="form_mailer.cfm" method="POST">
          <fieldset>
            <legend>
              <span>Contact Form</span>
            </legend>
            <ol>
              <li>
                <label for="contactName">
                  Name
                </label>
                <input id="contactName" name="contactName" type="text" />
              </li>
              <li>
                <label for="contactEmail">
                  Email Address
                </label>
                <input id="contactEmail" name="contactEmail" type="text" />
              </li>
              <li>
                <label for="contactType">
                  Message Type
                </label>
                <select id="contactType" name="contactType">
                  <option value="1">Enquiry</option>
                  <option value="2">Spam</option>
                  <option value="3">Wedding proposal</option>
                </select>
              </li>
              <li>
                <label for="contactMessage">
                  Message
                </label>
                <textarea id="contactMessage" name="contactMessage" cols="25" rows="5"></textarea>
              </li>
              <li class="checkbox">
                <input id="contactNewsletter" name="contactNewsletter" type="checkbox" value="1" />
                <label for="contactNewsletter">
                  I'd like to receive your hourly newsletter
                </label>
              </li>
              <li>
                <fieldset>
                  <legend>
                    Respond by
                  </legend>
                  <ol>
                    <li>
                      <input id="contactMethod" name="contactMethod" type="radio" value="1" />
                      <label for="contactMethod">
                        Email
                      </label>
                    </li>
                    <li>
                      <input id="contactMethod" name="contactMethod" type="radio" value="2" />
                      <label for="contactMethod">
                        Pony messenger
                      </label>
                    </li>
                  </ol>
                </fieldset>
              </li>
            </ol>
          </fieldset>
          <fieldset class="submit">
           <input type="submit" value="Submit" />
          </fieldset>
        </form>
      </body>
    </html>

    and here is my form_mailer.cfm page

    Code:
    <cfmail to="myEmail@somewhere.com.au"
    from="#contactEmail#"
    subject="Testing AJAX Form" 
    server="127.0.0.1">
    Name: #contactName#
    Email: #contactEmail#
    Contact Type: #contactType#
    Message: #contactMessage#
    Newsletter:  #contactNewsletter#
    Method:   #contactMethod#
    </cfmail>

    It's probably something simple for sure.
    Cheers

  8. #8
    SitePoint Author Kevin Yank's Avatar
    Join Date
    Apr 2000
    Location
    Melbourne, Australia
    Posts
    2,571
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Hmm yes, the 500 status code definitely indicates that your mailer script is generating an error of some kind. My next stop would be your web server's logs, where details of the 500 error would be logged.
    Kevin Yank
    CTO, sitepoint.com
    I wrote: Simply JavaScript | BYO PHP/MySQL | Tech Times | Editize
    Baby’s got back—a hard back, that is: The Ultimate CSS Reference

  9. #9
    SitePoint Member
    Join Date
    Jul 2007
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ok, were starting to get somewhere with this.

    I checked the logs here is the error message.

    coldfusion.runtime.UndefinedVariableException: Variable CONTACTEMAIL is undefined.

    So I then set default parameters for each of the form variables being sent.

    Code:
    <cfparam name="contactName" default="Onimok">
    <cfparam name="contactEmail" default="someone@somewhere.com.au">
    <cfparam name="contactType" default="1">
    <cfparam name="contactMessage" default="Blah Blah">
    <cfparam name="contactNewsletter" default="Yes">
    <cfparam name="contactMethod" default="phone">
    
    <cfmail to="myEmail@somewhere.com.au"
    from="#contactEmail#"
    subject="Testing AJAX Form" 
    server="127.0.0.1">
    Name: #contactName#
    Email: #contactEmail#
    Contact Type: #contactType#
    Message: #contactMessage#
    Newsletter:  #contactNewsletter#
    Method:   #contactMethod#
    </cfmail>
    So now it works and sends the email, but only with the default values. This would indicate that the form variables aren't being sent to my form_mailer.cfm page at all.

    I went through each of the form elements separately and none of them are being sent to my processing page.

    So the form is sent via ajax and I get the sucessfully submitted message, however the email that is sent is only using my default values not the ones form the actual form.

    Any ideas on where we go from here?

    Thanks again for your help.

  10. #10
    SitePoint Author Kevin Yank's Avatar
    Join Date
    Apr 2000
    Location
    Melbourne, Australia
    Posts
    2,571
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Hmm... The first place I'd look is the second-last line of the submitListener method in your JavaScript:
    Code:
    requester.send(parameters);
    This is the line that sends the contents of the form to the server. Try inserting an alert immediately before this line that displays the value of the parameters variable, to see if the contents of your form are indeed being collected correctly.

    If they are, the next step would be to examine the Ajax request in Firebug's Console tab (Options > Show XMLHttpRequests) to confirm that the form values are being sent with the request.
    Kevin Yank
    CTO, sitepoint.com
    I wrote: Simply JavaScript | BYO PHP/MySQL | Tech Times | Editize
    Baby’s got back—a hard back, that is: The Ultimate CSS Reference

  11. #11
    SitePoint Member
    Join Date
    Jul 2007
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hmm... Curiouser and curiouser...

    Well the variables are showing up in the alert!

    Code:
    submitby=ajax&contactMessage=Testing!&contactType=Enquiry&contactName=James%20Bond&contactEmail=jbond%40hotmail.com&contactNewsletter=Yes&contactMethod=email
    and also in Firebugs console at the same breakpoint. So I'm danged if I know why I'm still getting the error that they are undefined on the processing page. The strange thing is that when the script timed out and I clicked the blue arrow in firebug to continue it sends the form as a normal form to my cfm page and it works and sends the email!!

    I think the only thing left to do is modify the script to display the response text in a div element for example and build a php page to see if the variables are being sent. Should we possibly change it to a GET and send a string with the ? appended to the url and the name value pairs.

    Any other thoughts?

    I have actually found a similar ajax form that I have working at the moment.

    http://www.captain.at/howto-ajax-form-post-get.php

    I've been trying to compare the two to find out what the secret ingredients are but no luck so far.

  12. #12
    SitePoint Author Kevin Yank's Avatar
    Join Date
    Apr 2000
    Location
    Melbourne, Australia
    Posts
    2,571
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Have you checked in Firebug that the variables are actually being sent in the Ajax request? You can see this in the Console tab when the "Show XMLHttpRequests" option is enabled.

    Assuming the variables are being sent with the request, your debugging efforts should now move to the ColdFusion side of things. Unfortunately, I don't know ColdFusion well enough to assist here. Is there some way to output the full details of the HTTP request being processed in ColdFusion?

    I'd recommend against sending this type of form submission as a GET request, but it might be worth trying as a debugging step.
    Kevin Yank
    CTO, sitepoint.com
    I wrote: Simply JavaScript | BYO PHP/MySQL | Tech Times | Editize
    Baby’s got back—a hard back, that is: The Ultimate CSS Reference

  13. #13
    SitePoint Member
    Join Date
    Jul 2007
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Talking Problem Solved!

    Ok it now works! All it needed was this line in the contact_form.js

    Code:
    requester.open("POST", form.getAttribute("action"), true);
    requester.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    The answer was on page 311 all the time!

    Looks like it isn't just for Opera that it's needed.

    Thanks for all your help with this Kevin, appreciated.

    Cheers

    John

  14. #14
    SitePoint Member
    Join Date
    Jul 2007
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Clarification of problem.

    Just to clarify the solution to my problem.

    It was actually a combination of things. I realised I had already tried adding the requester.setRequestHeader in my first attempts to fix this. The reason it didn't work then was that it needed to go underneath the requester.open line not above it. If it is above it, it will just submit the form as a normal form not with ajax.

    For other coldFusion people trying this you need to add a default value for the checkbox if it wasn't ticked on the form, and don't add the form scope to your coldFusion variables in the processing page.

    Cheers!

    Code:
    <cfparam name="contactNewsletter" default="No">
    <cfmail to="someone@somewhere.com"
    from="#contactEmail#"
    subject="Testing AJAX Form" 
    server="127.0.0.1">
    Name: #contactName#
    Email: #contactEmail#
    Contact Type: #contactType#
    Message: #contactMessage#
    Newsletter:  #contactNewsletter#
    Method:   #contactMethod#
    </cfmail>


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •