Easy, but depends what exactly you want to do. Here's some example snippet of code:
<?php
if(!empty($_POST['lname'])) {
$valueOfInput = $_POST['lname'];
die(json_encode(array('status' => 'success', 'lname' => $valueOfInput)));
}
?>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<input type="text" id="lname" name="lname" value="" />
<script type="text/javascript">
$(document).ready(function() {
$("#lname").on("keypress", function() { // waiting for keypress event to be fired
setTimeout(function() { // delay to have the key value inserted into input, and affect value param
$.post(document.location.href, { lname: $("#lname").val() }, function(data) { // sending ajax post request
console.log(data);
});
}, 50);
});
});
</script>
</body>
</html>
You didn't write about any JS frameworks, but I assumed that it would be easier for you (beginner) to start with jQuery or some other framework which can help you with some abstraction around JS features.
Here brief description what's going on:
website is waiting till you start writing anything to the input (just as in your code)
script is handling typing event (keypress) and waits till the value is inserted to your input
script is sending an ajax request with input value as a param
PHP code is taking the value from $_POST superglobal array, and inserts it into your PHP variable
PHP code is sending response to the JS script that all good, and this response is printed in your console (you can do whatever you want - need with it)
Issue: It will send a lot of requests to the server, so consider better approach (change
event instead of keypress
?)