简体   繁体   English

如何在不重新加载页面的情况下将数据从 HTML 页面传递到 PHP 脚本?

[英]How to pass data from HTML page to PHP script without reloading the page?

Goal: I want to Hide "myForm" div when data successfully post to the database and the "section" div will show component when submit button will clicked, its working properly.目标:我想在数据成功发布到数据库时隐藏“myForm”div,当点击提交按钮时,“section”div 将显示组件,它工作正常。

Problem / Requirement: Problem is that data not posting to the database, how can i solve this problem to save data to the database and show / hide div after that database operation.问题/要求:问题是数据没有发布到数据库,我该如何解决这个问题以将数据保存到数据库并在数据库操作后显示/隐藏 div。

Note: I don't want to reload my page.注意:我不想重新加载我的页面。

HTML Code: 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 Code: 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';
});

Please suggest flow and process in above Javascript code for how to pass my data to below PHP script..请在上面的 Javascript 代码中建议流程和过程,以了解如何将我的数据传递到下面的 PHP 脚本..

PHP Code: 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);
    }
}

Thanks for your help in advance..提前感谢您的帮助..

You have to pass your client request to server side through AJAX, call your server script using AJAX from your javascript code function:您必须通过 AJAX 将您的客户端请求传递到服务器端,使用 javascript 代码 ZC1C425Z568E68385D14A34A6659BCEAE779F28185E757ABFCA5Z 调用您的服务器脚本

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);
        }
    });

});

You are using pure javascript.您使用的是纯 javascript。 You can send post request to server by using XMLHttpRequest.您可以使用 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");

});

For reference xmlhttprequest you may visit https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send this url.如需参考 xmlhttprequest,您可以访问https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/发送此 Z572D4E421E5E6B9BC11D815E8A027112

`$(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
    }});
  });
});`

Using the fetch api for simplicity and brevity - an example piece of code that will make a POST request to the server ( in this instance the same page but change location.href for the correct endpoint / url ) and use the callback to perform the DOM manipulation.为简单起见,使用fetch api - 一个示例代码,将向服务器发出 POST 请求(在本例中为同一页面,但更改location.href以获得正确的端点 / url )并使用callback执行 DOM操纵。

The PHP at the top here is to emulate YOUR database insert - you would be advised however to use a prepared statement rather than embedding user content directly in the SQL as this leaves you vulnerable to SQL Injection.顶部的 PHP 用于模拟您的数据库插入 - 但是建议您使用prepared statement ,而不是将用户内容直接嵌入 SQL 中,因为这会使您容易受到 Z9778840A0101CB30C982ZB767A 注入的攻击。

<?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>

You can do it many ways.你可以通过很多方式做到这一点。 I made this very simple way using Ajax with a single php file.我使用 Ajax 和一个 php 文件做了这个非常简单的方法。 You need to send the data via ajax and need to catch that using PHP.您需要通过 ajax 发送数据,并且需要使用 PHP 捕获该数据。 You can try the below code.你可以试试下面的代码。

Note: Please make sure you have changed the your connection name, password and db name注意:请确保您已更改连接名称、密码和数据库名称

<!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);
    }
?>

暂无
暂无

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

相关问题 如何在不重新加载页面的情况下将数据javascript传递到php页面 - how to pass data javascript into php page without reloading the page 如何在不重新加载页面的情况下将信息传递给并运行PHP脚本 - How to pass information to and run a PHP script without reloading the page 在 HTML 文件中重新运行 PHP 脚本而不重新加载页面 - Rerun PHP Script inside HTML file without reloading page 如何将变量从 javascript 函数传递到 php 文件而不重新加载编写 javascript 函数的当前 html 页面? - how to pass a variable from javascript function to php file without reloading the current html page in which javascript function is written? 将当前HTML文本框值从JavaScript传递到PHP,而无需重新加载页面或写入URL - Pass current HTML textbox value from JavaScript to PHP without reloading the page or writing to the URL 如何在不使用XMLHttpRequest()重新加载页面的情况下将datepicker值传递给php; - How to pass datepicker value to php without reloading the page using XMLHttpRequest(); 提交表单后如何清除表单并将数据传递到php文件而不重新加载页面 - how to clear form after submit the form and pass the data to php file without reloading page 执行PHP脚本而无需重新加载页面 - performing php script without reloading the page 如何在不使用php和Ajax重新加载的情况下从同一页面上的mysql获取数据 - How to fetch data from mysql on the same page without reloading using php and ajax 如何不重新加载就返回HTML页面 - How to return to an html page without reloading it
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM