Ajax发布到相同的.php文件

时间:2018-01-21 18:15:39

标签: javascript php jquery html ajax

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>

我的数据库: the clang FAQ

enter image description here

enter image description here

P.S编辑代码,添加了添加所有选项的代码

4 个答案:

答案 0 :(得分:2)

试试这个

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

答案 1 :(得分:1)

我只是简单地查看了大量的html,因此可能错过了那里的错误,但是通过AJAX POST到同一个文件需要小心注意处理请求的代码部分。无需担心您的请求将返回整个文档 - 通常不是所需的事务状态,因此将该部分代码与ob_clean()隔离,以便在该点结束之前删除任何html /其他内容exit

ajax请求的回调函数应该处理响应 - 在您的情况下,您希望添加到标识为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>

答案 2 :(得分:1)

As it is quite different to the original answer and because the question has mutated a little I felt it might be clearer to add as another answer. Because the original question just revolved around the dvd being added a rethink was required to accomodate other columns and data for the insert statement. The following has not been tested but replaces the original ajax handling php code.

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

The db schema

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)

Adding DVD DVD

Adding a book Book

Adding furniture Furniture

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

答案 3 :(得分:0)

在你的ajax调用中你指定了dataTyp:'json'。然后你应该从php返回json数据。而不是退出,你应该使用return。

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