This seems like it should be pretty simple, but I'm trying to update the data based on a variable value change. When you click the button, I need the variable "filter" to change its value, which will then change the content on the page. When the value changes, we're making a WP call to retrieve new content. My problem is, I'm having difficulty figuring out how to update the value using an onclick event with PHP.
function filterMedia(filter) {
const currentURL = window.location.href;
fetch(currentURL, {
method: "POST",
body: JSON.stringify({ "filter": filter }),
headers: { "Content-Type": "application/json" }
})
.catch(err => console.log(err));
}
<?php
$filter = "";
if (isset($_POST['filter'])) {
switch($_POST['filter']) {
case "media":
$filter = "news-article";
break;
case "press":
$filter = "press-release";
break;
case "video":
$filter = "video";
break;
}
}
?>
<div class="news-filter">
<div class="filter">
<button onclick="filterMedia('media')">In The Media</button>
</div>
<div class="filter">
<button onclick="filterMedia('press')">Press Releases</button>
</div>
<div class="filter">
<button onclick="filterMedia('video')">Videos</button>
</div>
</div>
PHP $_POST is only filled in from url-encoded or multipart/form-data parameters, it doesn't parse JSON content. So send that format:
function filterMedia(filter) {
const currentURL = window.location.href;
fetch(currentURL, {
method: "POST",
body: "filter=" + encodeURIComponent(filter),
headers: { "Content-Type": "application/x-www-form-urlencoded" }
})
.catch(err => console.log(err));
}