Post to External PHP and Receive Data Back with jQuery Ajax Method

I already discussed how to use jQuery to GET data from external file by using the Ajax method. Let’s play around with the jQuery Ajax method a bit more. Today, I am going to show how to Post data to an external PHP file for processing, and then send back to the webpage.

Example 1

Let’s start with a most basic example.

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Post Data with Ajax Method</title>
    <link href="stylesheet.css" rel="stylesheet">
    <script type="text/javascript" src="jquery.js"></script>
    <script>
        $(document).ready(function( ){

            // Declare a variable with name and value pair
            // this will use to send to external PHP file for processing.
            var myData ="member=peter";

            $.ajax({
                type: "POST",
                data: myData,
                dataType: "json",
                url: "member.php",
                success: function(data, status) {
                    $("#outputBox").text(data);
                }
            });
        });

    </script>
<head>

<body>
<h1>Post Data with Ajax Method</h1>
<p>Output Box</p>

<div id="outputBox">
      <p>Display output here...</p>
      <p>&nbsp;</p>
</div>
</body>
</html>

The above webpage is very simple. It simply using jQuery Ajax Posting the data (name/value pair) to server (external PHP file – member.php) for manipulation.

Let’s see how the PHP file pass the data back to the server (webpage) for further processing.

To make thing simple, I will ignore the data first and start with the most basic code structure of the PHP file.

<?php

// Returns the JSON representation of a value back to webpage
echo json_encode("This is me!");

?>

I use json_encode() function to pass the value (This is me”) back to the server (webpage).

When the webpage is opened, the value (This is me”) received from external PHP file and displayed on the Div layer.

Download Example 1:
Click here to download jQuery Ajax Post example 1 source files

Example 2

The PHP file in example 1 is very simple. It just send a string (This is me) back to the server. Okay! We already got some idea how the jQuery Ajax posting works. Let’s do an example with a little bit more difficult. Don’t worry! It is still very simple.

In this example, I try to send a value back to server. Here’s the codes of the PHP file:

<?php

// Value sent from webpage (name and value pair)
$member = $_POST['member'];

// Returns the JSON representation of a value back to webpage
echo json_encode($member);

?>

Still remember the name/value pair variable send from webpage?

var myData ="member=peter";

Open the webpage, the value ($member) received from external PHP file and displayed on the Div layer.

This concept of manipulating the data is very important. Actually the PHP file will usually do a lot more with the data before sending the results back to the server.

Download Example 2:
Click here to download jQuery Ajax Post example 2 source files

Example 3

Now we have some basic knowledge of using jQuery Ajax posting data to a PHP file and receive the data back. We can do an example with a little bit more interesting.

There are two buttons on the webpage. When users click on the buttons, the corresponding values of the button will post to the external PHP file for processing, and then send back to this webpage, and finally display the value of the button on the Output Box.

Here’s the layout of the webpage.

Here’s the codes of the webpage.

<!DOCTYPE html>
<html>
<head>
        <title>Post Data with Ajax Method - Example 3</title>
        <link href="stylesheet.css" rel="stylesheet">

        <script src="jquery.js"></script>

        <script type="text/javascript">
            $(document).ready(function(){

                var targetElement = $("#container button");

                $('#container #btnSubmit').click(function() {

                    // Declare a variable to hold the name and value pair
                    // jQuery(this).val() is the current value of
                    //   button being clicked on
                    // alert(jQuery(this).val());
                    var myData = 'button=' + jQuery(this).val();

                    $.ajax({ // ajax call starts
                        type: "POST",
                          url: 'member.php',
                          data: 'button=' + jQuery(this).val(),
                          dataType: 'json',
                          success: function(data, status)
                          {

                            // If data send back from PHP is success,
                            //  display the data
                            $("#outputBox").text(data);

                          }
                  });

                // No need to refresh the page
                return false;
              });

        });
        </script>
</head>
<body> 

<div id="container">

    <h1>Post Data with Ajax Method 3</h1>

    <form method="post" action="">
      <button id="btnSubmit" value="gold" type="submit">Gold members</button>
      <button id="btnSubmit" value="silver" type="submit">Silver members</button>
      </form>

    <p>Output Box</p>
    <div id="outputBox">
      <p>Display output here...</p>
      <p>&nbsp;</p>
    </div>

</div>

</body>
</html>

The value of current selected button can easily be obtained with:

jQuery(this).val();

Actually we learned this before in another jQuery tutorial - jQuery Handle Current Selected Element with $(this). Please read the tutorial again if you have no any idea how it works.

Also remind once again that the data Post to PHP file with Ajax Method need to be in name/value pair format (or jason format)., i.e. name= value:

var myData = 'button=' + jQuery(this).val();

Here’s the codes of PHP file to manipulate the data. This is very simple, and no further explanation should be required.

<?php

    // Value sent from webpage (name and value pair)
    //echo $button;
    $button = $_POST['button'];

    // Check which button is clicked
    if ($button == "gold") {
          print json_encode("This is Gold Member");
    } else if ($button == "silver") {
        print json_encode("This is Silver Member");
    }

?>

When the “Gold members” button is clicked, the “button=gold” data string is post to the PHP file. The PHP file extract the value from the string, and obtained the value of “gold”. Then send the string “This is Gold Member” back to the webpage.

The process is the same when the “Silver members” button is clicked:

Download Example 3:
Click here to download jQuery Ajax Post example 3 source files

Example 4

Actually this example is same as example 3. However I would like to change the jQuery codes a little bit.

In example 3, you should notice this line of code:

// No need to refresh the page
return false;

In the old days, changing a small portion of contents of a webpage by JavaScript requires to refresh the whole page to see the results. With the magic of Ajax, changing a small portion of contents of a webpage do not requires to refresh the page. Sound great! And the above line of code is not allow the page to refresh. This way, the users can see the changes of contents without the annoying flashing screen due to refreshing of page.

However, some webmasters would like to write a separate function to do that. This can make the main function a bit shorter and cleaner.

<!DOCTYPE html>
<html>
<head>
        <title>Post Data with Ajax Method - Example 4</title>
        <link href="stylesheet.css" rel="stylesheet">

        <script src="jquery.js"></script>

        <script type="text/javascript">
            $(document).ready(function(){

                // No need to refresh the page
                $("#myForm").submit(function(){
                    return false;
                });

                var targetElement = $("#container button");

                $('#container #btnSubmit').click(function() {

                    // Declare a variable to hold the name and value pair
                    // jQuery(this).val() is the current value of
                    //   button being clicked on
                    // alert(jQuery(this).val());
                    var myData = 'button=' + jQuery(this).val();

                    $.ajax({ // ajax call starts
                        type: "POST",
                          url: 'member.php',
                          data: 'button=' + jQuery(this).val(),
                          dataType: 'json',
                          success: function(data, status)
                          {

                            // If data send back from PHP is success,
                            //  display the data
                            $("#outputBox").text(data);

                          }
                  });

                // No need to refresh the page
                //return false;
              });

        });
        </script>
</head>
<body>

<div id="container">

    <h1>Post Data with Ajax Method 4</h1>

    <form id="myForm" name="myForm" method="post" action="">
      <button id="btnSubmit" value="gold" type="submit">Gold members</button>
      <button id="btnSubmit" value="silver" type="submit">Silver members</button>
      </form>

    <p>Output Box</p>
    <div id="outputBox">
      <p>Display output here...</p>
      <p>&nbsp;</p>
    </div>

</div>

</body>
</html>

Download Example 4:
Click here to download jQuery Ajax Post example 4 source files

Example 5: jQuery Ajax Method + serializeArray() method

Let’s combine what we learned in previous post – Using jQuery serializeArray() Method – with this post. I will try to Post the serializeArray() object by Ajax to PHP file for processing.

I will use the same form in the post – Using jQuery serializeArray() Method.

This time, I will post the object of serialized array to external PHP file with jQuery Ajax Method. The codes of webpage will becomes:

<!DOCTYPE html>
<html>
<head>
        <title>Using jQuery serializeArray() Method</title>
        <link href="stylesheet.css" rel="stylesheet">

        <script src="jquery.js"></script>

        <script type="text/javascript">
            $(document).ready(function(){
                $("#myForm").submit(function(){
                    return false;
                });

                $('#btnSubmit').click(function() {

                    var data = $("#myForm :input").serializeArray();

                    $.ajax({ // ajax call starts
                        type: "POST",
                          url: 'member.php',
                          data: data,
                          dataType: 'json',
                          success: function(data, status)
                          {

                            // If data send back from PHP is success,
                            //  display the data
                            $("#outputBox").text(data);

                          }
                  });

                });    
            });
        </script>
</head>
<body> 

<h1>Using jQuery serializeArray() Method</h2>

<div id="container">

    <strong>Member Area</strong>

    <form id="myForm" name="myForm" action="member.php" method="POST">
    <p>First Name: <input type="text" name="txtFirstName" id="txtFirstName"> </p>
    <p>Last Name: <input type="text" name="txtLastName" id="txtLastName"> </p>            
    <button type="submit" name="btnSubmit" id="btnSubmit">Submit</button>            
    </form>

    <p>Output Box</p>
    <div id="outputBox">
      <p>Display output here...</p>
      <p>&nbsp;</p>
    </div>

</div>

</body>
</html>

As we learned before that the jQuery serializeArray() method created an array of objects with name and value, for example:

[{name:"txtFirstName", value:"Peter"},
{name:"txtLastName", value:"Pan"}]

Here’s the codes of PHP file (member.php) that process the serializeArray() object. This should be very easy as the serializeArray() object is in name/value pair format.

<?php

    // Value sent from webpage (serializeArray)
    $txtFirstName = $_POST['txtFirstName'];
    $txtLastName = $_POST['txtLastName'];

      print json_encode("Your name is: " . $txtFirstName . " " . $txtLastName);

?>

Open the webpage and test. The First Name and Last Name send back from the external PHP file, and display on the webpage.

Download Example 5:
Click here to download jQuery Ajax Post example 5 source files

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>