MOKUJI—collection of
notes by Zac Fukuda

Ajax Tutorial with PHP, jQuery

002
Sep 24, 2015

This tutorial shows you how to make a simple Ajax event with PHP and jQuery. Designed for beginners to Ajax and PHP. With this codes, you'll be able to send texts to the server and receive the feedback message along with HTTP status. You can download the source code from Github.

Files

You might be looking for just the codes, so I provide those first and the explanations after.

index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Ajax Tutorial with PHP, jQuery</title>

    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <div class="container">
      <h1>Ajax Tutorial with PHP, jQuery</h1>
      <!-- A div that receives message from PHP(server-side) -->
      <div id="message"></div>

      <!-- Post Area -->
      <p>Posts:</p>
      <ul id="posts"></ul>

      <!-- form -->
      <form id="form" action="./ajax.php" method="post">
        <textarea name="text" rows="8" placeholder="What's on your mind?"></textarea>
        <input type="submit" name="submit" value="Post">
      </form>

    </div><!-- /.container -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="vendor/jquery-2.1.4.min.js"><\/script>')</script>
    <script src="main.js"></script>
  </body>
</html>
main.js
+function ($) {

  var $message  = $('#message'),
      $posts    = $('#posts'),
      $form     = $('form'),
      $textarea = $('textarea');

  $form.submit( function(e) {
    e.preventDefault();
    e.stopPropagation();

    // Retrieve variables needed for the ajax event.
    var action   = $(this).attr('action'),
        method   = $(this).attr('method'),
        formData = $(this).serialize();

    $.ajax({
      url: action, // "./ajax.php" in this tutorial
      type: method, // post
      data: formData, // text that you input in textarea
      beforeSend: function () {
        $form.removeClass();
      }
    }).done( function (data, status, xhr) {
      // Event to be triggered if succeed

      // Display the message that you got from
      // the server side, then add a class.
      $message.html(data).addClass('ok');

      // Append the post.
      var newPost = document.createElement('li'),
          node    = document.createTextNode( $textarea.val() );
      newPost.appendChild(node);
      $posts.append(newPost);

      // Empty textarea
      $textarea.val('');

    }).fail( function (xhr, status, error) {
      // Event to be triggered if fail

      // Display the message that you got from
      // the server side, then add a class.
      $message.html( xhr.responseText ).addClass('error');

    }); // End ajax

  }); // End submit event
}(jQuery);
ajax.php
<?php
try {

  /**
   * The value inside of $_POST[] should match
   * the name of your textarea that you set in index.html.
   */
  if ( !isset($_POST["text"]) ) {
    throw new Exception("Textarea named 'text' doesn't exist.");
  }
  $text = $_POST["text"];
   if (!$text) {
     throw new Exception("Textarea is empty.");
   }

  // Usually you want to store this value to DB.
  // But this tutorial is not designed for it.
  // So, we skip this part.

  $message = "Your ajax is working successfully.";

  // Return $message to the client side.
  echo $message;

} catch(Exception $e) {
  header('HTTP/1.1 401 Unauthorized');
  echo $e->getMessage();
}
style.css

This file is not necessary, so I skip providing. Please refer to the Github

Paths are written in relative way so it doesn't matter if you run the codes in the sub-directory.

How it works

There are simply four things that makes this an ajax.

  1. .serialize()
  2. $.ajax()
  3. $_POST[]
  4. echo

.serialize()

.serialize() gets the values of all form elements and creates a text string in standard URL-encoded notation. For example, in this tutorial, name "text" is set to textarea, so when you type "Test post" in the flield and then click the post button, it automatically generates a text of text=Test%20post. %20 means a space in URL-encoded notation.

$.ajax()

$.ajax() is the main function of this event, of course. To dive into it, I encourage you to take a look at the official api jQuery doc, but here, I explain the very basics, that is url, type, and data.

Url is the path or file to which the request is to be sent. In this tutorial, this is ./ajax.php. Method is the HTTP method to use for the request. In general, this could be GET, POST, PUT, or DELETE. Just as the button indicates, this time we use POST method. For more about HTTP method, please check out Wikipedia. Data is the data to be sent to the server, this time value of textarea, that you serialized by .serialize(), will be sent.

.done() and .fail() are the codes that will be excuted after the ajax completes.

$_POST[]

This is how you access to the data that is sent from the client side. This time we send the request with POST method, so after the underscore should be POST. Inside the square blancket is the name of textarea, which is "text" this time. For instance, if you make a input field with the name of "email", this would be $_POST["email"]. If you send the request with GET method, you just need to replace POST with GET, $_GET["email"].

echo

By this, the server side send back the message to the client. In order to send the proper HTTP status code, I use try{} catch{} here.

Reference