这里有很多类似的问题,但我的问题有点复杂。如何使用PHP + Ajax插入数据MySQL
我有一个名为movies
从我在循环中使用下面的代码显示数据表:
<?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();
?>
此循环显示从movies
表四个条目。当用户点击.add-to-watchlist
按钮时,电影将被添加到用户的列表中。我有两个单独的表users
为用户和watchlist
为users
和movies
之间的交界表。
我的问题是,我该如何实现一个函数,以便我可以将四个列表中的“特定”电影添加到用户列表中?为了获取movieId
,我将其转换为隐藏的输入字段,但仍然无法使其工作。
我jQuery代码是:
$('.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);
}
});
});
而且watchlist.php
是:
<?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();
?>
注意:'$ currentDate ='now()';'为什么不直接在查询中传递它呢?特别是有一个原因,为什么你这样做? –
[你是否观看过浏览器开发工具中的AJAX请求/响应?你有没有在项目中包含jQuery库?是否有任何错误报告?你在网络服务器上运行它吗?](http://jayblanchard.net/basics_of_jquery_ajax.html) –
哪里是$ currentUser? –