简体   繁体   English

如何使此联系​​表具有交互性并反映信息?

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

How would I go about making this HTML contact form interactive? 我将如何使此HTML联系人表单具有交互性?

<!-- 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. 我希望将用户输入的信息通过PHP脚本发送给我,但我不确定该PHP脚本的外观。

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). 一种方法是使用AJAX(JavaScript客户端向服务器发出的请求)。

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. 不久前,我已经编写了一个AJAX函数,该函数通过将所需参数发送到服务器来处理AJAX调用的执行。 The request is received by a PHP file that will return data. 该请求由将返回数据的PHP文件接收。 This data can then be used by JavaScript in a callback function. 然后,JavaScript可以在回调函数中使用此数据。

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. 下面的函数使用GET运行AJAX调用,允许我们将参数( object )发送到文件( string ),并在请求结束后启动回调( function )。

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. 然后,在文件send.php ,可以放入以下代码来处理AJAX调用发送的url参数。

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. 通过上述过程,您无需在HTML中使用form You can simply have the input tags, and of course, a button to launch the function sendData() . 您只需input标签,当然还有一个button即可启动功能sendData() Use the attribute onclick in the button 's tag to specify the action to be executed when the button is clicked. button的标记中使用属性onclick可以指定单击按钮时要执行的操作。

 <!-- 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. 您甚至可以使用PHP,以便它在回调中返回实际的Javascript对象,而不只是字符串。 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. 您必须使用内置的json_encode()函数来获取PHP数组的JSON表示形式。 For example: 例如:

$array = array({

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

});

echo json_encode($array);

Then in JavaScript inside the callback function use: 然后在JavaScript内部的回调函数中使用:

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). 您实际上已将响应转换为Javascript对象(不确定它是否是JSON对象...,但它是JavaScript对象,这很重要)。 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... 这意味着您可以访问obj的属性:例如, obj.name将具有用户名, obj.subject是消息的主题,等等。

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. 您可能在PHP文件中有一个进程,可将数据保存到数据库并返回其他信息。 The possibilities are countless with AJAX! 使用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 . 如果您是初学者,并且不想编写任何PHP代码,则可以使用https://formspree.io/之类的服务,也可以使用我在此处创建的服务 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. 使用我的表单处理程序,您可以使用GOTO名称指定提交表单后页面应重定向到的位置。

<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. 如果您阅读了文档,则可以使用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. 使用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: 您的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处理程序(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. 不要忘记验证表单数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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