First a little explanation. PHP is server side (backend) and JavaScript is client side (frontend). I look at it this way, by the time JavaScript is doing something - PHP is already finished doing whatever it was doing and taking a nap. ;D
What you need is a middleman and that is where Ajax (Asynchronous JavaScript And XML) comes into helping you out. The javascript with the help of Ajax will tell the PHP script “Hey I need you to do something and could you send something back to me?”. 8) Majority of time Javascript is expecting some kind of response back from PHP via Ajax and the PHP script usually responds back “Sure, but you are going to have some code to catch my reply back to ya!!” 
Now the interaction can be automatic between javascript-Ajax-php or it can be user initiated by a button, link, form, etc…
Here’s a partial script from a thread response that I just did. Either look at this or look at the other thread.
The Javascript and AJax portion ->
[php] /*
* Ajax and JSON script
*/
function sortTable(status) {
var check = “status=” + status; // Put it in $_POST Format:
//console.log(check);
var xhr = new XMLHttpRequest();
/* Waiting for a response back from PHP. I put this
before I actually send for I don't want to miss the response */
xhr.onreadystatechange = function () {
//console.log('readyState: ' + xhr.readyState, 'xhr.status: ' + xhr.status);
if (xhr.readyState === 2) {
//console.log(xhr.status);
if (xhr.status === 410) {
}
}
if (xhr.readyState === 4 && xhr.status === 200) {
var info = JSON.parse(xhr.responseText);
var tBody = document.getElementById('insertData');
var element = document.getElementById('name1');
/*
* Don't create elements if they already exists!
*/
if (typeof (element) !== 'undefined' && element !== null) {
for (var i = 0; i < info.length; i++) {
document.getElementById('name' + (i + 1)).innerHTML = info[i].Name;
document.getElementById('continent' + (i + 1)).innerHTML = info[i].Continent;
document.getElementById('population' + (i + 1)).innerHTML = info[i].Population;
}
} else { // Does not exist!
for (var x = 0; x < info.length; x++) {
var row1 = document.createElement('tr');
var tableName = document.createElement('td');
var tableNameId = document.createAttribute('id');
tableNameId.value = 'name' + (x + 1);
tableName.setAttributeNode(tableNameId);
tableName.innerHTML = info[x].Name;
row1.appendChild(tableName);
tBody.appendChild(row1);
var row2 = document.createElement('tr');
var tableContinent = document.createElement('td');
var tableContinentId = document.createAttribute('id');
tableContinentId.value = 'continent' + (x + 1);
tableContinent.setAttributeNode(tableContinentId);
tableContinent.innerHTML = info[x].Continent;
row1.appendChild(tableContinent);
tBody.appendChild(row2);
var row3 = document.createElement('tr');
var tablePopulation = document.createElement('td');
var tablePopulationId = document.createAttribute('id');
tablePopulationId.value = 'population' + (x + 1);
tablePopulation.setAttributeNode(tablePopulationId);
tablePopulation.innerHTML = info[x].Population;
row1.appendChild(tablePopulation);
tBody.appendChild(row3);
}
}
}
}; // End of Ready State:
/* This is where I open communication, setup the proper formatting and finally sending
the information to the php script via Ajax */
xhr.open('POST', 'result.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.send(check);
}[/php]
and here’s the php portion that I have in a separate file.
[php]<?php
include ‘connection.php’;
/* Makes it so we don’t have to decode the json coming from JavaScript */
header(‘Content-type: application/json’);
$check = filter_input(INPUT_POST, ‘status’, FILTER_SANITIZE_FULL_SPECIAL_CHARS); // Grab The Post
/* Retrieving Data using PDO /
function retreiveData($sql) {
$db_options = [
/ important! use actual prepared statements (default: emulate prepared statements) /
PDO::ATTR_EMULATE_PREPARES => false
/ throw exceptions on errors (default: stay silent) /
, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
/ fetch associative arrays (default: mixed arrays) */
, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];
$pdo = new PDO('mysql:host=' . DATABASE_HOST . ';dbname=world;charset=utf8', DATABASE_USERNAME, DATABASE_PASSWORD, $db_options);
$stmt = $pdo->prepare($sql); // Prepare the query:
$stmt->execute(); // Execute the query with the supplied user's parameter(s):
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
return $data;
}
if ($check === “ASC”) {
$sql = ‘SELECT Name, Continent, Population FROM country ORDER BY Name ASC’;
} else {
$sql = ‘SELECT Name, Continent, Population FROM country ORDER BY Name DESC’;
}
$data = retreiveData($sql);
$output = $data;
output($output);
/*
- Set error code then send message to Ajax / JavaScript
*/
function errorOutput($output, $code = 500) {
http_response_code($code);
echo json_encode($output);
}
/*
- If everything validates OK then send success message to Ajax / JavaScript
*/
function output($output) {
http_response_code(200);
echo json_encode($output);
}
[/php]
Now the Ajax portion is written in vanilla javascript meaning no library to make it easier to code, for example jQuery is a popular javascript library that makes it easier to write javascript and Ajax. While it is easier to write, I feel learning straight Javascript version first makes it better to understand what is truly going on between Javascript and PHP using Ajax. There are plenty of online tutorials and books to help you understand Ajax (Javascript) and how to write good code. Heck, I am even learning something new everyday, for I am more of a backend developer than a frontend developer.
Hope this helps - John
P.S. I know my javascript portion is not the greatest and I have seen replies on other forums that it is bad practice to use .innerHTML. However like I already stated I’m always learning something new and in my case I’m learning how to write better javascript code.