Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

General Discussion

Abdi Ahmed
PLUS
Abdi Ahmed
Courses Plus Student 1,667 Points

Getting to work a script that makes Ajax call using PHP and JQuery

Hi all,

I have been struggling to get a script to work using PHP and Jquery. I want to collect the form input, do the error checking and once the errors are cleared pass the form element to PHP file and send an email to client:

Here are file that I have:

HTML

<?php include 'header.php'; ?>

<div class="row"><!-- Row start -->
<!--   Test -->
    <div class="col-md-9" role="main">
    <div class="bs-docs-section">
     <h1 id="d">Register here to communicate with your Customers</h1>

        <p>Fill out the form below to complete the registration. </p>
         <p>          </p>

     <form role="form" method="POST" action="" class="form-horizontal" id="RegisterForm">

           <div class="form-group">
              <label for="firstname" class="col-sm-3 control-label">First Name </label>

              <div class="col-sm-6"> 
                <input type="text" class="form-control" name="name" id="name" placeholder=" ">
                 <span class="help-block" style="display: none;">Please enter your first name.</span>
             </div>
           </div><!-- End control group -->

           <div class="form-group">
             <label for="lastname" class="col-sm-3 control-label">Last name  </label>
               <div class="col-sm-6">
                <input type="text" class="form-control" name="lname" id="lname" placeholder=" ">
                 <span class="help-block" style="display: none;">Please enter your last name.</span>
               </div>
           </div><!-- End control group -->




           <div class="form-group">
             <label for="email" class="col-sm-3 control-label">Email </label>
               <div class="col-sm-6">
                <input type="text" class="form-control" name="email" id="email" placeholder=" "> 
                <span class="help-block" style="display: none;">Please enter a valid e-mail address.</span>
               </div>
           </div><!-- End control group -->

           <div class="form-group">
             <label for="business" class="col-sm-3 control-label">Business Name</label>
               <div class="col-sm-6">
                <input type="text" class="form-control" name="businessName" id="businessName" placeholder=" ">
                <span class="help-block" style="display: none;">Please type your business name.</span>
               </div>
           </div><!-- End control group -->



           <!-- Choose option is added  -->
               <div class="form-group">
                <label for="businessType" class="col-sm-3 control-label">Business Name</label>
                <div class="col-sm-6">
                 <select class="form-control" name="BusinessType" id="BusinessType">
                   <option value="">Please choose company type</option>
                   <option value="fdc">Family Day Care</option>
                   <option value="remittance">Remittance Service</option>
                   <option value="individual">Individual user</option>
                 </select>
                   <span class="help-block" style="display: none;">Please choose a valid option.</span>
                 </div>
                </div>


           <div class="form-group">
             <label for="password" class="col-sm-3 control-label">Choose Password </label>
               <div class="col-sm-6">
                <input type="text" class="form-control" name="password1" id="password1" placeholder=" ">
                <span id="pass1info" class="help-block" style="display: none;">Please choose password.</span>
               </div>      
           </div><!-- End control group -->


           <div class="form-group">
             <label for="confirmpass" class="col-sm-3 control-label">Confirm Password </label>
               <div class="col-sm-6">
                <input type="text" class="form-control" name="password2" id="password2" placeholder=" ">
                 <span id="pass2info" class="help-block" style="display: none;">Confirm your password.</span>
               </div>         
           </div><!-- End control group -->


             <img style="margin-left:220px;" id="captcha" src="library/vender/securimage/securimage_show.php" alt="CAPTCHA Image" />
              <a href="#" onclick="document.getElementById('captcha').src = 'library/vender/securimage/securimage_show.php?' + Math.random(); return false" class="btn btn-info btn-sm">Show a Different Image</a><br/>

              <div class="form-group" style="margin-top: 10px;">
               <label for="captcha_code" class="col-sm-3 control-label">Please enter a the security code </label>
                <div class="col-sm-6">             
                  <input type="text" class="form-control" name="captcha_code" id="captcha_code" placeholder="For security, please enter the code displayed in the box." />
                 <span class="help-block" style="display: none;">Please enter the code displayed on the image.</span>

               </div>

              </div><!-- End control group -->


            <div class="col-sm-offset-3 col-sm-9"> 
               <button type="submit"  id="RegisterSubmit" class="btn btn-primary">Submit Registration</button>
            </div> 

         </form><!-- End Form -->

        </div>
    </div>
<!--   Test -->

      <div class="col-md-3">
      <h1 id="download"></h1> <!-- Dummy heading used for spacing -->
          <div class="bs-sidebar hidden-print" role="complementary">
            <div class="panel panel-default">
                <div class="panel-heading">
                  <h3 class="panel-title">Panel title</h3>
                </div>
              <div class="panel-body">
                 Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequa
              </div>
          </div>
          </div>
 </div><!-- Finsish col-md-3 -->

 <?php include 'footer.php'; ?>

Contact-form.js

$(document).ready(function() {
  $("#RegisterSubmit").click(function() {
    //clear any errors
    contactForm.clearErrors();

    //do a little client-side validation -- check that each field has a value and e-mail field is in proper format

    //var pass1-info = $("#pass1-info");
    var pass2info = $("#pass2-info") ;

    var $PassWord1 = $("#password1").val();
    var $PassWord2 = $("#password2").val();


    var hasErrors = false;
    $('#RegisterForm input, select').each(function() {
      if (!$(this).val()) {
        hasErrors = true;
        contactForm.addError($(this));
      }
    });
    var $email = $('#email');
    if (!contactForm.isValidEmail($email.val())) {
      hasErrors = true;
      contactForm.addError($email);
    }

    if ($("#BusinessType option:selected").val() == ''); {
        hasErrors = true;
        contactForm.addError($(this));

    }

    if ($PassWord1 !== $PassWord2){
        //pass2info.text("There is password mismatch!");
        hasErrors = true;
        contactForm.addError($("#password2"));

    }


    //if there are any errors return without sending e-mail
    if (hasErrors) {
      return false;
    }

    var formValues = $("#RegisterForm").serialize();
    alert(formValues);

    //send the feedback e-mail
    $.ajax({
      type: "POST",
      url: "library/sendmail.php",
      data: formValues,

      success: function(data)
      {
        contactForm.addAjaxMessage(data.message, false);
        //get new Captcha on success
        $('#captcha').attr('src', 'library/vender/securimage/securimage_show.php?' + Math.random());
      },
      error: function(response)
      {
        contactForm.addAjaxMessage(response.responseJSON.message, true);
      }
   });
    return false;
  }); 
});

//namespace as not to pollute global namespace
var contactForm = {
  isValidEmail: function (email) {
    var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return regex.test(email);
  },
  clearErrors: function () {
    $('#emailAlert').remove();
    $('#RegisterForm .help-block').hide();
    $('#RegisterForm .form-group').removeClass('has-error');
    $('#RegisterForm .col-sm-6').removeClass('has-error');

  },
  addError: function ($input) {

    $input.siblings('.help-block').show();
    //$input.parent('.form-group').addClass('has-error');
    $input.parent().addClass('has-error');



  },

  addAjaxMessage: function(msg, isError) {
    $("#RegisterSubmit").after('<div id="emailAlert" class="alert alert-' 
                                          + (isError ? 'danger' : 'success') 
                                          + '" style="margin-top: 5px;">' 
                                          + $('<div/>').text(msg).html() 
                                          + '</div>');
  }
};

sendmail.php

<?php
  //start a session -- needed for Securimage Captcha check
  session_start();

  //add you e-mail address here
  define("MY_EMAIL", "a_abdi406@yahoo.com");

  /**
   * Sets error header and json error message response.
   *
   * @param  String $messsage error message of response
   * @return void
   */
  function errorResponse ($messsage) {
    header('HTTP/1.1 500 Internal Server Error');
    die(json_encode(array('message' => $messsage)));
  }

  /**
   * Return a formatted message body of the form:
   * Name: <name of submitter>
   * Comment: <message/comment submitted by user>
   *
   * @param String $name     name of submitter
   * @param String $messsage message/comment submitted
   */

  //function setMessageBody ($name,  $lastName, $businessName,$businessType,$passwWord1, $message)

  function setMessageBody ($name, $lastName, $businessName, $businessType, $passwWord1) {
    $message_body = "Thanks for registering, your registeration details are the following" ."\n\n";
    $message_body = "Name: " . $name."\n\n";
    $message_body = "Last Name: " . $lastName."\n\n";
    $message_body = "Business Name: " .$businessName."\n\n";
    $message_body = "Business Type: " .$businessType."\n\n";
    $message_body = "Your Password: " .$passWord1."\n\n";
    //$message_body .= "Comment:\n" . nl2br($message);
    return $message_body;
  }

  print_r($_POST);

  $name     = $_POST['name']; 
  $lastName = $_POST['lname']; 
  $email    = $_POST['email']; 
  $businessName = $_POST['businessName']; 
  $businessType = $_POST['BusinessType']; 
  $passWord1    = $_POST['password1']; 
  $passWord2    = $_POST['password2']; 




  header('Content-type: application/json');
  //do some simple validation. this should have been validated on the client-side also
  //if (empty($email) || empty($message)) {

 if (empty($email)) {
    //errorResponse('Email or message is empty.');
    errorResponse('Email or other important information is missing.');
  }

  //do Captcha check, make sure the submitter is not a robot:)...
  include_once './vender/securimage/securimage.php';
  $securimage = new Securimage();
  if (!$securimage->check($_POST['captcha_code'])) {
    errorResponse('Invalid Security Code');
  }

  //try to send the message
  if(mail(MY_EMAIL, "Registration Form Results", setMessageBody($name, $lastName, $businessName, $businessType, $passWord1), "From: $email")) {
    echo json_encode(array('message' => 'Your message was successfully submitted.'));
  } else {
    header('HTTP/1.1 500 Internal Server Error');
    echo json_encode(array('message' => 'Unexpected error while attempting to send e-mail.'));
  }
?>

2 Answers

Richard Duncan
Richard Duncan
5,568 Points

What aspect have you been struggling with? You might be better posting a specific question relating to one aspect of the problem on a resource like http://stackoverflow.com.

If you have a specific aspect of the code you are struggling with I would be happy to take a look here but I don't think really this forum is the place for posting entire project files and expecting others to debug it for you.

Abdi Ahmed
PLUS
Abdi Ahmed
Courses Plus Student 1,667 Points

Thanks for offering help I have posted some instruction on stackoverflow and here is the link: https://stackoverflow.com/questions/23043491/program-with-php-and-jquery-making-ajax-call

see if you can help me, I am stuck..