My answer is nothing new but find the complete code. I haven't tested it. Please be aware there might be a minor typo.
javascript.php
<!doctype html>
<html lang="en">
<head>
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<button onclick="test_request()">Test Request</button>
<script>
function test_request() {
$.post("php.php", {jsvar: name}, function(data_from_php) {
console.log(data_from_php);
});
}
</script>
</body>
</html>
php.php
<?php
$phpvar = $_POST['jsvar'];
echo 'Hello' . $phpvar;
What's happening is jQuery
is posting some value to the HTTP
server (aka a POST
request) and the anonymous function(data_from_php)
is waiting for the server to respond with some data. As soon as the data arrives the function is triggered.
You can verify it from the Chrome's
debugger window (or Firefox
etc). For example, in Chrome just press Ctrl+Shift+I
to open the developers tools. Click on the Network
tab and click on XHR
and notice when the request is made. You will be able to see what is happening under the hood and how it is working.