添加一个收藏夹按钮,用PHP中的值更新mysql数据库,无需重新加载页面[重复]

This question already has an answer here:

I've got a page which will randomly select a number of images from the database, and display a favourite button next to them. I guess the easy way would be to post the ID in the URL, and insert it into the database on page reload (then reload again to take it out the URL). Although, unless I add some sort of seed into the random select, on reload entirely new images will be selected, which obviously is not good if you were planning on favoriting more than one image on the page.

The other way I'd know how would be to open a new page in a tab, insert the ID into the database, and close the page, although I know it could be a lot better though, so would anyone have an example of how to make the link update the mysql table without leaving the page?

There is jquery running on the site, but I only know a little javascript from figuring bits out, so it'd be great if I could have something basic to work on. I can most likely get the font colour to change and all, just need help with the mysql bit.

Not that it really matters, but the table is only FavID, UserID, ImgID and Date

Also, I've had a quick look at this - How to update a mysql database without reloading page, is that for posting the ID to another page to run without the user being redirected? Will it also have the session variables or should I post the required ones through too?

Thanks

</div>

With AJAX !

if ((isset($_POST['Action'])) && (substr($_POST['Action'], 0, 11) == "AJAX_Update")) {
    $id = substr($_POST['Action'], 11);
    // Update SQL
    $query = "...";
    @$result = mysqli_query($query);
    if ($result) { print "OK"; } else { print "Error !"; }
    die();
}

(...)

$id = 5; // Example
print "<img src='update.png' style='cursor:pointer' onClick='AJAX_Update($id);'>"; print "<span id='result'></span>";

(...)

?>

<script language='JavaScript'>

            function AJAX_Update(id) {
                xhr = new XMLHttpRequest();
                xhr.onreadystatechange = function() {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        document.all['result'].innerHTML = 'Update result : ' + xhr.responseText;
                    }
                }
                xhr.open("POST", "<?php print "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; ?>", true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.send("Action=AJAX_Update" + id);
            }

</script>