<

The "Hello World" Exercise with jQuery and PHP

Published on
70,289 Points
7,389 Views
19 Endorsements
Last Modified:
Awarded
jQuery is a JavaScript library that greatly simplifies JavaScript programming.

AJAX is an acronym formed from "Asynchronous JavaScript and XML."  AJAX refers to any communication between client and server, when the human client does not observe a new page load.  An HTTP request occurs, but it occurs as a result of a JavaScript event, rather than an explicit page load or form submission.  As a result, the web page takes on an appearance much like a desktop application, with smooth transitions as data is added or removed from the viewport.  This is often referred to as the "Web 2.0" effect.

I found myself looking around for a jQuery/AJAX "Hello World" example (that simplest of scripts to prove that the essential moving parts are working correctly).  There are lots of partial examples in many different places all over the WWW, but nothing seemed complete and well-documented, so I decided to write my own.  Here is the result of that effort.

The Server-Side of the Exercise
To make my example, I decided the essential parts would be the ability to send some data to the server and get a response back, so the first part of the exercise is the server-side script that produces a response containing the data it received from the AJAX request.  AJAX provides a RESTful interface.  The data for the request is sent via GET or POST and the response from the server is sent in the form of browser output.  As a result, it is very easy to test the back-end script.  Just type its URL into a browser address bar and you can see the RESTful interface in action.  Here is that script.
 
<?php // RAY_ajax_server.php
error_reporting(E_ALL);
date_default_timezone_set('America/Chicago');

// START THE OUTPUT BUFFER TO CAPTURE THE var_dump() DISPLAY
ob_start();

// MAKE THE OUTPUT EASY TO READ
echo '<pre>';

// SEND BACK THE DATE...
echo date('r');
echo  PHP_EOL;

// ... AND THE GET-REQUEST VARIABLES
echo 'GET: ';
var_dump($_GET);

// ... AND THE POST-REQUEST VARIABLES
echo 'POST: ';
var_dump($_POST);

echo '</pre>';
echo  PHP_EOL;

// CAPTURE THE OUTPUT BUFFER
$response = ob_get_clean();

// SEND THE CONTENTS OF THE OUTPUT BUFFER
die($response);

Open in new window

When you run that script from the browser you see something like this:

Thu, 13 Sep 2012 13:32:35 -0500
GET: array(0) {
}
POST: array(0) {
}

Once I had the server side working, I turned to the client side and began looking at jQuery.

How jQuery Syntax Works
In the simplest of terms, jQuery does two things: (1) Select HTML page elements, and (2) Perform actions on them.  The process of finding page elements is accomplished through the use of "selectors" that enable the programmer to choose one or more elements of the document.  Selectors can be HTML tags or named CSS elements, such as div or class.  The "actions" process consists of reading or changing these elements.  It may include accessing the content such as a form input, changing the CSS attributes (location, color, visibility), or changing the contents (text, HTML markup) of the page element.  The syntax looks like this:

$(selector).action()

The Client-Side of the Exercise
I coded the jQuery client-side example shown below.  A few explanatory notes follow each important line of the code.

 
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

Open in new window

This loads the latest version of the "minified" jQuery library.  The jQuery library is a very large and elaborate JavaScript library.  We choose the "minified" version because it uses minimalist syntax and variable names to shrink the size of the code, and thereby improve the performance of your web page by reducing the time it takes to load the jQuery file.

 
$(document).ready(function(){

Open in new window

This tells jQuery to wait until the document is ready.  The reason for this waiting period is because inline JavaScript (not part of a function) is run as soon as the browser encounters the code.  By waiting, we ensure that all of the needed parts of the web page have been loaded.  The document.ready event occurs after the onLoad event, but usually before the entire web page is loaded.  Images, for example, do not have to finish loading before the document is ready.  As a practical matter, this is frequently the first line of jQuery code.

 
    $("#signal").click(function(){

Open in new window

This tells jQuery to run the following function when there is a mouse click in the page element named with the id="signal" attribute.  If you look into the HTML below, you can see this element on line 23.

 
        indata = $("#xinput").val();

Open in new window

This copies the value from the page element with the id="xinput" attribute and assigns it to the JavaScript variable named "indata."

 
        $.post("RAY_ajax_server.php", {myArg:indata}, function(response){

Open in new window

This makes a POST-method request to the URL Ray_Ajax_Server.php, passing the input data in a request argument named "myArg" and receives the response from the server in a JavaScript variable named "response."

 
            $("#output p#target").html(response);

Open in new window

This tells jQuery to select the page element identified by the id="output" and look inside it for the

tag having the id="target" attribute.  The response variable from the server will replace the HTML and text in that paragraph.

In the HTML tags of the body, you can see the id= attributes associated with our jQuery selectors.  Here is the entire client-side script:
 

<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />
<title>Ajax Example Using jQuery</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

<script>
$(document).ready(function(){
    $("#signal").click(function(){
        indata = $("#xinput").val();
        $.post("RAY_ajax_server.php", {myArg:indata}, function(response){
            $("#output p#target").html(response);
        });
    });
});
</script>

</head>
<body>

<input id="xinput" value="Enter your name here" />
<div   id="signal">This is not a link, but Click Me Anyway!</div>
<div   id="output">
   <p  id="static">This element remains unchanged</p>
   <p  id="target">This element gets the AJAX response</p>
</div>

</body>
</html>

Open in new window


The Initial Page Load
On the initial page load, you will see an input box followed with something like this:

This is not a link, but Click Me Anyway!
This element remains unchanged
This element gets the AJAX response

After the AJAX Request Completes
When you put in your name and click, you will see something like this:

This is not a link, but Click Me Anyway!
This element remains unchanged
Thu, 13 Sep 2012 14:05:50 -0500
GET: array(0) {
}
POST: array(1) {
  ["myArg"]=>
  string(3) "Ray"
}


Executive Summary
Once you have that much working, you have mastered the Hello World exercise of a jQuery AJAX request.  You have sent information from the client browser to the server and received the server's response.  You have placed the response into the document in a way that lets it appear in the viewport.  Starting with that foundation, you can begin using jQuery to build interactive and lively web applications with the look and feel of "Web 2.0."

References and Further Reading
http://www.w3.org/TR/CSS21/selector.html
http://www.w3schools.com/jquery/jquery_syntax.asp
http://api.jquery.com/category/selectors/
http://www.w3schools.com/jquery/jquery_ref_selectors.asp

Please give us your feedback!
If you found this article helpful, please click the "thumb's up" button below. Doing so lets the E-E community know what is valuable for E-E members and helps provide direction for future articles.  If you have questions or comments, please add them.  Thanks!
 
19
Comment
Author:Ray Paseur
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
5 Comments
 
LVL 58

Expert Comment

by:tigermatt
Great article Ray! Voted "yes" above.

-Matt
0
 
 

Administrative Comment

by:ericpete
Ray,

Somehow, we dropped the ball on this one. It has now been set to EE-Approved. Congratulations!

ericpete
Page Editor
0
 
 

Administrative Comment

by:ericpete
Ray_Paseur,

Congratulations! Your article has been selected as an Editors' Choice.

ericpete
Page Editor
0
 

Expert Comment

by:Nico2011
Thanks Ray - very helpful - hope you are well!
0
 
LVL 36

Expert Comment

by:Loganathan Natarajan
It is very helpful.
0

Featured Post

Learn by Doing. Anytime. Anywhere.

Do you like to learn by doing?
Our labs and exercises give you the chance to do just that: Learn by performing actions on real environments.

Hands-on, scenario-based labs give you experience on real environments provided by us so you don't have to worry about breaking anything.

Join & Write a Comment

Use Wufoo, an online form creation tool, to make powerful forms. Learn how to choose which pages of your form are visible to your users based on their inputs. The page rules feature provides you with an opportunity to create if:then statements for y…
Learn how to set-up custom confirmation messages to users who complete your Wufoo form. Include inputs from fields in your form, webpage redirects, and more with Wufoo’s confirmation options.

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month