In broad terms, you need to turn part of your application into a service and have calls to it made by an asynchronous HTTP request from your page (this falls under the "AJAX" denomination).
It is this PHP script that should handle the SQL queries.
I actually need to go no further than W3Schools to have a bad example of MySQL query that is vulnerable to SQL injection (the problem is in
$sql="SELECT * FROM user WHERE id = '".$q."'";). DO NOT USE THIS EXAMPLE. I'd avoid W3Schools, see http://www.w3fools.com/