There are a lot of similar questions out there, but my issue is a little bit more complicated.
I have a table called movies
from which I am displaying data in a loop using the code below:
<?php
// LISTS MOVIES ORDERED BY RELEASE DATE -- LATEST MOVIES BY YEAR.
$stmt = $connect->prepare("SELECT id, title, releaseDate, posterUrl FROM movies ORDER BY releaseDate DESC LIMIT 4");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($movieId, $movieTitle, $movieDate, $moviePoster);
while ($stmt->fetch()) { ?>
<div class="index-movie">
<div class="meta-container">
<img src="<?php echo $moviePoster; ?>" alt="<?php echo $movieTitle; ?>" class="poster">
<div class="meta">
<span class="title"><?php echo $movieTitle . ' (' . substr($movieDate, 0, 4) . ')'; ?></span>
</div>
</div>
<form method="POST" class="watchlist-form">
<input type="text" name="watchlist-movie-id" style="display: none;" class="watchlist-movie-id" value="<?php echo $movieId; ?>">
<input type="submit" class="add-to-watchlist" value="Add to Watchlist" name="add-to-watchlist">
</form>
</div>
<?php
}
$stmt->free_result();
$stmt->close();
?>
This loop displays four entries from the movies
table. When the user clicks the .add-to-watchlist
button, the movie is to be added to the user's list. I have a two separate tables users
for users and watchlist
for the junction table between users
and movies
.
My question is, how do I implement a function so that I can add the "specific" movie from the list of four to the user's list? For fetching the movieId
I echoed that into a hidden input field, but still can't get that to work.
My jQuery code is:
$('.add-to-watchlist').on('click', function(e) {
e.preventDefault();
var data = $(this).parent().find('.watchlist-movie-id').val();
$.ajax({
type: 'POST',
url: 'includes/watchlist.php',
dataType: 'text',
data: data,
success: function() {
$(this).hide();
},
error: function(error) {
alert(error);
}
});
});
And watchlist.php
is:
<?php
require('includes/config.php');
require('includes/auth.php');
$defaultId = 'DEFAULT';
$currentDate = 'now()';
$movieId = $_POST['watchlist-movie-id'];
$stmt = $connect->prepare("INSERT INTO watchlist (id, date, userId, movieId) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssii", $defaultId, $currentDate, $currentUser, $movieId);
$stmt->execute();
$stmt->close();
?>