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

如何使用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();
?>

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();
       },
       //...
    });
});