skip to Main Content

I got a while loop, and inside that loop i got another while loop that i only want to run after button.click

My javascript code inside profile.php:

$('.commentbtn').click(function()
{
    $.ajax({
        url: 'includes/functions.inc.php',
        type: 'GET',
        data: {
            'offset': 0,
            'limit': 3
        },
        success: function(data)
        {}
    });

My php code inside functions.inc.php:

function getProfilePostModals($conn)
{
    $uid = $_SESSION['userId'];

    $sql = "SELECT * FROM posts WHERE uid=$uid AND type=1";
    $query = mysqli_query($conn, $sql);

    while ($postrow = $query->fetch_assoc()) 
    {
        $pid = $postrow['pid'];

        //// some code for the posts /////
        echo "<input id='opencomments".$pid."' class='commentbtn' type='button' value='Comment'>";

        if (isset($_GET['offset']) && isset($_GET['limit'])) {
            $commentssql = "SELECT * FROM postcomments WHERE pid=$pid";
            $commentsquery = mysqli_query($conn, $commentssql);

            while ($commentrow = $commentsquery->fetch_assoc())
            {
                //// some code for the comments that i want to run after "offset" and "limit" isset
            }
        }
    }
}

Everything was working fine before I started adding the if(isset).
But now the comments are not coming up anymore. What I want to do is to make a load on scroll function for the comments, I know its not complete code for that yet, I just try to see if I can get the isset to work first. Thank you in advance, I’m still learning.

UPDATE:
The functions.inc.php got more than 1 function inside it, and inside my profile.php I have this code to get everything to:

<?php include 'includes/functions.inc.php'; ?>
<?php getProfilePostModals($conn);?>

I don’t know if this information helps or not.

** NEW UPDATE:**

getcomments.inc.php:

<?php if (isset($_GET['offset'])) {
    require 'dbh.inc.php';
    $pid = $_GET['pid'];

$commentssql = "SELECT * FROM postcomments WHERE pid=$pid";
$commentsquery = mysqli_query($conn, $commentssql);
while ($row = $commentsquery->fetch_assoc()) {
    $commentuid = $row['uid'];
    $pcid = $row['pcid'];
    $commentpid = $row['pid'];
    $commentdate = $row['date'];
    $comment = $row['postcomment'];

    $usersql = "SELECT * FROM users WHERE id=$commentuid";
    $userquery = mysqli_query($conn, $usersql);
    $userrow = $userquery->fetch_assoc();
    $commentimage = $userrow['imageUsers'];
    $ctusername = $userrow['uidUsers'];

    echo "<div id='deletecomment".$pcid."' class='deletecommentverify'>
    <form action='includes/deletecomment.inc.php' method='POST' runat='server' name='deletepost_form'>
        <h3>Are you sure you want to delete this comment?</h3>
        <input type='hidden' name='pcid' value='".$pcid."'>
        <button class='deletecommentbtn' type='submit' name='deletecomment_submit'>Yes</button>
        <input id='closedeletecomment".$pcid."' class='closedeletecomment' type='button' value='No'>
    </form>
</div>
    <div class='commentbox' id='commentbox".$pcid."'>
            <img class='usercommentimage' src='images/".$commentimage."'>
            <input type='hidden' name='commentuid' value='".$commentuid."'>
            <p><a href='profile.php'>".$ctusername." </a> ".$comment."</p>";
            if ($commentuid == $_SESSION['userId']) {
                echo "
            <span class='deletecommenticon' id='opendeletecomment".$pcid."'></span>";
            }
            echo "
            <div class='comment_info'>
                <span class='comment_count'>".$commentdate."</span>
            </div>

        </div>
        ";
}
}

And I made a test.php just to try it out with this code:

<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
session_start();
include 'includes/dbh.inc.php';
include 'includes/functions.inc.php';
include 'includes/like.inc.php';
include 'includes/getcomments.inc.php';
date_default_timezone_set('Europe/Copenhagen');
if (!isset($_SESSION['userId'])) {
    header("Location: login.php");
}
?>

<!DOCTYPE html>
<html>

<head>
    <title>Beautytrends</title>
    <link href="https://fonts.googleapis.com/css?family=Mali|Raleway&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/fontawesome.min.css">
    <link href="css/style.css" type="text/css" rel="stylesheet">
    <link rel="icon" href="images/notext-logo.png">
</head>

<body>


  <input id='181' class='commentbtn' data-id='181' type='button' value='Comment'>
    <div id="profile-content">



    </div>



<script src="js/jquery-3.4.1.min.js"></script>


<script>



$(document).ready(function(){



                $('.commentbtn').click(function(){
                    var pid = $(this).attr("id")
                    $.ajax({
                        url: 'test.php',
                        type: 'GET',

                        data: {
                            'offset': 0,
                            'limit': 3,
                            'pid' = pid

                        },
                        success: function(data){
                            $('#profile-content').append(data);}


                        }

                    });
                });

            });

</script>

</body>
</html>

But it’s still not working. I tried to put ‘includes/getcomments.inc.php?offset=0&limit=3&pid=181’ in the browser and then everything comes up, so its like the ajax dont send the GET data to getcomments.

2

Answers


  1. Here are my comments and suggestions to help solve the issues you’re having.

    I don’t understand what you’re trying to do here, but $(this) refers to the button itself which doesn’t seem like what you need. I don’t see that you’re actually using the variable either.

    $('.commentbtn').click(function()
    {
        $post = $(this);
    

    You need to do something with the response you receive. Until you get everything working I would recommend the following. Then you can just check the browser console for any output that was sent from the server.

    success: function(data)
            {console.log(data);}
    

    You’re referring to the wrong variable name, $row should be $postrow. This is going to cause an error because ['pid'] index doesn’t exist.

    while ($postrow = $query->fetch_assoc()) 
        {
            $pid = $row['pid'];
    

    For this bit, you need to do something if the variables are not set, such as send back a response, otherwise you’ll never know what went wrong. Also, as stated in the comments, NEVER access user provided data directly without first validating/sanitizing it and use prepared statements for your queries.

    if (isset($_GET['offset']) && isset($_GET['limit'])) {
        $commentssql = "SELECT * FROM postcomments WHERE pid=$pid";
        $commentsquery = mysqli_query($conn, $commentssql);
    
        while ($commentrow = $commentsquery->fetch_assoc())
        {
            //// some code for the comments that i want to run after "offset" and "limit" isset
        }
    } else {
        echo "Expected $_GET values not received";
    }
    

    Finally, you have no way of knowing if your queries fail because you have no error handling. This is something you need to implement into your code.

    Login or Signup to reply.
  2. First thing you want to do is load jquery in your head section rather than the middle of the page:

    <head>
        <title>Beautytrends</title>
        <link href="https://fonts.googleapis.com/css?family=Mali|Raleway&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/fontawesome.min.css">
        <link href="css/style.css" type="text/css" rel="stylesheet">
        <link rel="icon" href="images/notext-logo.png">
        <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    </head>
    

    Then you can replace your button

    <input id='181' class='commentbtn' data-id='181' type='button' value='Comment'>

    with

    <div class="button-holder">
      <!-- We set the initial value 1 because we want only 1 results at a time -->
      <input type="hidden" id="result_no" value="1">
      <input type="button" class="button btn-md btn-success load-button" id="loadmore" value="Load More Results">
    </div>
    

    The benefit of this button setup is it stores a variable saying which record to load (result_no) which you can use in your query.

    Your javascript can be replaced by this code:

    <script type="text/javascript">
    $(document).ready(function(){
     $("#loadmore").click(function(){
      loadmore();
     });
    });
    
    function loadmore()
    {
     var val = document.getElementById("result_no").value;
     $.ajax({
     type: 'post',
     url: 'load_more.php',
     data: {
      getresult:val
     },
     success: function (response) {
      var content = document.getElementById("profile-content");
      content.innerHTML = content.innerHTML+response;
    
      // We increase the value by 1 because we limit the results by 1
      document.getElementById("result_no").value = Number(val)+1;
     }
     });
    }
    </script>
    

    Offset is replaced by result_no so your other code will only change slightly. Make sure this is its own php file named load_more.php (if you want to change the name of the file change it in the javascript as well):

    <?php if (isset($_GET['result_no'])) {
        require 'dbh.inc.php';
        $pid = $_POST['result_no'];
    
    $commentssql = "SELECT * FROM postcomments WHERE pid=$pid";
    $commentsquery = mysqli_query($conn, $commentssql);
    while ($row = $commentsquery->fetch_assoc()) {
        $commentuid = $row['uid'];
        $pcid = $row['pcid'];
        $commentpid = $row['pid'];
        $commentdate = $row['date'];
        $comment = $row['postcomment'];
    
        $usersql = "SELECT * FROM users WHERE id=$commentuid";
        $userquery = mysqli_query($conn, $usersql);
        $userrow = $userquery->fetch_assoc();
        $commentimage = $userrow['imageUsers'];
        $ctusername = $userrow['uidUsers'];
    
        echo "<div id='deletecomment".$pcid."' class='deletecommentverify'>
        <form action='includes/deletecomment.inc.php' method='POST' runat='server' name='deletepost_form'>
            <h3>Are you sure you want to delete this comment?</h3>
            <input type='hidden' name='pcid' value='".$pcid."'>
            <button class='deletecommentbtn' type='submit' name='deletecomment_submit'>Yes</button>
            <input id='closedeletecomment".$pcid."' class='closedeletecomment' type='button' value='No'>
        </form>
    </div>
        <div class='commentbox' id='commentbox".$pcid."'>
                <img class='usercommentimage' src='images/".$commentimage."'>
                <input type='hidden' name='commentuid' value='".$commentuid."'>
                <p><a href='profile.php'>".$ctusername." </a> ".$comment."</p>";
                if ($commentuid == $_SESSION['userId']) {
                    echo "
                <span class='deletecommenticon' id='opendeletecomment".$pcid."'></span>";
                }
                echo "
                <div class='comment_info'>
                    <span class='comment_count'>".$commentdate."</span>
                </div>
    
            </div>
            ";
    }
    }
    

    I’ve never used MySQL so I can’t test it with that. However, this works with a different query using Postgres so it should work fine here if your query is valid.

    Any problems, just let me know. This also doesn’t solve your injection attack issues but you can solve those later.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search