Reputation: 1009
Trying to delete a record by using JQuery/Ajax function so that my page will not reload everytime I delete. I have a Movie.php that serves as a model object for Movie and this is where I put the function called delete_movie to delete based on movieId parameter. I have tried to call it inside my Jquery call but it looks like it is not calling my function delete_movie(movieId).
This is my Movie.php
<?php
class Movie {
public static function delete_movie($movieId) {
$db = Database::getDB();
$query = 'DELETE FROM MOVIE
WHERE movieId = :movieId';
$statement = $db->prepare($query);
$statement->bindValue(':movieId', $movieId);
$statement->execute();
$statement->closeCursor();
}
}
?>
movielist.php
<tr class="delete_mem<?php echo $movie['movieId'];?>">
<td><?php echo $movie['title']; ?> </td>
<td><?php echo $movie['releaseYear']; ?></td>
<td><?php echo $movie['imdbId']; ?></td>
<td><?php echo $movie['description']; ?></td>
<td><button type="submit" class="btn btn-danger" id="<?php echo $movie['movieId'];?>">Delete</button></td>
</tr>
JQScript.js
$(document).ready(function() {
$('.btn-danger').click(function() {
var id = $(this).attr("id");
if (confirm("Are you sure you want to delete this?")) {
$.ajax({
type: "POST",
url: "model/Movie.php",
data: {
delete_movie : id
},
success: function() {
alert('Success deletion!');
}
});
} else {
return false;
}
});
});
Upvotes: 0
Views: 1147
Reputation: 166
You cannot call PHP code from JavaScript (not easily, at least). Fortunately for you, you can do what you're trying to achieve because you're sending a POST
message to Movie.php
. All that you have to do now is to handle that POST
message in Movie.php
.
<?php
class Movie {
public static function delete_movie($movieId) {
$db = Database::getDB();
$query = 'DELETE FROM MOVIE
WHERE movieId = :movieId';
$statement = $db->prepare($query);
$statement->bindValue(':movieId', $movieId);
$statement->execute();
$statement->closeCursor();
}
}
// add this
if (isset($_POST["delete_movie"])) {
Movie.delete_movie($_POST["delete_movie"]);
}
?>
I suggest you don't forget to add authentication. Otherwise, anyone can delete any movie from your database. Try adding a session
. That's outside the scope of this question, though.
Upvotes: 0
Reputation: 780
When PHP is running movie.php
, it's just processing the class. The PHP within the file doesn't actually say to do anything.
If you don't need classes, you could just change your movie.php
to
$db = Database::getDB();
$query = 'DELETE FROM MOVIE
WHERE movieId = :movieId';
$statement = $db->prepare($query);
$statement->bindValue(':movieId', $movieId);
$statement->execute();
$statement->closeCursor();
If there's more in the file or you must use classes, then you need a controller that receives the url POST, and then calls Movie::delete_movie($id)
.
You appear to be following the MVC pattern, the model and view you have, and adding this controller to control the actions, would be the final part.
Upvotes: 1