The first thing you have to realize is the JavaScript is Client-side(frontside) and PHP is Server-Side(backend). You be better off using AJAX or some other in-between applications that will communicate between the two. I have only used Ajax, but others here probably can give you another that you can use. I personally would just use Ajax. There are plenty of tutorials and documentation on the web in order for you to get what you want.
Here’s a vanilla Ajax call that I used for a trivia game that I did a long time ago, but a script that you would need would be even simpler.
function getCategories() {
form_data = serializeFormById('categories-form');
//console.log('serialize', form_data);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
//console.log('Result: ' + result);
var json = JSON.parse(result);
//console.log(json.total);
/*
* Hide Category Selection
*/
document.getElementById('categories-form').style.display = 'none';
document.getElementById('textContainer').style.display = "block";
document.getElementById('subject').innerHTML = "Category " + json.category;
loadGame('triviaxml.php', 0, json.total, json.category);
}
};
xhr.open('POST', 'totalRecords.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.send(form_data);
}