search

Home  >  Q&A  >  body text

How to solve the problem of not being able to access the $_POST value when using the $.post method

<p>I'm having a lot of trouble sending data from one page to another. I'm developing a movie website that displays movies on the homepage and when I click on a movie I want to access the movie details page with reviews. In fact, I want to send the movie ID to the movie-detail.php page because I want to filter the comments related to that movie in the comments section of the movie detail page. This is the movie poster in the homepage, created by using append in a js file, when I click on it: </p> <pre class="brush:php;toolbar:false;"><div class="movie-poster" onclick="loadComments(${movie.id})" data-movie-id="${movie .id}">... ...</pre> <p>It triggers this function: </p> <pre class="brush:php;toolbar:false;">function loadComments(movieId){ $.post("/web/action/show-comments.php", { movieId }); }</pre> <p>This is show-comments.php:</p> <pre class="brush:php;toolbar:false;"><?php include "../../db/db_conn.php"; if(!isset($_SESSION)) session_start(); if(isset($_POST['movieId'])) $movieId = $_POST['movieId']; $userId = $_SESSION['id']; $sql = "SELECT * FROM reviews WHERE movie_id="."$movieId"; #WHERE movie_id="."$movieId"; $result = pg_query($conn,$sql); while ($row = pg_fetch_row($result)) { ?> <div style="background-color: #aaa; padding: 8px 16px; margin: auto; margin-bottom: 8px; border:1px solid black; border-radius:10px; border-left:4px solid black; width: 80%;"> <hr style="opacity:0.9"> <p style="background-color: gray; padding: 16px; border-radius:10px">Commenter:<?php echo "$row[2]" ?></p> <hr style="opacity:0.9"> <p> <?php echo "$row[1]" ?></p> </p> <hr style="opacity:0.9"> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star checked"></span> <span class="fa fa-star"></span> <span class="fa fa-star"></span> <hr style="opacity:0.9"> </div> <?php } ?></pre> <p><code>show-comments.php</code> is included in the comments section div of the <code>movie-detail.php</code> page, but when I try to enter the page, it Always gives me undefined array key error regarding $movieId variable. The only thing I need is the movie ID. I've tried many things, using cookies and hiding input fields, but none seem to work, always giving me this error. I tried printing the <code>$_POST</code> array but it was empty. What did i do wrong? </p>
P粉043432210P粉043432210509 days ago593

reply all(1)I'll reply

  • P粉764836448

    P粉7648364482023-08-16 09:42:02

    Try the following methods and correct them if there are any errors. I think you are not using the $.post() function correctly because the movieId is not properly formatted as a key value pair. Please try the following methods

    function loadComments(movieId) {
      $.post("/web/action/show-comments.php", { movieId: movieId });
    }

    reply
    0
  • Cancelreply