将POST数据发送到PHP脚本 - jQuery,AJAX& PHP

时间:2016-12-08 01:29:37

标签: javascript php jquery mysql ajax

我似乎很难将POST数据发送到我的PHP脚本。

我的AJAX将数据(博客帖子的ID)发送到我的PHP脚本,然后PHP脚本会从数据库中找到包含匹配ID的行。

然后,脚本将数据发送回博客文章的标题和帖子的内容,AJAX将其拾取并插入到DOM中的表单中。

我能成功:

  • 插入样本数据(例如,如果我只是将字符串存储到数组中,我将传回AJAX,它会成功地将这些字符串插入到表单中);和
  • 在指定静态ID时从数据库中插入正确的数据(例如,如果我切换$ _POST [' editpostid']并指定整数5,则查询成功找到包含ID = 5,AJAX将此数据插入表单中。

因此,从我的角度来看,问题是ID永远不会到达PHP脚本,或者我的脚本无法在JSON对象中看到ID。

请查看我的代码并告诉我您的想法。我对这一切都很陌生,所以我很感激您的反馈意见 - 如果它能解决问题的话。

的Javascript / jQuery的:

// When edit button is clicked
$('li.edit').click(function() {

    // Get class (postid inserted with PHP) of edit button, excluding edit class
    var oldpostid = $(this).attr('class').split(' ')[1];

    alert(oldpostid); // Returns the correct postid, for example 5

    var jsonObj = { 'postid': oldpostid };

    alert(jsonObj); // Returns 'object Object'

    // Send postid to PHP script
    $.ajax({
        type: 'POST',
        url: '../scripts/fetchpost.php',
        dataType: 'json',
        data: { 'editpostid': jsonObj },
        success: function() {

            // Fetch post data back from script
            $.getJSON('../scripts/fetchpost.php', function(data) {

                alert(data.title); // Returns null
                alert(data.content); // Returns null

                // All of the below code works if the PHP script returns sample text,
                // or if an ID is specified in the PHP script itself

                var title = data.title;
                var content = data.content;

                // Insert data into editor
                $('#titlehead').text(title);
                $('#edittitle').val(title);
                var editor = 'editpost-content';
                tinymce.get(editor).setContent(content);
            });
        },
        error: function( e ) {
        console.log(e.message);
    }
    });
});

PHP:

<?php

// Specifies connection details
include('../scripts/config.php');

// Fetch data from AJAX
$postid = $_POST['editpostid']; // Where I think the problem lies. Returns null.
// Again, this works if I switch out $_POST with an integer, such as 5

// Find rows in database that match postid
$postedit_qry = mysqli_query( $dbconnect, "SELECT * FROM posts WHERE postid='$postid'" );

// Store results in an associative array
$row = mysqli_fetch_assoc( $postedit_qry );

// Split array into variables
$title = $row['title'];
$content = $row['content'];

// Organise data into an array for json
$postedit = array(
    'title' => $title,
    'content' => $content
);

// Return array as json object for ajax to pick up
echo json_encode( $postedit );

// Close connection
mysqli_close( $dbconnect );

?>

更新 - 解决方案:

修正了jQuery / Javascript:

// Snip

// Get class (postid inserted with PHP) of edit button, excluding edit class
    var oldpostid = $(this).attr('class').split(' ')[1];

    // Send postid to PHP script
    $.ajax({
        type: 'POST',
        url: '../scripts/fetchpost.php',
        dataType: 'json',
        contentType: 'application/x-www-form-urlencoded',
        data: { "editpostid": oldpostid },
        success: function(data) {

            var title = data.title;
            var content = data.content;

// Snip

PHP脚本保持不变。

非常感谢您的帮助! MrPupper

2 个答案:

答案 0 :(得分:2)

我认为您错过了索引'postid'并需要替换此

$postid = $_POST['editpostid'];

这一行:

$postid = $_POST['editpostid']['postid'];

或者不是发送

data: { 'editpostid': jsonObj },

发送此

data: { 'editpostid': oldpostid },

答案 1 :(得分:0)

查看您的代码,您似乎得到了null,因为您要求fetchpost.php脚本两次。一旦您通过$.ajax(...);与脚本联系,再次致电$.getJSON(...);时再次与脚本联系。但是,当您通过$.getJSON(...);进行联系时,您不是POST数据,而且您的脚本似乎没有正确定义的方式来处理GET请求,因此脚本没有&#39} ; t知道如何反应,它返回空信息。

我会将JavaScript / jQuery更改为以下内容:

// When edit button is clicked
$('li.edit').click(function() {

    // Get class (postid inserted with PHP) of edit button, excluding edit class
    var oldpostid = $(this).attr('class').split(' ')[1];

    alert(oldpostid); // Returns the correct postid, for example 5

    var jsonObj = { 'postid': oldpostid };

    alert(jsonObj); // Returns 'object Object'

    // Send postid to PHP script
    $.ajax({
        type: 'POST',
        url: '../scripts/fetchpost.php',
        dataType: 'json',
        data: {'editpostid': jsonObj },
        success: function(sData) {
            var data = JSON.parse(sData);
            alert(data.title); // Returns null
            alert(data.content); // Returns null

            // All of the below code works if the PHP script returns sample text,
            // or if an ID is specified in the PHP script itself

            var title = data.title;
            var content = data.content;

            // Insert data into editor
            $('#titlehead').text(title);
            $('#edittitle').val(title);
            var editor = 'editpost-content';
            tinymce.get(editor).setContent(content);
        },
        error: function( e ) {
            console.log(e.message);
        }
    });
});

此外,PHP将期望application/x-www-form-urlencoded值能够与$_POST[...]进行交互。因此,如果您想提供JSON,那么在您的PHP中,您需要实现一个解决方案,例如:$postedData = json_decode(file_get_contents('php://input')); (请参阅this answer中的详细信息;有关{的更多信息,请参阅{1}},请参阅the official PHP documentation for json_decode.

注意:虽然不在你的问题范围之内,而且你可能已经知道这一点,但我发现重要的是要指出你的MySQL是不安全的,并且由于盲目信任而容易受到SQL注入攻击json_decode未被篡改。在初始化postId并连接到数据库之后,但在将$postid = $dbconnect->real_escape_string($postid);放入SQL查询字符串之前,需要通过说$dbconnect来清理它。