0

I seem to be struggling with sending POST data to my PHP script.

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.

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.

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

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.

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:

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

?>

Update - Solution:

Fixed 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.

Many thanks for your help! MrPupper

StuTheWebGuy
  • 11
  • 1
  • 6
  • Thanks for all the answers! I used a combination of both Farzad and Spencer's suggestions to fix it, including my own research using the PHP docs. I've updated my original question to include the solution. – StuTheWebGuy Dec 08 '16 at 07:33

2 Answers2

1

I think you missed the index 'postid' and need to replace this

$postid = $_POST['editpostid'];

with this line :

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

Or instead of sending

data: { 'editpostid': jsonObj },

send this

data: { 'editpostid': oldpostid },
Farzad Salimi Jazi
  • 760
  • 10
  • 25
  • Thanks for your reply Farzad. I have my code working now, and it was due to a number of errors that both Spencer and yourself helped me find. I found that your second suggestion worked for me, and I scrapped the array altogether. I appreciate the help! :) – StuTheWebGuy Dec 08 '16 at 07:27
  • @MrPupper More than happy to help :) – Farzad Salimi Jazi Dec 08 '16 at 07:51
0

Looking over your code, it seems like you are getting null because you are requesting the fetchpost.php script twice. Once when you contact the script via $.ajax(...); and once more when you call $.getJSON(...);. When you contact via $.getJSON(...);, though, you are not POSTing 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.

I would change the JavaScript/jQuery to the following:

// 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[...]. 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')); (See more about that in this answer; for more about json_decode, see the official PHP documentation for json_decode.)


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. You need to sanitize it by saying $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.

Spencer D
  • 3,376
  • 2
  • 27
  • 43
  • Many thanks Spencer, my code is now working! The code itself was broken in a few places, which both Farzad and yourself helped fix. I also found that removing the line containing JSON.parse() entirely allowed my code to work. With regards to your note about SQL security, I am fully aware and I thank you for the reminder. This code is for a university assignment project and will not be released as production code, and thus we are not expected to cover these security aspects. However, I've taken note of your comment for future projects, and I appreciate the feedback you've given me! :) – StuTheWebGuy Dec 08 '16 at 07:31
  • @MrPupper, ah, I wasn't sure if `JSON.parse` would be necessary or if the jQuery library would automatically convert it to an object because `dataType` was specified. And I figured you probably knew about the SQLi vulnerability, but I always try to point it out when I see it, so someone doesn't release code vulnerable code that could jeopardize their users/customer :P Anyway, glad to be of help. Good luck with your studies. – Spencer D Dec 08 '16 at 23:21