<

How to Make Javascript Talk to PHP

Published on
14,641 Points
4,841 Views
3 Endorsements
Last Modified:
Awarded
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:
<html>
<head>
<!-- Step 1a: Load jQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
    
  <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 />
   <b>Result:</b>
   
   <!-- 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...
  jQuery.ajax({

    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>.
    jQuery("#divRecordResult").html(result);

  });

}
</script>

</body>
</html>

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:
<?php
// 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
   $result->free();
}
else
{
  // 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:

http://api.jquery.com/jQuery.ajax/

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:

http://www.experts-exchange.com/Programming/Project_Management/Security/A_1263-5-Steps-to-Securing-Your-Web-Application.html

Now go build something!
3
Author:gr8gonzo
Enjoy this complimentary article view.

Get unlimited access to our entire library of technical procedures, guides, and tutorials written by certified industry professionals.

Get 7 days free
Click here to view the full article

Using this article for work? Experts Exchange can benefit your whole team.

Learn More
COLLABORATE WITH CERTIFIED PROFESSIONALS
Experts Exchange is a tech solutions provider where users receive personalized tech help from vetted certified professionals. These industry professionals also write and publish relevant articles on our site.
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.
Learn from the best.