An example of using an ajax function bound to the oninput
event to call your php function.
<?php
$new_name='';
if( $_SERVER['REQUEST_METHOD']=='POST' ){
function my_php_function( $name ){
$name = !empty( $_POST['user_name'] ) ? $_POST['user_name'] : $name;
return $name;
}
exit( my_php_function( &$new_name ) );
}
?>
<html>
<head>
<title></title>
<script>
/* a re-usable ajax function */
function ajax( url, params, callback ){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( this.readyState==4 && this.status==200 ) callback.call( this, xhr.response );
};
var payload=[];
for( var n in params )payload.push( n+'='+params[n] );
payload=payload.join('&');
xhr.open( 'POST', url, true );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send( payload );
}
/* event handler to send ajax request */
function call_my_php_function( event ){
ajax.call( this, location.href, { user_name:event.target.value }, function(r){
document.querySelector('input[name="new_name"]').value=r;
});
}
</script>
</head>
<form method='post'>
Name: <input type='text' name='user_name' oninput='call_my_php_function( event )' /><br />
new_name: <input type='text' name='new_name' value='<?php echo $new_name; ?>'/>
</form>
</html>