duandan4680 2017-07-24 17:14
浏览 92
已采纳

如何使用PHP + Ajax插入数据MySQL [关闭]

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();
?>
  • 写回答

1条回答 默认 最新

  • doudu2404 2017-07-24 19:41
    关注

    The main issue I see is that your AJAX data field needs to be an object, otherwise the $_POST value will only contain a key with the value submitted.

    var data = 'hi';
    
    $.ajax({
       data: data
    });
    
    var_dump($_POST);
    
    array(1) {
      ["hi"]=>
      string(0) ""
    }
    

    You should update your code to something like this, to get your expected result.

    var movieId = $(this).parent().find('.watchlist-movie-id').val();
    
     $.ajax({
         //...
         data: {
            'watchlist-movie-id': movieId,
         },
         //...
      });
    

    Otherwise you can submit the entire form using:

    $.ajax({
       //...
        data: $(this).parent().serialize(),
       //...
    });
    

    I also suggest removing the hidden form field element and just use a <button> element instead, to make your life simpler.

    <button type="submit" name="watchlist-movie-id" value="<?php echo $movieId; ?>">Add to Watchlist</button>
    

    Then you can update your javascript to.

    $('button[name="watchlist-movie-id"]').on('click', function(e){
         e.preventDefault();
         var movieId = $(this).val();
         $.ajax({
           //...
            data: {
              'watchlist-movie-id': movieId,
           },
           success: function() {
                 $(this).hide();
           },
           //...
        });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?