3

Following is the HTML code for a form and further it is a php code for receiving the data to a desired email address. On submitting it is redirecting to the php code rather than sending the mail. Thanks in advance.

     <!doctype html>
                <html>
                <head>
                <meta charset="utf-8">
                <title>HTML Form</title>
                <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
            <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
                <script>
                  $(document).ready(function () {
                  $("#htmlform").submit(function (e) {
                  var url = "html_form_send.php"; // the script where you handle the form input.
                  $.ajax({type: "POST",
                   url: url,
                   data: $(this).serialize(), // serializes the form's elements.
                      success: function (data) {
                          alert(data); // show response from the php script.
                      }});
                  e.preventDefault(); // avoid to execute the actual submit of the form
                    });
                    });
              </script>
                </head>
                <form name="htmlform" id="htmlform" method="post" action="html_form_send.php">
                <table width="450px">
                  <tr>
                 <td valign="top">
                  <label for="first_name">First Name *</label>
                 </td>
                 <td valign="top">
                  <input  type="text" name="first_name" maxlength="50" size="30">
                 </td>
                </tr>

                <tr>
                 <td valign="top">
                  <label for="last_name">Last Name *</label>
                 </td>
                 <td valign="top">
                  <input  type="text" name="last_name" maxlength="50" size="30">
                 </td>
                </tr>
                <tr>
                 <td valign="top">
                  <label for="email">Email Address *</label>
                 </td>
                 <td valign="top">
                  <input  type="text" name="email" maxlength="80" size="30">
                 </td>

                </tr>
                <tr>
                 <td valign="top">
                  <label for="telephone">Telephone Number</label>
                 </td>
                 <td valign="top">
                  <input  type="text" name="telephone" maxlength="30" size="30">
                 </td>
                </tr>
                <tr>
                 <td valign="top">
                  <label for="comments">Comments *</label>
                 </td>
                 <td valign="top">
                  <textarea  name="comments" maxlength="1000" cols="25" rows="6"></textarea>
                 </td>

                </tr>
                <tr>
                 <td colspan="2" style="text-align:center">
                  **<input class="Submit" type="submit" name="Submit" value="Submit"/>**
                  </td>
                </tr>
                </table>
                </form> 

                </body>
                </html>

PHP code

           <?php
        if ( isset( $_POST['first_name'] ) ) { // <<<< Changes i have made

          $email_to = "Name@gmail.com"; // <<<<<<< This is temporary. 


                $email_subject = "website html form submissions";


                function died($error) {
                    // your error code can go here
                    echo "We are very sorry, but there were error(s) found with the form you submitted. ";
                    echo "These errors appear below.<br /><br />";
                    echo $error."<br /><br />";
                    echo "Please go back and fix these errors.<br /><br />";
                    die();
                }

                // validation expected data exists
                if(!isset($_POST['first_name']) ||
                    !isset($_POST['last_name']) ||
                    !isset($_POST['email']) ||
                    !isset($_POST['telephone']) ||
                    !isset($_POST['comments'])) {
                    died('We are sorry, but there appears to be a problem with the form you submitted.');       
                }

                $first_name = $_POST['first_name']; // required
                $last_name = $_POST['last_name']; // required
                $email_from = $_POST['email']; // required
                $telephone = $_POST['telephone']; // not required
                $comments = $_POST['comments']; // required

                $error_message = "";
                $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
              if(!preg_match($email_exp,$email_from)) {
                $error_message .= 'The Email Address you entered does not appear to be valid.<br />';
              }
                $string_exp = "/^[A-Za-z .'-]+$/";
              if(!preg_match($string_exp,$first_name)) {
                $error_message .= 'The First Name you entered does not appear to be valid.<br />';
              }
              if(!preg_match($string_exp,$last_name)) {
                $error_message .= 'The Last Name you entered does not appear to be valid.<br />';
              }
              if(strlen($comments) < 2) {
                $error_message .= 'The Comments you entered do not appear to be valid.<br />';
              }
              if(strlen($error_message) > 0) {
                died($error_message);
              }
                $email_message = "Form details below.\n\n";

                function clean_string($string) {
                  $bad = array("content-type","bcc:","to:","cc:","href");
                  return str_replace($bad,"",$string);
                }

                $email_message .= "First Name: ".clean_string($first_name)."\n";
                $email_message .= "Last Name: ".clean_string($last_name)."\n";
                $email_message .= "Email: ".clean_string($email_from)."\n";
                $email_message .= "Telephone: ".clean_string($telephone)."\n";
                $email_message .= "Comments: ".clean_string($comments)."\n";


            // create email headers
            $headers = 'From: '.$email_from."\r\n".
            'Reply-To: '.$email_from."\r\n" .
            'X-Mailer: PHP/' . phpversion();
            mail( $email_to, $email_subject, $email_message, $headers );


      }
      ?>
Vishu kapoor
  • 79
  • 1
  • 10
  • Not entirely sure what you are asking here. Do you mean the email doesn't send and you want it to or you want your post action to be a different PHP script? If you've got any errors with the `mail()` function then you are suppressing them with the `@` symbol. Remove this and you might get some errors to repair. – Henders Nov 04 '15 at 10:35
  • if you don't want this redirect to the php file you have to use AJAX to submit the form. By the way: you are missing the `name="Submit"` in `` – swidmann Nov 04 '15 at 10:37
  • @AndyHenderson I want to receive the form data. to a specific email-id..Even after removing @ symbol i am not able to get what i want. – Vishu kapoor Nov 04 '15 at 12:42
  • @Vishukapoor the person that gets sent this email from the form is specified by `$email_to = "Name@gmail.com";` If you want to change who receives this email then you need to change `Name@gmail.com` to whatever email address you want it to go to. Is that what you mean? – Henders Nov 04 '15 at 12:52
  • @AndyHenderson Yeah that is being done purposely. I do not want to reveal my id. – Vishu kapoor Nov 04 '15 at 13:06
  • @swidmann Thanks for mentioning the name error. i have added an ajax `$("#idForm").submit(function(e) { var url = "path/to/your/script.php"; // the script where you handle the form input. $.ajax({ type: "POST", url: url, data: $("#idForm").serialize(), // serializes the form's elements. success: function(data) { alert(data); // show response from the php script. } }); e.preventDefault(); // avoid to execute the actual submit of the form. });` But still it is showing the same error. – Vishu kapoor Nov 04 '15 at 13:15
  • @Vishukapoor, added an answer and also forgot the name of the button xD, well I added it now – swidmann Nov 04 '15 at 13:19
  • _"But still it is showing the same error"_ Unless i'm missing something I haven't seen you say what this error is. Are you getting any error text, code or log anywhere? This will help work out the issue. – Henders Nov 04 '15 at 14:45
  • "_On submitting it is redirecting to the php code rather than sending the mail._" I mentioned it in the beginning of the question. I have updated the code. Now it is not redirecting to php file but on submitting the form it is not sending the data to the mail. Can you review the php file. I think there is an error in it. @AndyHenderson – Vishu kapoor Nov 04 '15 at 15:00
  • @Vishukapoor No need to put your email address in. You can take that out so you don't get spam. Are you getting any PHP errors? – Henders Nov 04 '15 at 15:11

2 Answers2

2

Post your form with ajax and e.preventDefault(); will avoid the redirect. I thought this is too long for a comment, but I'm refering to your comment.

You just forgot to give the form an id look change this in your code:

JavaScript:

$("#htmlform").submit(function (e) {....

PHP:

<form name="htmlform" id="htmlform"....

You have to change that in the example below:

var url = "path/to/your/html_form_send.php";// insert your path to the php file

Here is a working example:

<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
    $(document).ready(function () {
        $("#htmlform").submit(function (e) {
            var url = "path/to/your/html_form_send.php"; // the script where you handle the form input.
            $.ajax({type: "POST", url: url, data: $(this).serialize(), // serializes the form's elements.
                success: function (data) {
                    alert(data); // show response from the php script.
                }});
            e.preventDefault(); // avoid to execute the actual submit of the form
        });
    });
</script>
<form name="htmlform" id="htmlform" method="post" action="html_form_send.php">
    <table width="450px">
        <!-- just removed for testing -->
        <tr>
            <td colspan="2" style="text-align:center">
                <input type="submit" name="Submit" value="Submit">
            </td>
        </tr>
    </table>
</form>

html_form_send.php

<?php
if ( isset( $_POST['Submit'] ) ) {

    $email_to = "Name@gmail.com";

    /**
     *  JUST SHORTENED FOR THIS EXAMPLE
     */
    // save the return of the mail function, if you are using the @
    $sent = @mail( $email_to, $email_subject, $email_message, $headers );

    echo json_encode( array( "success" => $sent ) ); // return something that you can use in javascript
}// <<<<<<< YOU FORGOT THIS
?>

HINT: From the jQuery docs:

Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button.

So your if will never be true, due to the fact you are using serialize

if ( isset( $_POST['Submit'] ) ) {

Just change that to

if ( isset( $_POST['first_name'] ) ) {

or add a hidden input field with the name "submit" to your form

<form name="htmlform" id="htmlform" method="post" action="html_form_send.php">
        <input type="hidden" name="Submit" value="some value" />
swidmann
  • 2,787
  • 1
  • 18
  • 32
  • After making these changes i am still not able to receive mails. Although now on submission it is not referring to php file. – Vishu kapoor Nov 04 '15 at 13:53
  • please remove the `@` from `@mail` and maybe dump the return value, try to validate how far you get in your php file. maybe add some `var_dump(__LINE__)` to it and check the response of the ajax call in your browsers network panel – swidmann Nov 04 '15 at 13:57
  • Can you review my php file. I think there might be an error in it. – Vishu kapoor Nov 04 '15 at 15:05
  • well yes, but I'll do that on the weekend if you still need it, otherwise you could try to post it here: http://codereview.stackexchange.com/ – swidmann Nov 04 '15 at 16:20
  • @Vishukapoor, I had a few minutes and updated my answer, I testet this and received an email. BUT next time please look into your error log you missed a closing `}` this will give you a `parse error syntax error` Here you can get some tips: http://stackoverflow.com/questions/845021/how-to-get-useful-error-messages-in-php – swidmann Nov 04 '15 at 16:49
  • @Vishukapoor: did you try the additional answer below `html_form_send.php`. Would be glad to hear if it worked – swidmann Nov 06 '15 at 15:28
  • I didn't read your comment mentioning you completed it yesterday. I was under this impression that you will do it on the weekends. I am afraid but the code isn't working. If i will put submit as hidden then it won't show the toggle button for submission. . – Vishu kapoor Nov 06 '15 at 18:32
  • @Vishukapoor: no problem just use the `if ( isset( $_POST['first_name'] ) ) {`by the way if you added the hiddn input field you have to KEEP the submit button, too. – swidmann Nov 06 '15 at 19:54
  • Still it is not working properly. I have update the code in the question. See how it is different from yours. – Vishu kapoor Nov 07 '15 at 04:32
  • @Vishukapoor: what means it´s not working properly, do you get any errors? – swidmann Nov 07 '15 at 20:22
  • I am still not receiving the mails. I am using exactly the same code which is there in question. Is it that i have to host it on github or AWS to receive these mails? – Vishu kapoor Nov 08 '15 at 06:23
  • well you need at least sendmail (or euqivalent) for that, it´s installed on servers. If you are on a localhost, please search (maybe google) for: **sendmail on localhost** or **send emails from localhost** If you can host this at github or AWS then do it :) – swidmann Nov 08 '15 at 18:46
  • Thank you so much. I was missing out on sendmail. – Vishu kapoor Nov 09 '15 at 05:41
0

if you submit a form you are getting sent to the document you specified in your action parameter.

If you want to send data to your php without loading to a different page you can use a ajax call, which you can call on buttonclick via javascript, or just simply merge your php with your html document and referencing a '#' in your action parameter.

Silencio
  • 175
  • 8
  • Thanks for the answer. I tried using this ajax `$("#myForm").submit(function(e) { var url = "html_form_send.php"; // the script where you handle the form input. $.ajax({ type: "POST", url: url, data: $("#myForm").serialize(), // serializes the form's elements. success: function(data) { alert(data); // show response from the php script. } }); e.preventDefault(); // avoid to execute the actual submit of the form. }); ` Still getting the same error – Vishu kapoor Nov 04 '15 at 13:06