Created
July 3, 2021 14:40
-
-
Save steveshead/ff250965820a09a60cafd74d9be58946 to your computer and use it in GitHub Desktop.
[Ajax - favorite a blog post ] - Using ajax to update without page refresh
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
session_start(); | |
if(!isset($_SESSION['favorites'])) { $_SESSION['favorites'] = []; } | |
function is_ajax_request() { | |
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && | |
$_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'; | |
} | |
if(!is_ajax_request()) { exit; } | |
// extract $id | |
$raw_id = isset($_POST['id']) ? $_POST['id'] : ''; | |
if (preg_match("/blog-post-(\d+)/", $raw_id, $matches)) { | |
$id = $matches[1]; | |
// store in $_SESSION['favorites'] | |
if (!in_array($id, $_SESSION['favorites'])) { | |
$_SESSION['favorites'][] = $id; | |
} | |
echo 'true'; | |
} else { | |
echo 'false'; | |
} | |
?> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
session_start(); | |
//$_SESSION['favorites'] = []; | |
if(!isset($_SESSION['favorites'])) { $_SESSION['favorites'] = []; } | |
function is_favorite($id) { | |
return in_array($id, $_SESSION['favorites']); | |
} | |
?> | |
<!doctype html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"> | |
<script src="https://kit.fontawesome.com/6b773fe9e4.js" crossorigin="anonymous"></script> | |
<title>Asynchronous Button</title> | |
<style> | |
button.favorite-button:hover, button.unfavorite-button:hover { | |
transition: 0.3s ease-in-out; | |
} | |
button.favorite-button { | |
display: inline; | |
} | |
.favorite button.favorite-button { | |
display: none; | |
} | |
button.unfavorite-button { | |
display: none; | |
} | |
.favorite button.unfavorite-button { | |
display: inline; | |
} | |
.favorite-heart { | |
color: red; | |
font-size: 2em; | |
float: right; | |
display: none; | |
} | |
.favorite .favorite-heart { | |
display: block; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="container py-5"> | |
<div class="row"> | |
<div class="col-lg-6 mx-auto"> | |
<div id="blog-posts"> | |
<div id="blog-post-101" class="blog-post border p-4 my-3 shadow-sm <?php echo(is_favorite(101) ? 'favorite' : ''); ?>"> | |
<span class="favorite-heart">♥</span> | |
<h3>Blog Post 101</h3> | |
<p class="fs-6 fw-light">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed scelerisque nunc malesuada mauris fermentum commodo. Integer non pellentesque augue, vitae pellentesque tortor. Ut gravida ullamcorper dolor, ac fringilla mauris interdum id. Nulla porta egestas nisi, et eleifend nisl tincidunt suscipit. Suspendisse massa ex, fringilla quis orci a, rhoncus porta nulla. Aliquam diam velit, bibendum sit amet suscipit eget, mollis in purus. Sed mattis ultricies scelerisque. Integer ligula magna, feugiat non purus eget, pharetra volutpat orci. Duis gravida neque erat, nec venenatis dui dictum vel. Maecenas molestie tortor nec justo porttitor, in sagittis libero consequat. Maecenas finibus porttitor nisl vitae tincidunt.</p> | |
<button class="favorite-button btn btn-primary">Favorite</button> | |
<button class="unfavorite-button btn btn-primary">Unfavorite</button> | |
</div> | |
<div id="blog-post-102" class="blog-post border p-4 my-3 shadow-sm <?php echo(is_favorite(102) ? 'favorite' : ''); ?>"> | |
<span class="favorite-heart">♥</span> | |
<h3>Blog Post 102</h3> | |
<p class="fs-6 fw-light">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed scelerisque nunc malesuada mauris fermentum commodo. Integer non pellentesque augue, vitae pellentesque tortor. Ut gravida ullamcorper dolor, ac fringilla mauris interdum id. Nulla porta egestas nisi, et eleifend nisl tincidunt suscipit. Suspendisse massa ex, fringilla quis orci a, rhoncus porta nulla. Aliquam diam velit, bibendum sit amet suscipit eget, mollis in purus. Sed mattis ultricies scelerisque. Integer ligula magna, feugiat non purus eget, pharetra volutpat orci. Duis gravida neque erat, nec venenatis dui dictum vel. Maecenas molestie tortor nec justo porttitor, in sagittis libero consequat. Maecenas finibus porttitor nisl vitae tincidunt.</p> | |
<button class="favorite-button btn btn-primary">Favorite</button> | |
<button class="unfavorite-button btn btn-primary">Unfavorite</button> | |
</div> | |
<div id="blog-post-103" class="blog-post border p-4 my-3 shadow-sm <?php echo(is_favorite(103) ? 'favorite' : ''); ?>"> | |
<span class="favorite-heart">♥</span> | |
<h3>Blog Post 103</h3> | |
<p class="fs-6 fw-light">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed scelerisque nunc malesuada mauris fermentum commodo. Integer non pellentesque augue, vitae pellentesque tortor. Ut gravida ullamcorper dolor, ac fringilla mauris interdum id. Nulla porta egestas nisi, et eleifend nisl tincidunt suscipit. Suspendisse massa ex, fringilla quis orci a, rhoncus porta nulla. Aliquam diam velit, bibendum sit amet suscipit eget, mollis in purus. Sed mattis ultricies scelerisque. Integer ligula magna, feugiat non purus eget, pharetra volutpat orci. Duis gravida neque erat, nec venenatis dui dictum vel. Maecenas molestie tortor nec justo porttitor, in sagittis libero consequat. Maecenas finibus porttitor nisl vitae tincidunt.</p> | |
<button class="favorite-button btn btn-primary">Favorite</button> | |
<button class="unfavorite-button btn btn-primary">Unfavorite</button> | |
</div> | |
</div> | |
</div><!-- end column --> | |
</div><!-- end row --> | |
</div><!-- end container --> | |
<script> | |
function favorite() { | |
var parent = this.parentElement; | |
var xhr = new XMLHttpRequest(); | |
xhr.open('POST', 'favorite.php', true); | |
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); | |
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); | |
xhr.onreadystatechange = function () { | |
if(xhr.readyState == 4 && xhr.status == 200) { | |
var result = xhr.responseText; | |
// console.log('Result: ' + result); | |
if(result == 'true') { | |
parent.classList.add("favorite"); | |
} | |
} | |
}; | |
xhr.send("id=" + parent.id); | |
} | |
var buttons = document.getElementsByClassName("favorite-button"); | |
for(i=0; i < buttons.length; i++) { | |
buttons.item(i).addEventListener("click", favorite); | |
} | |
function unfavorite() { | |
var parent = this.parentElement; | |
var xhr = new XMLHttpRequest(); | |
xhr.open('POST', 'unfavorite.php', true); | |
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); | |
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); | |
xhr.onreadystatechange = function () { | |
if(xhr.readyState == 4 && xhr.status == 200) { | |
var result = xhr.responseText; | |
console.log('Result: ' + result); | |
if(result == 'true') { | |
parent.classList.remove("favorite"); | |
} | |
} | |
}; | |
xhr.send("id=" + parent.id); | |
} | |
var buttons = document.getElementsByClassName("unfavorite-button"); | |
for(i=0; i < buttons.length; i++) { | |
buttons.item(i).addEventListener("click", unfavorite); | |
} | |
</script> | |
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// You can simulate a slow server with sleep | |
// sleep(2); | |
session_start(); | |
if(!isset($_SESSION['favorites'])) { $_SESSION['favorites'] = []; } | |
// A handy function to remove a single element from an array | |
function array_remove($element, $array) { | |
$index = array_search($element, $array); | |
array_splice($array, $index, 1); | |
return $array; | |
} | |
function is_ajax_request() { | |
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && | |
$_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'; | |
} | |
if(!is_ajax_request()) { exit; } | |
// extract $id | |
$raw_id = isset($_POST['id']) ? $_POST['id'] : ''; | |
if(preg_match("/blog-post-(\d+)/", $raw_id, $matches)) { | |
$id = $matches[1]; | |
// store in $_SESSION['favorites'] | |
if(in_array($id, $_SESSION['favorites'])) { | |
$_SESSION['favorites'] = array_remove($id, $_SESSION['favorites']); | |
} | |
echo 'true'; | |
} else { | |
echo 'false'; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment