How to Make Javascript Talk to PHP

Published on
14,991 Points
3 Endorsements
Last Modified:
One question that comes up again and again on the PHP section of Experts Exchange is, "How can I make Javascript call some PHP (or MySQL) code?"

The short answer is that you can't make them talk to each other directly. PHP and Javascript are like two people that are in different countries. They can never talk to each other face-to-face because they're not in the same room, but they can use a variety of tools to help them still communicate, from letters to video chat (which is pretty close to talking face-to-face).

These tools always involve computers talking to each other on behalf of the people, and it's the same thing with PHP and Javascript.

Javascript is a client-side scripting language. That means that when you open up Firefox (for example) and visit a page containing Javascript, Firefox is given the Javascript code for that page and it is up to Firefox to decide to run that code at the time that it receives everything. It is up to Firefox's Javascript engine to properly execute all of the instructions that the web page developer has laid out. Bottom-line, Javascript is run on the visitor's own computer by whatever browser that person is using.

PHP (and most languages) are server-side. This means that when the visitor's browser asks the web server for the page, all of the PHP code is run on that web server and THEN the finished results are delivered as an HTML document (at least that is the most common approach).

Here's a simple animation that shows how the communication works between a web browser and a web server and where Javascript, PHP, and MySQL are located (you may need to click on it to see the animation):
Web Browser and Web Server Communication
So back to the question, "How can I make Javascript call some PHP (or MySQL) code?" The answer is to have Javascript tell the web browser to send another request to the web server, and the web server can pass that request to PHP. PHP can then respond with something that Javascript can use.

This process obviously happens once when the page loads, but what happens when you want Javascript to call PHP without reloading the page? The answer is AJAX.

AJAX stands for A.synchronous J.avascript A.nd X.ML. Basically, AJAX is simply the concept of using one of Javascript's tools to load a web page (any URL) and have Javascript be able to see and process the results instead of simply displaying the results in the browser.

This article is not going to cover how to perform an AJAX call from scratch because it can be complicated. Luckily, there are popular Javascript libraries like jQuery that make it extremely easy to create AJAX calls.

Let's say you have a web page at http://www.mysite.com/index.html and you want a visitor to be able to type in a number. You want to take that number, look up the record in the database, and show the result to the visitor. Easy!

We need to do the following things:

Web Page: http://www.mysite.com/index.html
1. Make sure the web page has:
    a. jQuery loaded (other libraries work, too)
    b. A way for the visitor to type in the record number
    c. A button for them to click to get the record
    d. A place to display the result.

PHP Script: http://www.mysite.com/getrecord.php
2. Make sure we have a PHP script that:
    a. Connects to our database
    b. Finds the requested record
    c. Displays the result

So first, let's build a sample page:
<!-- Step 1a: Load jQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
  <b>Record Number:</b>

  <!-- Step 1b: Provide a way for them to type in the record number -->
  <input type="text" id="txtRecordNumber">

  <!-- Step 1c: ...and a button for them to click to get the record -->
  <input type="button" onClick="requestRecord();" value="Get the Record">

   <br />
   <!-- Step 1d: ...and a place to display the result -->
   <div id="divRecordResult"></div>

<!-- When the button is clicked, we need to run a Javascript function called requestRecord -->
<script type="text/javascript">
function requestRecord()
  // First, we'll get the record number that the user entered...
  recordNumber = jQuery("#txtRecordNumber").val();

  // Now we are going to send it using AJAX to our PHP script...

    type: "POST",
    url: "http://www.mysite.com/getrecord.php",
    data: {
      recordNumberFromJavascript: recordNumber
    dataType: "html"

  }).done(function( result ) {

    // "result" will contain whatever comes back from our PHP script
    // so we'll use jQuery to put the result inside our results <div>.




Open in new window

Now that we have our web page ready, we just need our PHP script. We'll say it looks something like this:
// Connect to our database (Step 2a)
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_database");

// Find the record (Step 2b)
if ($result = $mysqli->query("SELECT Name FROM Records WHERE RecordNumber = " . intval($_POST["recordNumberFromJavascript"])))
   $row = $result->fetch_assoc();
   // Step 2c: Display the value (this is what Javascript will see)
   echo $row["Name"];

   // Cleanup
  // In case the database cannot find that record, show a message to Javascript
  echo "Not a valid record number!";

Open in new window

Presto! We now have a working AJAX model. We have a web page that sends an AJAX request to PHP. PHP then calls the database and looks up the record number and returns the name or a "Not a valid record number!" message. As soon as PHP responds, jQuery takes that result and puts it into a <div> so the visitor can see it!

The rest is up to your imagination. There are many options for how you can send the AJAX call (as a POST, as a GET, different parameters, etc...) and many shortcuts, as well. The most comprehensive jQuery documentation page on all of its options for AJAX is found here:


AJAX and Security
AJAX is a powerful concept, but like all powerful tools, it can also be a big security problem if you do not treat it with caution.

In my above example, there is nothing to stop any visitor from requesting any record number they want. Also, a PHP script is a PHP script, whether it's used by AJAX or not. So even though YOU might only use getrecord.php properly with AJAX, someone else could still access getrecord.php directly and use it to steal your data.

It is always a good idea to think through the ways that a PHP script could be misused by someone with bad intentions. You can then add security to help prevent those kinds of situations. I would suggest reading my article on web application security as a follow-up to this article on AJAX:


Now go build something!
Ask questions about what you read
If you have a question about something within an article, you can receive help directly from the article author. Experts Exchange article authors are available to answer questions and further the discussion.
Get 7 days free