Hi,

I am new with jQuery. I copied an open source code for sending a contact us form using jQuery. You can see the form at Website at the bottom right side yellow box.
The input fields are as follows: Name, Email, Tel, Comments.

This is my JS file the validates the form and sends to PHP file.

1. $(document).ready(function() {
          
          //if submit button is clicked
          $('#send_form').click(function () {        
              
              function validEmail(str) {
                  return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
              }

              //Get the data from all the fields
              var name = $('input[name=contact_name]');
              var email = $('input[name=contact_email]');
              var phone = $('input[name=contact_tel]');
              var comment = $('textarea[name=contact_message]');

              //Simple validation to make sure user entered something
              //If error found, add hightlight class to the text field
              if (name.val()=='') {
                  name.addClass('hightlight');
                  return false;
              } else name.removeClass('hightlight');
              
              if ((email.val()=='') || (email.val().indexOf("@")==-1) || (email.val().indexOf(".")==-1)) {
                  email.addClass('hightlight');
                  return false;
              } else email.removeClass('hightlight');

              if (phone.val()=='') {
                  phone.addClass('hightlight');
                  return false;
              } else phone.removeClass('hightlight');
              
              if (comment.val()=='') {
                  comment.addClass('hightlight');
                  return false;
              } else comment.removeClass('hightlight');
              
              //organize the data properly
              var data = 'name=' + name.val() + '&email=' + email.val() + '&phone=' + phone.val() + '&comment='  + encodeURIComponent(comment.val());

              //disabled all the text fields
              $('.text').attr('disabled','true');
              
              //show the loading sign
              $('.loading').show();
              
              //start the ajax
              $.ajax({
                  //this is the php file that processes the data and send mail
                  url: "/includes/jquery/process_form.php",    
                  
                  //GET method is used
                  type: "POST",

                  //pass the data            
                  data: data,        
                  
                  //Do not cache the page
                  cache: false,
                  //success
                  success: function (html) {                
                      //if process_form.php returned 1/true (send mail success)
                      if (html==1) {                    
                          //hide the form
                          $('#contact_form').fadeOut('slow');                    
                          
                          //show the success message
                          $('#contact_done').fadeIn('slow');
                          
                      //if process_form.php returned 0/false (send mail failed)
                      } else {
                          alert('111Sorry, unexpected error. Please try again later.');                
                      }
                  }        
              });
              
              //cancel the submit button default behaviours
              return false;
          });    
      });

This is my PHP form that handles the form itself:

1. <?php
      require("../phpmailer/class.phpmailer.php"); //Change this to the path to the phpmailer class as stipulated by Brinkster
      function mymailer ($useremail=1, $subject, $message, $useremail_bcc=1) {         
          $mail = new PHPMailer();
          $mail->IsSMTP();                                      // set mailer to use SMTP
          $mail->Host = "localhost";  // change this to Brinkster host
          $mail->SMTPAuth = true;     // turn on SMTP authentication
          $mail->Username = "admin@orchot-hagilboa.com";  // SMTP username
          $mail->Password = "xxxxx"; // SMTP password
          $mail->CharSet = 'utf-8';    //for hebrew only
          
          $mail->From = "admin@orchot-hagilboa.com";
          $mail->FromName = "Orchot Hagilboa";
          if($useremail == 1){
              $mail->AddAddress('info@orchot-hagilboa.com');
          } else {
              $mail->AddAddress($useremail);
          }        
          if($useremail_bcc != 1){    //send emails to multiple address
              foreach(array_keys($useremail_bcc) as $name) {    // now loop through the combined results get NAME & EMAIL
                  foreach($useremail_bcc[$name] as $email) {
                      #echo $name.' - '.$email.'<br/>';
                      $mail->AddBCC($email);
                  }
              }
          }            
          
          $mail->IsHTML(true);
          $mail->Subject = $subject;
          $mail->Body    = $message;
                  
          if(!@$mail->Send()) {
             echo "Message could not be sent. <p>";
             echo "Mailer Error: " . $mail->ErrorInfo;
             exit;
          }
      }

      //Retrieve form data.
      //GET - user submitted data using AJAX
      //POST - in case user does not support javascript, we'll use POST instead
      $name = ($_POST['name']) ? $_POST['name'] : $_POST['name'];
      $email = ($_POST['email']) ?$_POST['email'] : $_POST['email'];
      $phone = ($_POST['phone']) ?$_POST['phone'] : $_POST['phone'];
      $comment = ($_POST['comment']) ?$_POST['comment'] : $_POST['comment'];

      //flag to indicate which method it uses. If POST set it to 1
      if ($_POST) $post=1;

      //Simple server side validation for POST data, of course,
      //you should validate the email
      if (!$name) $errors[count($errors)] = 'Please enter your name.';
      if (!$email) $errors[count($errors)] = 'Please enter your email.';
      //if (!$phone) $errors[count($errors)] = 'Please enter your phone.';
      if (!$comment) $errors[count($errors)] = 'Please enter your comment.';

      //if the errors array is empty, send the mail
      if (!$errors) {

          //recipient - change this to your name and email
          $from = $name . ' <' . $email . '>';
          
          //subject and the html message
          $subject = 'צור קשר מ'.$name;    
          $message = '
          <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
          <html xmlns="http://www.w3.org/1999/xhtml">
          <head></head>
          <body>
          <table>
              <tr><td>שם</td><td>' . $name . '</td></tr>
              <tr><td>מייל</td><td>' . $email . '</td></tr>
              <tr><td>טל</td><td>' . $phone . '</td></tr>
              <tr><td>הודעה</td><td>' . nl2br($comment) . '</td></tr>
          </table>
          </body>
          </html>';

          //send the mail
          $result = mymailer($from, $subject, $message);
          
          if ($result) return 1;
          else return 0;

          //if POST was used, display the message straight away
          if ($_POST) {
              if ($result) echo 'Thank you! We have received your message.';
              else echo '222Sorry, unexpected error. Please try again later';
              
          //else if GET was used, return the boolean value so that
          //ajax script can react accordingly
          //1 means success, 0 means failed
          } else {
              echo $result;    
          }

      //if the errors array has values
      } else {
          //display the errors message
          for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br/>';
          echo '<a href="form.php">Back</a>';
          exit;
      }
      ?>

I don't understand why it is not working. It is not sending me an email.

thanks

The probelm could be something to do with

//GET - user submitted data using AJAX
      //POST - in case user does not support javascript, we'll use POST instead

which is followed by a block that handles $_POST but not $_GET. Therefore if your web page submits via GET method, then the php will fail.

I suggest you split the problem down the middle.

First test the server-side code (php/emailer) with hard coded values for $from , $subject , and $message .

When you get the emails to come through successfully, then address the client-side and all the $_POST/$_GET handling in php.

Airshow

in the .php file where i process the form, i changed:

$result = mymailer($from, $subject, $message);

to:

$result = mymailer('meytal@dachooch.com', 'my subject', 'my message');

i don't receive any emails. i still get this alert:
"111Sorry, unexpected error. Please try again later."
which is located in the .JS file.

I am not sure what im doing wrong.

update...

I changed mymailer() to:

$result = mail($from,$subject,$message);

and that did send me an email.
BUT, i still get the error "111Sorry, unexpected error. Please try again later."

why?

If you are getting an error message generated or even just handled by javascript, then you must still be going via your front end to call the php/mailer. You haven't split the problem in half yet.

Personally, I would call the php page directly, bypassing any javascript, and simply echo variables as necessary to gain confidence that the server-side is working properly. You will probably want to make a hack variant of your php file so as not to destroy the original.

Airshow

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.