【问题标题】:How to pass data from HTML page to PHP script without reloading the page?如何在不重新加载页面的情况下将数据从 HTML 页面传递到 PHP 脚本?
【发布时间】:2020-05-31 13:38:26
【问题描述】:

目标:我想在数据成功发布到数据库时隐藏“myForm”div,并且“section”div 将在单击提交按钮时显示组件,它工作正常。

问题/要求:问题是数据没有发布到数据库,我该如何解决这个问题,将数据保存到数据库并在数据库操作后显示/隐藏 div。

注意:我不想重新加载我的页面。

HTML 代码:

<div id="section" style="display: none;">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae cupiditate culpa reprehenderit animi,
        numquam distinctio repellendus debitis fugit unde consequatur eum magni illo minima amet quidem omnis veniam
        commodi voluptatum!
    </p>
</div>
<div id="myForm">
    <form id="testForm" method="post" action="#">
        <input id="form_name" type="text" name="name" class="form-control">
        <input type="submit" name="submit" class="btn btn-send" value="submit">
    </form>
</div>

JavaScript 代码:

const sectionDiv = document.getElementById('section');
const form = document.getElementById('myForm');

form.addEventListener('submit', function (e) {
    e.preventDefault();

    // Please suggest the flow and code for call PHP script from here

    form.style.display = 'none';
    sectionDiv.style.display = 'block';
});

请在上面的 Javascript 代码中建议流程和过程,以了解如何将我的数据传递到下面的 PHP 脚本..

PHP 代码:

include("db.php");

if (isset($_POST['submit'])) 
{
    $form_name=  $_POST['name'];
    $query = "INSERT INTO `test` (`xxname`) VALUES ('$form_name')";
    if(mysqli_query($conn, $query))
    {
        echo "asdfghjkl";
    } 
    else
    {
        echo "ERROR: Could not able to execute $query. " . mysqli_error($conn);
    }
}

提前感谢您的帮助..

【问题讨论】:

  • 使用 AJAX 将数据发送到 PHP 脚本(保存到数据库)并使用 callback 隐藏表单
  • 嗨。在表单中尝试,有一个输入框,但样式为 display:none

标签: javascript php html ajax


【解决方案1】:

您必须通过 AJAX 将您的客户端请求传递到服务器端,从您的 javascript 代码函数中使用 AJAX 调用您的服务器脚本:

const sectionDiv = document.getElementById('section');
const form = document.getElementById('myForm');

form.addEventListener('submit', function (e) {

    e.preventDefault();

    let serData = form[0].serialize();

    // Add your AJAX Code here
    $.ajax({
        url: "/form.php", // your PHP script's file name
        type: "post",
        data: serData, // pass your fields here 
        success: function(data){
            // do your actions here 
            // you can put your condition here like if( data.status == true ) then success other wise failure
            form.style.display = 'none';
            sectionDiv.style.display = 'block';
        },
        error: function (request, status, error) {
             // console your error here
             console.log(error);
        }
    });

});

【讨论】:

    【解决方案2】:

    您使用的是纯 JavaScript。您可以使用 XMLHttpRequest 向服务器发送 post 请求。

    form.addEventListener('submit', function (e) {
        e.preventDefault();
        var xhr = new XMLHttpRequest();
        xhr.open("POST", '/your-request-path', true);
    
        //Send the proper header information along with the request
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    
        xhr.onreadystatechange = function() { // Call a function when the state changes.
          if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
             form.style.display = 'none';
             sectionDiv.style.display = 'block';
          }
        }
        xhr.send("your form data");
    
    });
    

    参考xmlhttprequest你可以访问https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send这个url。

    【讨论】:

      【解决方案3】:
      `$(document).ready(function(){
        var data = $('.testForm').serialize();
        $(".btn-send").click(function(){
          $.ajax({
             url: "write path here where you insert data to database",
             data: data,
             success: function(response){
              // write code what you want if operation succes
          }});
        });
      });`
      

      【讨论】:

        【解决方案4】:

        您可以通过多种方式做到这一点。我使用带有单个 php 文件的 Ajax 制作了这种非常简单的方法。您需要通过 ajax 发送数据,并且需要使用 PHP 来捕获它。你可以试试下面的代码。

        注意:请确保您已更改连接名称、密码和数据库名称

        <!DOCTYPE html>
        <html>
            <head>
                <title>Insert Data from html form to MySQL Database using Ajax and PHP</title>
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
            </head>
            <body>
                <div class="message" style="display: none;">
                    <p>
                        Lorem ipsum dolor sit amet consectetur adipisicing elit. Quibusdam quo ex pariatur aliquid vero!
                        Voluptatibus harum accusamus amet maiores at sit, neque magni nulla ut optio quis culpa nisi nostrum!
                    </p>
                </div>
                <form id="myForm">
                    <label for="name">Name:</label>
                    <input type="text" id="name" placeholder="Name" name="name" />
                    <input type="submit" name="save" value="Submit" id="btn-save" />
                </form>
        
                <script>
                    const submit = $('#btn-save').click(function (e) {
                        e.preventDefault();
        
                        const name = $('#name').val();
        
                        if(!name) return alert('Please enter your name');
        
                        $.ajax({
                            url: 'index.php',
                            type: 'POST',
                            data: { name: name },
                            success: function (data) {
                                $('.message').show();
                                $('#myForm').hide();
                            },
                        });
                    });
                </script>
            </body>
        </html>
        
        <?php
            $conn = mysqli_connect("localhost", "root", "","mydb");
        
            // Checking connection
            if ($conn->connect_error) {
                die("Connection failed: " . $conn->connect_error);
            } 
        
            // If the form data found save and send response
            if(isset($_POST['name'])){
                $name=$_POST['name'];
                $sql = "INSERT INTO `users`( `name`) VALUES ('$name')";
        
                if (mysqli_query($conn, $sql)) {
                    echo json_encode(array("statusCode"=>200)); 
                }
                else { 
                    echo json_encode(array("statusCode"=>201)); 
                } 
                mysqli_close($conn);
            }
        ?>
        

        【讨论】:

          【解决方案5】:

          为了简单和简洁,使用fetch api - 将向服务器发出 POST 请求的示例代码(在本例中为同一页面,但更改 location.href 以获得正确的端点/url)并使用callback 执行 DOM 操作。

          此处顶部的 PHP 用于模拟您的数据库插入 - 但是建议您使用 prepared statement 而不是将用户内容直接嵌入 SQL 中,因为这会使您容易受到 SQL 注入的攻击。

          <?php
          
              # include scripts
              require 'db.php';
          
          
              /*
                  The PHP endpoint that handles the database insert.
                  For the purposes of this example it is on the same
                  page as the HTML form but can as easily be a different
                  script.
              */
              if( $_SERVER['REQUEST_METHOD']=='POST' ){
                  /*
                      Only process this piece if there is a POST request with
                      a particular parameter present in the request. Note that
                      it makes more sense to test that the parameter that will 
                      be used in any database operations is present as opposed
                      to the `submit` button which is commonly used for such a 
                      test but serves no purpose beyond this point so is redundant.
                  */
                  if( isset( $_POST['name'] ) ){
                      /*
                          As this is an AJAX request we are only interested in
                          content generated in this piece of code. Anything that
                          was generated before or after should be discarded.
                      */
                      ob_flush();
          
          
                      /* 
                          Create a "Prepared Statement" to allow the user 
                          supplied data to be handled in a safe manner. Note
                          that you should not use `mysqli_real_escape_string`
                      */
                      $sql='insert into `test` ( `xxname` ) values ( ? )';
                      $stmt=$db->prepare( $sql );
          
                      /*
                          The return value from the `prepare` method is a Boolean
                          so you are able to use that value to "Fork" the program
                          logic.
                      */
                      if( $stmt ){
                          /*
                              The prepared statement has been created by the server
                              so now you can assign values to the placeholders. This
                              is done using `bind_param`
          
                              Different types of variable can be bound using a different
                              `type` argument
                                  >   i   - integers
                                  >   s   - strings
                                  >   d   - double
                                  >   b   - boolean
                          */
                          $stmt->bind_param( 's', $_POST['name'] );
                          /*
                              With the variable bound to the placeholder
                              you can now commit the data to the db
                          */
                          $result=$stmt->execute();
                          $rows=$stmt->affected_rows;
                          /*
                              The return value from `execute` is a boolean. 
                              It will be false if, for some reason, the db
                              failed to process the request.
          
                              To determine if the request succeeded you can use
                              a combination of $result & $rows if you wish and
                              inform the user with an appropriate response.
                          */
                          $response = $result && $rows==1 ? 'Whoohoo! Record added - ya dancer!' : 'ERROR: Could not insert record';
                          exit( $response );
                      }else{
                          /*
                              If you get here it often suggests a syntax error in 
                              the sql. You could use $stmt->error to aid analysis
                              but not in production code.
                          */
                          exit('bogus');
                      }
                  }
          
                  /* To prevent the whole page appearing in the AJAX response */
                  exit();
              }
          ?>
          <!DOCTYPE html>
          <html lang='en'>
              <head>
                  <meta charset='utf-8' />
                  <title>Submit Form data and hide form</title>
              </head>
              <body>
          
                  <!-- slightly streamlined version of original HTML markup. -->
                  <div style='display:none;'>
                      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae cupiditate culpa reprehenderit animi,
                          numquam distinctio repellendus debitis fugit unde consequatur eum magni illo minima amet quidem omnis veniam
                          commodi voluptatum!
                      </p>
                  </div>
                  <div>
                      <form method='post'>
                          <input type='text' name='name' />
                          <input type='submit' />
                      </form>
                  </div>
          
          
                  <script>
                      /*
                          Bind an event handler to the submit ( or regular ) button to fire
                          an AJAX request to the PHP server.
          
                          Binding a FORM with the `submit` event requires a different approach
                          to that shown in the question. The callback function or event handler
                          needs to return a boolean and the form will only be submitted if the
                          function evaluates to true. Hence better binding to the button as we
                          do not want to send the form in the traditional sense - we need to 
                          fashion our own request without reloading the page.
                      */
                      document.querySelector('form > input[type="submit"]').addEventListener('click', function(e){
                          // Prevent the form being submitted.
                          e.preventDefault();
          
                          /* 
                              using parent and sibling selectors we can identify 
                              the required DOM elements that will be used in the
                              show/hide operations.  
                          */
                          let container=this.parentNode.parentNode;
                          let div=container.previousElementSibling;
          
                          /*
                              The `Fetch` api was developed to provide greater
                              flexibility than the more commonly used `XMLHttpRequest`
                              which has become the workhorse of many web applications.
          
                              To explain it fully you should study the documentation on
                              MDN - https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
                              Google - https://developers.google.com/web/updates/2015/03/introduction-to-fetch
          
                              Another little gem is the `FormData` object used here.
                              MDN - https://developer.mozilla.org/en-US/docs/Web/API/FormData
          
          
                              The fetch call sends the request in this case to the same page ( location.href )
                              and has various configuration options set - method and body being of interest.
          
                              The `body` of the request is the `FormData` object which can be populated
                              automagically by supplying a reference to the FORM as the argument or manually
                              by calling the `append` method.
          
                              rtfm
                          */
                          fetch( location.href, { method:'post',body:( new FormData( document.querySelector('form') ) ) } )
                              .then( response=>{ return response.text() } )
                              .then( text=>{
                                  /* The server response can be read / used here */
                                  console.info( text );
          
                                  /* perform the show and hide operations... */
                                  container.style.display='none';
                                  div.style.display='block';
                              })
                              .catch( err=>{ alert(err) })                
          
                      });
          
                  </script>
              </body>
          </html>
          

          【讨论】:

          • 如果你展示了如何实现参数绑定,它可能会更少。也试着多解释一下你的代码。
          猜你喜欢
          • 1970-01-01
          • 2017-03-03
          • 1970-01-01
          • 1970-01-01
          • 2013-08-20
          • 2010-12-22
          • 2013-07-17
          • 1970-01-01
          • 2015-10-09
          相关资源
          最近更新 更多