Reputation: 362
I want to pass the id in posts.php with ajax and here in href i want to put "#".
When this link gets clicked, It goes to that link. But I dont want to go that link and at a same time i need to pass the id in posts.php.
How can I do this?
<li><a href="posts.php?id=<?=$post_id?>" >post</a></li>
Upvotes: 2
Views: 52
Reputation: 4378
Could do something like this:
HTML:
<li><button type="button" id="pass-data" data-postid="<?= $post_id; ?>">Click me</button></li>
jQuery:
$("#pass-data").click(function(){ // on button click
var dataid = $(this).attr("data-postid"); // get post id
$.ajax({
method: "POST",
url: "posts.php", // page to post data to
data: { id: dataid }, // the post_id (you can access it with $_POST["id"])
success: function(){ // if successful
alert("Success!"); // alert "success!"
}
});
});
Upvotes: 2
Reputation: 177691
Like this - note the preventDefault that stops the link:
<li><a class="postLink" href="posts.php?id=<?=$post_id?>" >post</a></li>
$(function() {
$(".postLink").on("click",function(e) {
e.preventDefault(); // cancel link
$.post(this.href,function(data) {
console.log("Posted the link, returned:",data);
});
});
});
OR
<li><a class="postLink" href="#" data-id="<?=$post_id?>">post</a></li>
$(function() {
$(".postLink").on("click",function(e) {
e.preventDefault(); // cancel link
$.post("posts.php",{"id":$(this).data("id")},function(data) {
console.log("Posted the link, returned:",data);
});
});
});
Upvotes: 1