简体   繁体   English

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

[英]Sending POST data to PHP script - jQuery, AJAX & PHP

I seem to be struggling with sending POST data to my PHP script. 我似乎很难将POST数据发送到我的PHP脚本。

My AJAX sends data (an ID of a blog post) to my PHP script, which then finds the row that contains a matching ID from a database. 我的AJAX将数据(博客帖子的ID)发送到我的PHP脚本,然后该脚本从数据库中查找包含匹配ID的行。

The script then sends back the title of the blog post and the content of the post in an array, which AJAX picks up and inserts into a form in the DOM. 然后,脚本以数组形式发回博客文章的标题和文章的内容,AJAX会拾取该文章并将其插入DOM的表单中。

I can successfully: 我可以成功:

  • insert sample data (for example, if I simply store strings into the array I'm passing back to AJAX, it will successfully insert those strings into the form); 插入示例数据(例如,如果我只是将字符串存储到要传递回AJAX的数组中,它将成功将这些字符串插入表单中); and
  • insert the correct data from the database when a static ID is specified (for example, if I switch out $_POST['editpostid'] and specify the integer 5 instead, the query successfully finds the row with ID = 5 and AJAX inserts this data into the form). 在指定静态ID的情况下,从数据库中插入正确的数据(例如,如果我切换$ _POST ['editpostid']并指定整数5,则查询成功找到ID = 5的行,而AJAX会插入此数据放入表格)。

Therefore, from my point of view, the problem is that the ID is never reaching the PHP script, or my script cannot see the ID inside the JSON object. 因此,从我的角度来看,问题在于该ID从未到达PHP脚本,或者我的脚本无法在JSON对象中看到该ID。

Please take a look at my code and let me know what you think. 请看一下我的代码,让我知道您的想法。 I'm new to all this, so I'd appreciate your feedback - if it fixes the problem or not. 我是所有新手,因此,如果您能解决问题,请多多指教。

Javascript/jQuery: 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:

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

?>

Update - Solution: 更新-解决方案:

Fixed jQuery/Javascript: 固定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

The PHP script remains the same. PHP脚本保持不变。

Many thanks for your help! 非常感谢您的帮助! MrPupper 珀珀

I think you missed the index 'postid' and need to replace this 我认为您错过了索引'postid' ,需要替换它

$postid = $_POST['editpostid'];

with this line : 用这一行:

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

Or instead of sending 或者代替发送

data: { 'editpostid': jsonObj },

send this 发送这个

data: { 'editpostid': oldpostid },

Looking over your code, it seems like you are getting null because you are requesting the fetchpost.php script twice. 查看您的代码,由于您两次请求fetchpost.php脚本,因此您似乎获得了空值。 Once when you contact the script via $.ajax(...); 当您通过$.ajax(...);联系脚本时$.ajax(...); and once more when you call $.getJSON(...); 再次调用$.getJSON(...); . When you contact via $.getJSON(...); 当您通过$.getJSON(...); , though, you are not POST ing data and it seems like your script does not have a properly defined way to handle GET requests, so the script doesn't know how to react and it returns null information. ,但是,您不是POST数据,并且您的脚本似乎没有正确定义的方式来处理GET请求,因此该脚本不知道如何响应,并且返回空信息。

I would change the JavaScript/jQuery to the following: 我将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);
        }
    });
});

Additionally, PHP is going to be expecting an application/x-www-form-urlencoded value to be able to interact with $_POST[...] . 此外,PHP将期望application/x-www-form-urlencoded值能够与$_POST[...]进行交互。 As such, if you want to feed it JSON, then in your PHP, you will need to implement a solution such as: $postedData = json_decode(file_get_contents('php://input')); 这样,如果要向其提供JSON,则在PHP中,您将需要实现以下解决方案: $postedData = json_decode(file_get_contents('php://input')); (See more about that in this answer ; for more about json_decode , see the official PHP documentation for json_decode. ) (有关更多信息,请参json_decode 答案 ;有关json_decode更多信息,请参见json_decode 的官方PHP文档。


Note: While outside of the scope of your question, and you may know this already, I find it important to point out that your MySQL is insecure and vulnerable to SQL injection due to just blindly trusting that the postId has not been tampered with. 注意:虽然不在您的问题范围内,并且您可能已经知道这一点,但我发现有必要指出,您的MySQL不安全且容易受到SQL注入的攻击,因为仅仅盲目地相信postId未被篡改。 You need to sanitize it by saying $postid = $dbconnect->real_escape_string($postid); 您需要通过说$postid = $dbconnect->real_escape_string($postid);来清理它$postid = $dbconnect->real_escape_string($postid); after you initialize $dbconnect and connect to the database, but before you put the $postid into your SQL query string. 在初始化$dbconnect并连接到数据库之后,但在将$postid放入SQL查询字符串之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM