简体   繁体   中英

How do I make this contact form interactive and reflect information?

How would I go about making this HTML contact form interactive?

<!-- Contact Us Form -->
<div class="contact_form_container">
  <form id="reply_form" action="send.php" method="POST">
    <div>
      <input id="contact_form_name" class="input_field contact_form_name" type="text" name="name" placeholder="Name" required="required" data-error="Name is required.">
      <input id="contact_form_email" class="input_field contact_form_email" type="email" name="email" placeholder="E-mail" required="required" data-error="Valid email is required.">
      <input id="contact_form_subject" class="input_field contact_form_subject" type="text" name="subject" placeholder="Subject" required="required" data-error="Subject is required.">
      <textarea id="contact_form_message" class="text_field contact_form_message" name="message" placeholder="Message" rows="4" required data-error="Please, write us a message."></textarea>
    </div>
    <div>
      <button id="contact_form_submit" type="submit" class="contact_submit_btn trans_300" value="Submit">
                                        send<img src="images/arrow_right.svg" alt="">
                                    </button>
    </div>

  </form>

</div>

I would like the user-entered information to be sent to me through a PHP script, but I am not certain what that PHP script would look like.

Upon successful submission, I would like the user's name to be echoed on to the page (ie ' Thank you for your submission Joe, we will get back to you as soon as possible! ').

This is not that easy for beginners actually. One way to do this is by using AJAX (a request made by JavaScript clientside to the server).

I have written an AJAX function a while back that handles the execution of the AJAX call with the desired parameters sent to the server. The request is received by a PHP file that will return data. This data can then be used by JavaScript in a callback function.

This following function runs an AJAX call using GET, allowing us to send parameters ( object ) to a file ( string ) and launch a callback ( function ) when the request has been ended.

function ajax(file, params, callback) {

  var url = file + '?';

  // loop through object and assemble the url
  var notFirst = false;
  for (var key in params) {
    if (params.hasOwnProperty(key)) {
      url += (notFirst ? '&' : '') + key + "=" + params[key];
    }
    notFirst = true;
  }

  // create a AJAX call with url as parameter
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      callback(xmlhttp.responseText);
    }
  };
  xmlhttp.open('GET', url, true);
  xmlhttp.send();
}

Here's how we use it in your case:

function sendData() {

  parameters = {
    name: document.querySelector('#contact_form_name').value,
    email: document.querySelector('#contact_form_email').value,
    subject: document.querySelector('#contact_form_subject').value,
    message: document.querySelector('#contact_form_message').value
  };

  ajax('send.php', parameters, function(response) {
    // add here the code to be executed when data comes back to client side      
    // e.g. console.log(response) will show the AJAX response in the console
  });

}

Then in your file send.php you may put the following code to handle the url parameters sent by the AJAX call.

if (isset($_REQUEST['name'], $_REQUEST['email'], $_REQUEST['subject'], $_REQUEST['message'])) {
    // they are set, you can use them by accessing $_REQUEST
    // return the desired output with `echo` not `return`!
    echo $_REQUEST['name'] . ', you have sent a message.';
}

Using the above process, you are not required to use a form in your HTML. You can simply have the input tags, and of course, a button to launch the function sendData() . Use the attribute onclick in the button 's tag to specify the action to be executed when the button is clicked.

 <!-- Contact Us Form --> <div class="contact_form_container"> <input id="contact_form_name" class="input_field contact_form_name" type="text" name="name" placeholder="Name" required="required" data-error="Name is required."> <input id="contact_form_email" class="input_field contact_form_email" type="email" name="email" placeholder="E-mail" required="required" data-error="Valid email is required."> <input id="contact_form_subject" class="input_field contact_form_subject" type="text" name="subject" placeholder="Subject" required="required" data-error="Subject is required."> <textarea id="contact_form_message" class="text_field contact_form_message" name="message" placeholder="Message" rows="4" required data-error="Please, write us a message."></textarea> </div> <div> <button onclick="sendData()" id="contact_form_submit" type="submit" class="contact_submit_btn trans_300" value="Submit"> send<img src="images/arrow_right.svg" alt=""> </button> </div> 


Returning an object instead of a string:

You can even play around with PHP so that it returns an actual Javascript object in the callback instead of just a string. This can be very helpful if you would like to return various information back to client side.

You have to use the built-in json_encode() function to get the JSON representation of a PHP array. For example:

$array = array({

  'name' => $_REQUEST['name'],
  'subject' => $_REQUEST['subject']

});

echo json_encode($array);

Then in JavaScript inside the callback function use:

let obj = JSON.parse(response);

You have essentially converted the response into a Javascript object (not sure if it's a JSON object..., but it's JavaScript object, that is what matters). This means you can access obj 's properties: for instance, obj.name will have the name of the user, obj.subject the subject of the message, etc...

Note: in this example, I have just returned the information that was sent to the server in the first place, but you can return whatever you wish. You could have a process in the PHP file to save the data to a database and return some other kind of information. The possibilities are countless with AJAX!

If your a beginner and not looking to write any sort of PHP code you can use a service like https://formspree.io/ or one that I made myself here . These are pretty easy to use and require no code on your side.

Using my form handler you can use the GOTO name to specify where the page should re-direct to after the form is submitted.

<input class="hidden" type="text" name="GOTO" value="URL">

If you read the documentation there are lots of things you can customise using a service like Formspree. Therefore you can create a custom page saying "Thanks for your submission".

If you want to actually include information from the form that they submitted you will have to do like whats said above and create your own form handler.

Try something like this to display user name

if(

    !isset( $_POST['name'] ) || empty( $_POST['name'] ) ||
    !isset( $_POST['email'] ) || empty( $_POST['email'] ) ||
    !isset( $_POST['subject'] ) || empty( $_POST['subject'] ) ||
    !isset( $_POST['message'] ) || empty( $_POST['message'] ) ||

)

    exit( 'Please fill all fields' )

    // or redirect to previous page

    // header('Location: ' . $_SERVER['HTTP_REFERER'] . '#error=Please%20fill%all%fields' );



else{

    // Your message saving logic here, save it to a database / file or send it to mail

    echo "Thank you for your submission {$_POST['name'}, we will get back to you as soon as possible!";

}

Use jQuery ajax.

Your form:

     <form id="reply_form" action="#" method="POST">
          <div>
               <input id="contact_form_name" class="input_field contact_form_name" type="text" name="name" placeholder="Name" required="required" data-error="Name is required.">
               <input id="contact_form_email" class="input_field contact_form_email" type="email" name="email" placeholder="E-mail" required="required" data-error="Valid email is required.">
               <input id="contact_form_subject" class="input_field contact_form_subject" type="text" name="subject" placeholder="Subject" required="required" data-error="Subject is required.">
               <textarea id="contact_form_message" class="text_field contact_form_message" name="message"  placeholder="Message" rows="4" required data-error="Please, write us a message."></textarea>
          </div>
          <div>
               <button id="contact_form_submit" type="button" class="contact_submit_btn trans_300" value="Submit">
                      send<img src="images/arrow_right.svg" alt="">
               </button>
          </div>
      </form>

Your JS:

$('#contact_form_submit').click(function(){
    $.post('send.php', $('#reply_form').serialize(), function(data, status){
        if(status == "success"){
            var response_message = data.message;
            alert(response_message);
        }
    }, "json");
});

Your PHP handler (send.php)

<?php
   // Response array, it will be returned to client. You cant extend it with additional data.
   $response = ['message' => 'Error'];

   $name = $_POST['name'] ?: ""; 
   $email = $_POST['email'] ?: "";
   $subject= $_POST['subject'] ?: ""; 
   $message= $_POST['message'] ?: ""; 


   if($name) {
        if(filter_var($email, FILTER_VALIDATE_EMAIL)){
             if($subject){
                  if($message){
                      // do something with form data

                      // if success
                      $response['message'] = "Thank you for your submission". $name .", we will get back to you as soon as possible!";
                  }else{
                       $response['message'] = "Message is too short.";
                  }
             }else{
                  $response['message'] = "Enter subject.";
             }
        }else{
             $response['message'] = "Enter valid email.";
        }
   }else{
        $response['message'] = "Enter your name.";
   }

   echo json_encode($response); 
   exit();

?>

Important: Form action = "#", Button type = "button". Dont forget to validate your form data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM