使用PHP和JQuery编写Ajax调用程序

时间:2014-04-13 13:43:32

标签: ajax

我有点失去了程序,它确实形成处理,然后进行ajax调用,向用户发送电子邮件进行注册确认,它进行错误检查但是当你填写所有表单元素并点击提交按钮时没有去任何地方,预期的结果应该发送电子邮件并在提交按钮后添加消息。

文件:

HTML

<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> 

Javascript文件:contact-frm.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>');
  }
};

PHP文件:sendemail.php

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

  //add you e-mail address here
  define("MY_EMAIL", "1234406@gmail.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.'));
  }
?>

提前感谢您的帮助

1 个答案:

答案 0 :(得分:1)

我能找到的唯一错误是

if ($("#BusinessType option:selected").val() == ''); {

删除;,以便代码看起来像这样

if ($("#BusinessType option:selected").val() == '') {

并且代码现在完美运行..