无法将数据从ajax发送到php

时间:2017-04-20 23:13:26

标签: javascript php ajax

我真的需要你的帮助。我无法从ajax访问php中的帖子数据。我不知道这里发生了什么。我尝试在stackoverflow中搜索解决方案,但没有一个帮助我。这是我的剧本,..

    <script>
                    $('form.ajax').on('submit',function() {
                        var that = $(this),
                        url = that.attr('action'),
                        type = that.attr('method'),
                        data = {};

                        that.find('[name]').each(function(index, value) {
                            var that = $(this),
                            name = that.attr('name'),
                            value = that.val();

                            data[name] = value;
                            console.log(data.name);
                        });
                        $.ajax({
                            url: url,
                            type: type,
                            data: data,
                            success: function(response) {

                            }

                        });
                        return false;
                    });
                </script>

这是我的PHP代码,

                  <?php
$con=mysqli_connect("localhost","username","password","databasename");
if(mysqli_connect_errno())
{
    echo "failed to connect to MySQL:"+mysqli_connect_error();
    die();
}
$myQuery = "SELECT * FROM Invoice";
$result1 = mysqli_query($con,$myQuery);
if(isset($_POST['name'])){
    $name = $_POST['name'];
    $query = "SELECT * FROM Invoice WHERE InvoiceNumber LIKE '%".$name."'";
    $result1 = mysqli_query($con,$query);
}
$data1 = array();
while($row = mysqli_fetch_array($result1)) {
    $row_data = array(
        'InvoiceNumber' => $row['InvoiceNumber'],
        'InvoicePONumber' => $row['InvoicePONumber']
    );
    array_push($data1,$row_data);
}

echo json_encode($data1);

&GT;

1 个答案:

答案 0 :(得分:2)

$.ajax的默认请求方法是GET,因此您永远不会在$_POST var中获得任何结果。相反,您应该使用$.post或将请求类型添加到ajax来电。

$.ajax({
    ...
    type: 'POST'
});