将数据从ajax发布到php脚本

时间:2016-12-12 07:34:02

标签: php jquery ajax

问题

我有一个onclick Jquery函数,它将返回所单击表行的第一个单元格中的值。然后我尝试使用ajax type: 'POST'将此值传递给php脚本,然后使用此值执行数据库查询以进行比较。出于某种原因,$ _POST始终为空。 ajax没有返回任何错误,但我无法在服务器端接收数组的值。任何帮助表示赞赏。

的jQuery

$('tr.profileTableClick').click(function() {
var tableData = $(this).find('td:nth-child(1)').map(function() {
    return $(this).text();
}).get();

$.ajax({
    url: 'selectAnswers.php',
    type: 'POST',
    data: {
        'id': tableData
    },
    dataType: 'text',
    error: function() {
        console.log('Error in ajax request');
    },
    success: function(data) {
        console.log('Success of ajax request');
        console.log(data);
    }
});

PHP

以下是selectAnswers.php文件:

<?php

$id = $_POST['id'][0];

try {
    $conn = new PDO(
        "mysql:host=$servername;dbname=$dbname",
        $username,
        $password
    );

    $conn->setAttribute(
        PDO::ATTR_ERRMODE,
        PDO::ERRMODE_EXCEPTION
    );

    $stmt = $conn->prepare(
        "SELECT
            quality_of_service,
            self_improvement,
            personal_behavior,
            organization_rules_commitment,
            team_work,
            appearance, work_with_high_responsibility,
            loyalty_to_organization,
            punctuality_on_work,
            office_maintaining, areas_of_improvement,
            points_of_weakness,
            points_of_strength
        FROM appraisals_table
        WHERE Apr_Id = :id"
    );

    $stmt->bindValue(
        ':id',
        $id,
        PDO::PARAM_INT
    );

    $stmt->execute();

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $ans1 = $row['quality_of_service'];
        $ans2 = $row['self_improvement'];
        $ans3 = $row['personal_behavior'];
        $ans4 = $row['organization_rules_commitment'];
        $ans5 = $row['team_work'];
        $ans6 = $row['appearance'];
        $ans7 = $row['work_with_high_responsibility'];
        $ans8 = $row['loyalty_to_organization'];
        $ans9 = $row['punctuality_on_work'];
        $ans10 = $row['office_maintaining'];
        $ans11 = $row['areas_of_improvement'];
        $ans12 = $row['points_of_weakness'];
        $ans13 = $row['points_of_strength'];
    }
} catch(PDOException $e) {
    echo 'Error: '. $e->getMessage();
}

$conn = null;

Console log

2 个答案:

答案 0 :(得分:0)

更改js:

var tableData = $(this).find("td:nth-child(1)").text();

或php:

$id = (int)$_POST['id'][0]

答案 1 :(得分:0)

使用新的javascript&#39; FormData API。 。

var formdata = new FormData();
formdata.append('id', tableData);

$.ajax({
    url: 'selectAnswers.php', 
    type: 'POST', 
    data: formdata, 
    dataType: 'text', 
    error: function(){ 
        console.log("Error in ajax request"); 
    }, 
    success: function(data) { 
        console.log("Success of ajax request"); 
        console.log(data); 
    } 
});