I'm having some problems with ajax (have never been working with it). I would like to delete the selected row from the tabel without refreshing the page, and without creating a new file for the query. I'd like to keep all functions in the functions.php if possible?
I have 3 files here.
index file:
$res = articles($db);
foreach($res as $res){
$id = $res['article_id'];
echo "<form action='' method='post'>";
echo "<input type=hidden" name='delete' value="<?php echo $id;?>">
echo "<input type='submit' name='delete_article'>";
echo "</form>";
}
the ajax call
$.ajax({ url: 'HERE I WANT TO RUN THE DELETE FUNCTION FROM FUNCTIONS.PHP',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
the function
function delete_article($db){
$id = $_POST['delete'];
$sql = "DELETE FROM articles WHERE article_id = :article_id";
$stmt = $db->prepare($sql);
$stmt->bindValue(':article_id',$id);
$stmt->execute();
}
I think that a good approach would be to use REQUEST_METHOD.
php
switch (strtolower($_SERVER['REQUEST_METHOD'])) {
case "post":
someFunctionToSave($_GET["postId"]);
break;
case "get":
someFunctionToRetrieve($_GET["postId"]);
break;
case "delete":
someFunctionToDelete($_GET["postId"]);
break;
default:
break;
}
js
function deletePost (id) {
$.ajax({ url: 'function.php?postId=' + id,
data: {},
type: 'delete',
success: function(data) {}
})
}
function savePost (id) {
$.ajax({ url: 'function.php?postId=' + id,
data: {},
type: 'post',
success: function(data) {}
})
}
function getPost (id) {
$.ajax({ url: 'function.php?postId=' + id,
data: {},
type: 'get',
success: function(data) {}
})
}