簡體   English   中英

Ajax發布到相同的.php文件

[英]Ajax post to the same .php file

在Ajax調用中遇到了一些問題。 我的程序根據用戶選擇創建動態字段。 例如,如果用戶選擇“ dvd”,則Javascript將創建一個字段以添加DVD大小,或者如果選擇了家具,則它將創建3個字段以添加h w l個參數。

從HTML表單發布效果很好,但是我無法獲取從jQuery到PHP的數據。 您能幫我用Ajax發布DVD參數嗎?

    <?php

if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['submitted'] ) ) {

    ob_clean();



    include('connect_mysql.php');
    $message='error';

    if( isset( $_POST['price'], $_POST['sku'], $_POST['name'], $_POST['prtype'], $_POST['dvd'], $_POST['book'], $_POST['furnh'], $_POST['furnw'], $_POST['furnl'] ) ) {

        $sku = $_POST['sku'];
        $name = $_POST['name'];
        $price = $_POST['price'];
        $prtype = $_POST['prtype'];
        $dvd = $_POST['dvd'];
        $book = $_POST['book'];
        $furnh = $_POST['furnh'];
        $furnw = $_POST['furnw'];
        $furnl = $_POST['furnl'];

        $sql = "insert into `people` ( `sku`, `name`, `price`, `prtype`, `dvd`, `book`, `furnh`, `furnw`, `furnl`) values (?,?,?,?,?,?,?,?,?)";
        $stmt=$dbcon->prepare( $sql );
        if( $stmt ){

            $stmt->bind_param('sssssssss',$sku,$name,$price,$prtype,$dvd,$book,$furnh,$furnw,$furnl);
            $result=$stmt->execute();
            $stmt->free_result();
            $message=$result ? '1 record added' : 'Something went wrong';

        } else {
            $message='Problem preparing sql statement';
        }
    }


    exit( $message );
}

?>
<html>
<head>
    <title>Submit your data</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

</head>
<body>

<h1>Insert your data</h1>

<form method="post" action="training.php">
    <input type="hidden" name="submitted" value="true" />

    <fieldset>
        <legend>New Product</legend>
        <label>ID:<input type="text" name="sku"/></label>
        <label>Name:<input type="text" name="name"/></label>
        <label>Price:<input type="text" name="price"/></label>
        <label>Product Type</label>
        <select id="Product_Type" name="prtype">
            <option style="display: none;" selected>Select product type</option>
            <option value="Dvd">DVD</option>
            <option value="Book">Book</option>
            <option value="Furniture">Furniture</option>
        </select>
    </fieldset>

    <br  />
    <input type="submit" class="button" name="add" value="add new product"/>

    <script>

        var $input_DVD = $('<input id="dvd" input type="text" name="dvd" class="input" placeholder="Size"/>');
        var $input_Book = $('<input id="book" input type="text" name="book" class="input" placeholder="Weight"/>');
        var $input_FurnitureHeight = $('<input id="furnh" input type="text" class="input" name="furnh" placeholder="Height"/>');
        var $input_FurnitureWidth = $('<input id="furnw" input type="text" class="input" name="furnw" placeholder="Width"/>');
        var $input_FurnitureLength = $('<input id="furnl" input type="text" class="input" name="furnl"  placeholder="Length"/>');


        $(document).ready(function() {
            /*

                The issue was the generation of a new form with the specific values that
                you are trying to use for adding a new record. The new form was never
                included in the data sent so the logic tests were failing and thus no records
                were ever inserted.

                Some simple debugging using the console would have helped you identify this
                though there still remains the issue of how you deal with form submissions
                when the selected item in the `select` menu is other than DVD!!!

                Using the code here you ought to be able to work that part out now - this works
                for DVD as the selected item

                Rather than insert a new form, it now inserts a new fieldset within the original
                form.

            */

            $('select#Product_Type').on('change', function() {
                $('#container').remove();//<!---- just use the ID

                var val = $(this).val()
                $container = $('<fieldset id="container" ></fieldset>');//  <!---- fieldset, not form

                if (val == "Dvd")$input_DVD.appendTo($container);
                if (val == "Book")$input_Book.appendTo($container);
                if (val == "Furniture"){
                    $input_FurnitureHeight.appendTo($container);
                    $input_FurnitureWidth.appendTo($container);
                    $input_FurnitureLength.appendTo($container);
                }
                $container.insertAfter($(this)).val();
            })
        });

        $(function() {
            $('form').submit(function(e) {
                e.preventDefault();
                $.ajax({
                    type        : 'POST',
                    url         : location.href,    //  <!---- POST to same page
                    data        : $(this).serialize(),  //  <!---- send all data from this form
                    dataType    : 'json',
                    encode      : true
                })
                    .done(function(data) {
                        $('#result').html( data );
                    })
            });
        });
    </script>
</form>
<div id='result'></div>
</body>
</html>

我的數據庫: 在此處輸入圖片說明

在此處輸入圖片說明

在此處輸入圖片說明

PS編輯代碼,添加代碼以添加所有選項

嘗試這個

$('form').submit(function(e) {
                e.preventDefault();
                $.ajax({
                    type        : 'POST',
                    url         : 'training.php',  // post to same file
                    data        : $(this).serialize(),
                    dataType    : 'json',
                    encode      : true
                })
                    .done(function(data) {
                        $('#result').html(data);
                    })
            });

我只是簡要瀏覽了大部分html,因此可能在其中遺漏了錯誤,但是通過AJAX到POST到同一文件需要稍微注意處理請求的代碼部分。 不用擔心,您的請求將返回整個文檔-通常不是所需的事務狀態,因此隔離該部分代碼並用ob_clean()包圍以清除所有html /其他內容,然后再exit該點

ajax請求的回調函數應處理響應-在您希望添加到id為result的元素的情況下。

以前的sql容易受到sql注入的攻擊-因此,我在下面顯示如何使用准備好的語句。 以下內容均未經過測試,因此請原諒語法錯誤...

<?php

    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['submitted'] ) ) {

        ob_clean();



        include('connect_mysql.php');
        $message='error';

        if( isset( $_POST['price'], $_POST['sku'], $_POST['name'], $_POST['prtype'], $_POST['dvd'] ) ) {

            $sku = $_POST['sku'];
            $name = $_POST['name'];
            $price = $_POST['price'];
            $prtype = $_POST['prtype'];
            $dvd = $_POST['dvd'];

            $sql = "insert into `people` ( `sku`, `name`, `price`, `prtype`, `dvd`) values (?,?,?,?,?)";
            $stmt=$dbcon->prepare( $sql );
            if( $stmt ){

                $stmt->bind_param('sssss',$sku,$name,$price,$prtype,$dvd );
                $result=$stmt->execute();
                $stmt->free_result();
                $message=$result ? '1 record added' : 'Something went wrong';

            } else {
                $message='Problem preparing sql statement';
            }
        }


        exit( $message );
    }

?>
<html>
    <head>
        <title>Submit your data</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

    </head>
    <body>

        <h1>Insert your data</h1>

        <form method="post" action="training.php">
            <input type="hidden" name="submitted" value="true" />

            <fieldset>
                <legend>New Product</legend>
                <label>ID:<input type="text" name="sku"/></label>
                <label>Name:<input type="text" name="name"/></label>
                <label>Price:<input type="text" name="price"/></label>
                <label>Product Type</label>
                <select id="Product_Type" name="prtype">
                    <option style="display: none;" selected>Select product type</option>
                    <option value="Dvd">DVD</option>
                    <option value="Book">Book</option>
                    <option value="Furniture">Furniture</option>
                </select>
            </fieldset>

            <br  />
            <input type="submit" class="button" name="add" value="add new product"/>

            <script>

                var $input_DVD = $('<input id="dvd" input type="text" name="dvd" class="input" placeholder="Size"/>');
                var $input_Book = $('<input id="book" input type="text" name="book" class="input" placeholder="Weight"/>');
                var $input_FurnitureHeight = $('<input id="furnh" input type="text" class="input" name="furnh" placeholder="Height"/>');
                var $input_FurnitureWidth = $('<input id="furnw" input type="text" class="input" name="furnw" placeholder="Width"/>');
                var $input_FurnitureLength = $('<input id="furnl" input type="text" class="input" name="furnl"  placeholder="Length"/>');


                $(document).ready(function() {
                    /*

                        The issue was the generation of a new form with the specific values that
                        you are trying to use for adding a new record. The new form was never 
                        included in the data sent so the logic tests were failing and thus no records
                        were ever inserted.

                        Some simple debugging using the console would have helped you identify this
                        though there still remains the issue of how you deal with form submissions 
                        when the selected item in the `select` menu is other than DVD!!! 

                        Using the code here you ought to be able to work that part out now - this works
                        for DVD as the selected item

                        Rather than insert a new form, it now inserts a new fieldset within the original
                        form.

                    */

                    $('select#Product_Type').on('change', function() {
                        $('#container').remove();//<!---- just use the ID

                        var val = $(this).val()
                        $container = $('<fieldset id="container" ></fieldset>');//  <!---- fieldset, not form

                        if (val == "Dvd")$input_DVD.appendTo($container);
                        if (val == "Book") $input_Book.appendTo($container);

                        if (val == "Furniture"){
                            $input_FurnitureHeight.appendTo($container);
                            $input_FurnitureWidth.appendTo($container);
                            $input_FurnitureLength.appendTo($container);
                        }
                        $container.insertAfter($(this)).val();
                    })
                })

                $(function() {
                    $('form').submit(function(e) {
                        e.preventDefault();
                        $.ajax({
                            type        : 'POST',
                            url         : location.href,    //  <!---- POST to same page
                            data        : $(this).serialize(),  //  <!---- send all data from this form
                            dataType    : 'json',
                            encode      : true
                        })
                        .done(function(data) {
                            $('#result').html( data );
                        })
                    });
                });
            </script>
        </form>
        <div id='result'></div>
    </body>
</html>

在您的ajax調用中,您要指定dataTyp:'json'。然后您應該從php返回json數據。 而不是退出,您應該使用return。

      return json_encode(@utf8_encode($message));
//or
      return json_encode($message);

由於它與原始答案有很大不同,並且由於該問題有所改變,所以我覺得將其添加為其他答案可能會更清楚。 由於原始問題只是圍繞着要添加的dvd ,因此需要重新考慮以適應insert語句的其他列和數據。 以下內容未經測試,但取代了原始的處理Ajax的php代碼。

<?php

    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['submitted'] ) ) {

        ob_clean();

        /* my test db conn */
        $dbhost =   'localhost';
        $dbuser =   'root'; 
        $dbpwd  =   'xxx'; 
        $dbname =   'xxx';
        $dbcon  =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

        #include('connect_mysql.php');

        $message='error';

        if( isset( $_POST['price'], $_POST['sku'], $_POST['name'], $_POST['prtype'] ) ) {
            /* Do some filtering of the POSTed variables */
            $args=array(
                'sku'       =>  FILTER_SANITIZE_STRING,
                'name'      =>  FILTER_SANITIZE_STRING,
                'price'     =>  array(
                    'filter'    => FILTER_SANITIZE_NUMBER_FLOAT,
                    'flags'     => FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND
                ),
                'prtype'    =>  FILTER_SANITIZE_STRING,
                'dvd'       =>  FILTER_SANITIZE_STRING,
                'book'      =>  FILTER_SANITIZE_STRING,
                'furnh'     =>  FILTER_SANITIZE_STRING,
                'furnw'     =>  FILTER_SANITIZE_STRING,
                'furnl'     =>  FILTER_SANITIZE_STRING
            );
            $_POST=filter_input_array( INPUT_POST, $args );
            /* extract the POST data into variables */
            extract( $_POST );

            /* a one-for-all query, insert empty strings where suitable */
            $sql = "insert into `people` ( `sku`, `name`, `price`, `prtype`, `dvd`, `book`, `furnh`, `furnw`, `furnl` ) values (?,?,?,?,?,?,?,?,?)";
            $stmt= $dbcon->prepare( $sql );

            if( $stmt ){

                $stmt->bind_param('ssdssssss', $sku, $name, $price, $prtype, $dvd, $book, $furnh, $furnw, $furnl );

                if( !empty( $_POST['dvd'] ) ){
                    /* dvd only: set empty values for other parameters/vars */
                    $book = $furnh = $funw = $furnl = '';

                } elseif( !empty( $_POST['book'] ) ){
                    /* books: set empty values for other parameters/vars */
                    $dvd = $furnh = $funw = $furnl = '';

                } elseif( isset( $_POST['furnw'],$_POST['furnl'],$_POST['furnh'] ) ){
                    /* furniture: set empty values for other parameters/vars */
                    $book = $dvd = '';
                }

                $result=$stmt->execute();
                $stmt->free_result();
                $message=$result ? '1 record added' : 'Something went wrong';

            } else {
                $message='Problem preparing sql statement';
            }

            exit( $message );
        }
    }
?>
<html>
    <head>
        <title>Submit your data</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

    </head>
    <body>

        <h1>Insert your data</h1>

        <form method="post" action="training.php">
            <input type="hidden" name="submitted" value="true" />

            <fieldset>
                <legend>New Product</legend>
                <label>ID:<input type="text" name="sku"/></label>
                <label>Name:<input type="text" name="name"/></label>
                <label>Price:<input type="text" name="price"/></label>
                <label>Product Type</label>
                <select id="Product_Type" name="prtype">
                    <option style="display: none;" selected>Select product type</option>
                    <option value="Dvd">DVD</option>
                    <option value="Book">Book</option>
                    <option value="Furniture">Furniture</option>
                </select>
            </fieldset>

            <br  />
            <input type="submit" class="button" name="add" value="add new product"/>

            <script>

                var $input_DVD = $('<input id="dvd" input type="text" name="dvd" class="input" placeholder="Size"/>');
                var $input_Book = $('<input id="book" input type="text" name="book" class="input" placeholder="Weight"/>');
                var $input_FurnitureHeight = $('<input id="furnh" input type="text" class="input" name="furnh" placeholder="Height"/>');
                var $input_FurnitureWidth = $('<input id="furnw" input type="text" class="input" name="furnw" placeholder="Width"/>');
                var $input_FurnitureLength = $('<input id="furnl" input type="text" class="input" name="furnl"  placeholder="Length"/>');


                $(document).ready(function() {
                    /*

                        The issue was the generation of a new form with the specific values that
                        you are trying to use for adding a new record. The new form was never 
                        included in the data sent so the logic tests were failing and thus no records
                        were ever inserted.

                        Some simple debugging using the console would have helped you identify this
                        though there still remains the issue of how you deal with form submissions 
                        when the selected item in the `select` menu is other than DVD!!! 

                        Using the code here you ought to be able to work that part out now - this works
                        for DVD as the selected item

                        Rather than insert a new form, it now inserts a new fieldset within the original
                        form.

                    */

                    $('select#Product_Type').on('change', function() {
                        $('#container').remove();//<!---- just use the ID

                        var val = $(this).val()
                        $container = $('<fieldset id="container" ></fieldset>');//  <!---- fieldset, not form

                        if (val == "Dvd")$input_DVD.appendTo($container);
                        if (val == "Book") $input_Book.appendTo($container);

                        if (val == "Furniture"){
                            $input_FurnitureHeight.appendTo($container);
                            $input_FurnitureWidth.appendTo($container);
                            $input_FurnitureLength.appendTo($container);
                        }
                        $container.insertAfter($(this)).val();
                    })
                })

                $(function() {
                    $('form').submit(function(e) {
                        e.preventDefault();
                        $.ajax({
                            type        : 'POST',
                            url         : location.href,    //  <!---- POST to same page
                            data        : $(this).serialize(),  //  <!---- send all data from this form
                            dataType    : 'json',
                            encode      : true
                        })
                        .done(function(data) {
                            $('#result').html( data );
                        })
                    });
                });
            </script>
        </form>
        <div id='result'></div>
    </body>
</html>

數據庫模式

mysql> describe people;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| sku    | varchar(50) | YES  |     | NULL    |       |
| name   | varchar(50) | YES  |     | NULL    |       |
| price  | varchar(50) | YES  |     | NULL    |       |
| prtype | varchar(50) | YES  |     | NULL    |       |
| dvd    | varchar(50) | YES  |     | NULL    |       |
| book   | varchar(50) | YES  |     | NULL    |       |
| furnw  | varchar(50) | YES  |     | NULL    |       |
| furnl  | varchar(50) | YES  |     | NULL    |       |
| furnh  | varchar(50) | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+


mysql> select * from people;
Empty set (0.00 sec)

新增DVD DVD

新增書籍 書

加家具 家具類

mysql> select * from people;
+--------+--------------+-------+-----------+------+------+-------+-------+-------+
| sku    | name         | price | prtype    | dvd  | book | furnw | furnl | furnh |
+--------+--------------+-------+-----------+------+------+-------+-------+-------+
| 78459  | Geronimo     | 0     | Dvd       | 55   |      | NULL  |       |       |
| 123456 | pocahontas   | 7845  | Book      |      | 5632 | NULL  |       |       |
| 78     | chief wiggum | 0     | Furniture |      |      | 20    | 30    | 10    |
+--------+--------------+-------+-----------+------+------+-------+-------+-------+

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM