When the user chooses a category from the drop down, the posts, for example on a widget that shows latest 25 posts, should filter based on the category selected. I can do this with PHP but that reloads the page, which I do not want. There should be some ajax or JS alternative(using REST API).
Hi @codeispoetry hopefully this could get you in the right direction:
var select = document.getElementById('cat');
select.addEventListener('change', function(event) {
event.preventDefault();
var category = select.value;
var request = new XMLHttpRequest();
var url = '/this/is/some/url/to/request/your/categories?categoryId=' + category;
request.open('get', url, true);
request.onreadystatechange = function (data) {
if (request.status !== 200) {
console.error('error getting data');
} else {
var data = request.responseText || request.reponse;
/* 1. See possible options explained below */
}
};
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
request.send();
});
At this point you will act accordingly depending on what kind of data you are getting back, this depends in the wordpress API, which I don’t know.
Potentially you will get a JSON object and then based on that you can build your HTML and replace your existing one or just replace the content bits.
Potentially and ideally you also have a way to request just the relevant HTML content so you don’t have to rebuild it but I don’t know how to do this in Wordpress.
There is another possibility which would be making a request to the same URL with the new category, which will inevitably return you the whole page content (not the most optimal). Possibly injecting it into a document fragment without attaching it to the dom and then selecting with JS the node you’re interested in and injecting that in the dom.
A problem you very probably will face is that once you inject the HTML any JS that had been previously applied to that content won’t be initialised then and you’ll have to handle this manually.
disclaimer: This is not a beginner’s exercise but if you try hard you’ll learn a lot. Good luck
Which parts could you not understand?
I’m sure if you expand on it someone would be able to help you. As I said before the problem is not easy so you might want to help others a little more in helping you.
As a first step I would look into how the Wordpress API works and find out the way in which you can visit a custom URL that would return you just the content you’re interested in, without the rest of HTML such as head and body… This part involves no JavaScript, just PHP… after you got this then you can move on to the next step.