<

How to Make Javascript Talk to PHP

Published on
13,744 Points
3,944 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
Comment
Author:gr8gonzo
  • 3
  • 2
5 Comments
 

Expert Comment

by:Eduardo Fuerte
Hello gr8gonzo!

Unfortunatelly after some trials I didn't have success in make it works...
Maybe I'm doing something wrong or something must be adjusted.

It seems like getrecord.php is never fired.

I've done a test with a furnished value to see if it's ok...


It's ok.
img001
After that I did some modifications and tentatives to make it runs, no sucess too....

<html>
<head>
<!-- Step 1a: Load jQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>

<!--(Just an aditional test) form id="form1" name="form1" method="post" onsubmit="return validateForm()"-->

<form id="form1" name="form1" method="post" onsubmit="requestRecord();">

<!--(without ";" )form id="form1" name="form1" method="post" onsubmit="requestRecord()"-->
    
  <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 -->
 <!-- doesn´t work-->

 <!--input type="button" onclick="requestRecord()" value="Get the Record"-->

  <!--input type="button" value="Get the Record"/-->
  <input type="submit" value="Get the Record"/>

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

</form>
</body>
</html>

<!-- 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();
  
  // Just to see if it's fired.... it isn't 
  alert("Acionado !");
    
  // Now we are going to send it using AJAX to our PHP script...
  jQuery.ajax({

    type: "POST",
    //url: "http://www.mysite.com/getrecord.php",
    url: "http://localhost/Espiriplug_prj/Kool_Teste/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>

<script type="text/javascript">
function validateForm()
{
  var y9=document.forms["form1"]["txtRecordNumber"].value;

  if (y9.length==0)
  {
      alert("Preencha obrigatoriamente o Valor do lançamento!");
      return false;
  }
}  
</script>

Open in new window


Could you give me assistance?

Any other check could be done?

Sorry if I've confused something.

Thanks in advance!
0
 
LVL 37

Author Comment

by:gr8gonzo
Hi EFuerte,

It is not performed because your are submitting a form. When you click on a submit button that is inside a <form>, it tries to change the page.

That is why I used a <input type="button"> - because a regular button is different from a submit button. A regular button will not submit the form when clicked. This code:

<input type="button" onclick="requestRecord()" value="Get the Record">

...creates a button that has the label "Get the Record" and when the user clicks it ("onClick"), the browser will try to run the Javascript function called "requestRecord()".
0
 

Expert Comment

by:Eduardo Fuerte
Hi g8gonzo

So I've returned to your original code since the <form> was a workaround tentative to make the button fire php code. Still have no success.

Just for you to check if you could.

http://www.espiriplug.com.br/Espiriplug_prj/Kool_Teste/Teste_g8gonzo.php

http://www.espiriplug.com.br/Espiriplug_prj/Kool_Teste/getrecord.php

The code
<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",
    url: "http://www.espiriplug.com.br/Espiriplug_prj/Kool_Teste/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


and


<?php

    $db_host = "mysql.espiriplug.com.br";
    $db_user = "*******";
    $db_word = "************";
    $db_name = "******";
    
    echo "Passou 1...";

    
    // Connect to our database (Step 2a)
    //$mysqli = new mysqli("localhost", "my_user", "my_password", "my_database");

    $mysqli = new mysqli($db_host,$db_user,$db_word,$db_name);

    // Find the record (Step 2b)
//    if ($result = $mysqli->query("SELECT DESCRICAO as Name FROM DSGER WHERE SB_DGE = " .
//        intval($_POST["recordNumberFromJavascript"]))) {
//
    if ($result = $mysqli->query("SELECT DESCRICAO as Name FROM DSGER WHERE SB_DGE = 94"))
    {
        $row = $result->fetch_assoc();

        // Step 2c: Display the value (this is what Javascript will see)
        echo $row["Name"];

        //echo "Pass getrecord";


        // 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


Thanks.
0
 
LVL 37

Author Comment

by:gr8gonzo
You have a Javascript error. You are missing a comma after your url:

url: "http://www.espiriplug.com.br/Espiriplug_prj/Kool_Teste/getrecord.php"
should be:
url: "http://www.espiriplug.com.br/Espiriplug_prj/Kool_Teste/getrecord.php",

I would suggest using Firefox with the Firebug plug-in to help debug Javascript errors.

If there are further questions, please open up a question in the PHP zone so the comments section here doesn't get filled with code. Thanks!
0
 

Expert Comment

by:Eduardo Fuerte
Hi  gr8gonzo!

Now it worked fine. Sorry the inconvenience and thank you very much!
0

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

Join & Write a Comment

Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month