PHP POST变量没有收到来自AJAX的数据

时间:2015-12-07 18:56:35

标签: php json ajax post

我尝试使用AJAX将单击的元素ID发送到我的PHP文件,以便我的SQL语句可以选择适当的数据。一切似乎都在接受我的$_POST变量仍然未定义。

的Javascript

$(document).ready(function(){
    $('.productsForm').submit(createEntry);
    $('.clickProducts').bind('click touchend', refreshEntries);
});

function refreshEntries() {
    //Get the id number of the clicked element.
    var clicked_id = (this.id);
    var cigar_id = clicked_id.toString();
    var display = "";
    $.ajax({
        url: 'php/mobile-select.php',
        type: 'POST',
        contentType: "application/json",
        dataType: 'json',
        data: { product_id : cigar_id
        },
        success: function(json){
            //I'm attempting to loop through the JSON object and create product arrays for each cigar.
            $.each(json, function(key, value){
               $.each(value, function(x, y){
                    display += '<tr><td>'+ x + '</td><td>' + y +'</td></tr>';
                });
            });

        console.log(display);


        }
    })
} 

PHP

<?php
    include("connect-db.php");

    // Post remains undefined for some reason. ????
    $product_id = $_POST['product_id'];

    $select_sql = "SELECT product_name, current_inventory, price FROM products WHERE product_id = '$product_id' ";

    $result = $conn->query($select_sql);

    $data = array();

    while($r = mysqli_fetch_assoc($result)) {
        $data[] = $r;
    }

    $conn->close();

    echo json_encode($data);
?>

2 个答案:

答案 0 :(得分:0)

想想我弄清楚了。我不完全理解为什么,但删除&#34; contentType:&#34; application / json&#34; &#34;从我的.ajax函数做了伎俩。我很感激帮助。

答案 1 :(得分:-1)

您正在发送json对象,因此您需要读取原始数据。

$request_body = file_get_contents('php://input');
$post = json_decode($request_body, true);

$ post将包含您在数组中传递的对象。

还要小心将product_id直接传递给SQL语句。打开你的SQL攻击。