-2

I'm trying to create a sorting/order mechanism for posts on my website, either sorting by newest or hotest. I have a HTML <select> element on my frontpage.php that triggers via a jQuery onChange to save the selected options value into a variable. It then runs a GET request to the file feed.php with the value of the selected option. This dosen't now show anything. The error: Notice: Undefined index: order in the feed.php file.

<select id="order">
  <option value="published">Newest</option>
  <option value="votes">Hottest</option>
</select>

The jQuery that checks for a change and then saves the select #order childs value in the variable selected.

$('#order').change(function() { 
    var selected = $(this).children("option:selected").val();
    $.ajax({
        type: 'GET',
        data: {order: selected},
        url: '../../php/includes/posts/feed.php'
    });
});

Then I have the PHP script (feed.php) that outputs the posts with a while-loop (not included in this question.) The while-loop works as it should otherwise. I would want to change the order of the SQL table asynchronously.

$order = $_GET['order'];
if(isset($order)) {
    $sql = "SELECT * FROM posts ORDER BY '$order' DESC LIMIT 0, 5";
    $results = $conn->query($sql);
    // The php script continues but it works as it should without the code above of course.

Is this maybe due to that the $order isn't saved before use on feed.php?

EDIT:

This is the entire code for feed.php I've now changed the code for bth feed.php and my jQuery script to include the changes that were given

    if(isset($order)) {
    $order = $_GET['order'];
    $sql = "SELECT * FROM posts ORDER BY `$order` DESC LIMIT 0, 5";
    $results = $conn->query($sql);

    if ($results->num_rows > 0) {
        while($row = $results->fetch_assoc()) {
            $postID = $row['postID'];
            $author = $row['author'];
            //$img    = $row['fileName'];

            $published   = strtotime($row['published']);

            echo '
            <div class="post"> 
                <div class="post__head">
                    <div>
                        <h6>'.$row['title'].'</h6>
                        <p> <i class="far fa-user"></i> '.$author.'</p>
                        <p> <i class="far fa-clock"></i> '.date("j.n.Y - H:i:s", $published).'</p>
                    </div>

                    <div class="post__votes">
                        <p>'.$row['votes'].' Votes</p>
                        <i data-id="'.$postID.'" class="fas fa-arrow-up -upvote"></i>
                        <i data-id="'.$postID.'" class="fas fa-arrow-down -downvote"></i>
                    </div>
                </div>

                <div class="post__body">
                    <div class="post__img">

                    </div>

                    <p>'.$row['message'].'</p>

                    <div class="post__comments">
                        <p>Comments</p>';

                        $sqlComments     = "SELECT * FROM comments WHERE comments.postID = $postID"; // Loop through all comments for a given post
                        $resultsComments = $conn->query($sqlComments);

                        if($resultsComments->num_rows > 0){
                            while($row = $resultsComments->fetch_assoc()) {
                                echo $row['comment'] . '<br>';
                            }

                        } else {
                            echo 'No comments yet...';
                        } 
                    echo' 
                    </div>   
                </div>

                <div class="post__footer">';
                    if(isset($_SESSION["loggedin"])) {
                        $role = $_SESSION['role'];

                        if($role == 'admin' || $role == 'editor' || $author == $_SESSION['username']) { # Edit posts only if logged in and as a either admin, editor or as the user who created the post
                            echo '
                            <button type="button" class="post__editBtn" data-id="'.$postID.'">Edit <i class="fas fa-pencil-alt"></i></button> 
                            <button type="button" class="post__commentBtn" data-id="'.$postID.'">Comments <i class="fas fa-comments"></i></button>';
                        }

                        if($role == 'admin' || $author == $_SESSION['username']) { # Delete posts only if logged in as a admin or the author of the post
                            echo'
                            <form method="post"> 
                                <input type="hidden" value="'.$postID.'" name="post__deleteHidden">
                                <button name="post__deleteBtn">Delete <i class="far fa-trash-alt"></i></button>
                            </form>';
                        }
                    } 
                echo'</div>
            </div>';
        }

        echo ' 
        <div class="overlay-edit">
            <p>Editing </p>
            <form method="post" action="../../php/includes/posts/editPost.php" class="post__edit">
                <input type="text" name="postTitle" placeholder="Edit title">
                <textarea name="postMsg" maxlength="255" placeholder="Edit message"></textarea>
                <button type="submit">Edit Post</button>
                <button type="button" class="post__edit-close">Close</button>
                <input type="hidden" name="post__editHidden" value="">
            </form>
        </div>';

        echo'
        <div class="overlay-comment">
            <form method="post" action="../../../php/includes/posts/createComment.php" class="post__comment">
                <textarea name="comment" maxlength="255" placeholder="Comment"></textarea>
                <button type="submit">Submit comment</button>
                <button type="button" class="post__comment-close">Close</button>
                <input type="hidden" name="post__commentHidden" value="">
            </form>
        </div>';

        if(isset($_POST['post__deleteBtn'])) { # Delete a post
            $conn->query("DELETE * FROM posts WHERE postID = ".$_POST['post__deleteHidden']."");
        }

    } else {
        echo '<p>No posts to show...</p>';
    }
}

$conn->close();
?>
11
  • Have you debugged this to check if the value is missing in the JS, and so not sent in the request, or only the PHP? Feb 25, 2020 at 17:01
  • I can console.log(select) to view the values of the options. And prior to this I had a success: function wich alerted that the $.ajax worked. Feb 25, 2020 at 17:03
  • use data: "order="+selected, and do not forget to prepare/bind/exec at server side to avoid SQL injections Feb 25, 2020 at 17:06
  • @MaximSagaydachny Hi tried it out but to no success. Feb 25, 2020 at 17:12
  • 2
    '$order' < remove the quotes from that. We're dealing with a column and not a string value from in db. Feb 25, 2020 at 17:13

3 Answers 3

0

For the select list I would add a Select order option

<select id="order">
  <option value="none">Select order</option>
  <option value="published">Newest</option>
  <option value="votes">Hottest</option>
</select>

Then I would check if the selected option is different than the default one

$('#order').change(function() { 
    var selected = $(this).children("option:selected").val();
    if(selected != "none") {
      $.ajax({
        type: "get",
        url: "../../php/includes/posts/feed.php",
        data: { 
          order: selected
        },
        success: function(response) {
          //Do Something
        },
        error: function(xhr) {
          //Do Something to handle error
        }
      });
    }
});

Make sure the url of the feed.php is correct.

Run your feed.php script and make sure it returns a result.

4
  • Thx for the answer, I tried to change my code and the error function get thrown when I add a console.log to it... Feb 25, 2020 at 17:43
  • I run the JS script and it works fine. As I said earlier, make sure you are calling the correct php file and the latter does execute without errors
    – toh19
    Feb 25, 2020 at 17:58
  • Notice: Undefined index: order in feed.php refering to the top of the file (feed.php) $order = $_GET['order']; Feb 25, 2020 at 17:58
  • console.log(selected) right before $.ajax and make sure it logs one of these values: none, published or votes
    – toh19
    Feb 25, 2020 at 18:03
-1

You don't need to get option's value, get select's value instead

$('#order').change(function() { 
    var selected = $(this).val(); // change to select val, not children
    $.ajax({
        type: 'GET',
        data: {order: selected},
        url: '../../php/includes/posts/feed.php'
    });
});
5
  • Thx. But it didn't fix the problem. Feb 25, 2020 at 17:11
  • try to log to console what is the result of console.log(selected) ? Feb 25, 2020 at 17:14
  • Works fine, outputs the values of the select Feb 25, 2020 at 17:18
  • Good, also follow @Funk Forty Niner comment and remove quotes in your SQL query, change to ORDER BY $order Feb 25, 2020 at 17:19
  • 1
    Not my DV, but I am thinking about putting one because making this change doesn't solve the OP's problem. You can still do the traversal and get the values. There are several things wrong, but the most important one is that selected doesn't get set with a default value if the user never changes the drop-down. So, minus any other problems (of which there are several) the PHP variable will be undefined if the form is submitted without making the change. Feb 25, 2020 at 19:30
-1

Foreword: I am a serverside coder, not JS/jQuery, therefore this answer is for that.

You're getting the undefined index notice because you need to place the $order = $_GET['order']; inside the conditional statement. Plus, removing the quotes around the column name in your ORDER BY. Either remove them or use ticks.

if(isset($order)) {

$order = $_GET['order'];

$sql = "SELECT * FROM posts ORDER BY $order DESC LIMIT 0, 5";
$results = $conn->query($sql);

} else {
  echo "It is not set.";
 }

With ticks:

$sql = "SELECT * FROM posts ORDER BY `$order` DESC LIMIT 0, 5";

You're open to SQL injection with this, so please use a prepared statement.

Enable error reporting for PHP with the following at the top of your PHP files:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

And mysqli_error($conn) for the queries.

On an added note: DELETE * FROM posts is incorrect syntax to delete a row in MySQL. The * (asterisk) should not be part of DELETE; it's only used for a SELECT statement.

Plus, I have been told by a colleague of mine that you should use POST and not GET in your AJAX function.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.