QRdvark.com

  1. Abstract
  2. Including the JQuery library
  3. Hello World
  4. Selectors
  5. Events
  6. Targetting Other Elements
  7. CSS
  8. JQuery AJAX and PHP

Abstract

In this tutorial, the javascript library JQuery is used to demonstrate how PHP can work with other technologies. JQuery has been around for over 10 years, and a has proven itself to be a library to stand the test of time whilst other javascript libraries come and go.

Including the JQuery Library

The jQuery library resides on a CDN which can be linked to downloaded directly. The code below shows how to include the library code in both ways.

Include from CDN


<html>
<head>
<title>Introduction to PHP and JQuery</title>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
</head>
<body>
<h2>Introduction To PHP and JQuery</h2>
</body>
</html>

Include from local drive


<html>
<head>
<title>Introduction to PHP and JQuery</title>
<script src="/js/jquery-2.2.0.min.js"></script>
</head>
<body>
<h2>Introduction To PHP and JQuery</h2>
</body>
</html>

For the purposes of this tutorial, the latter code will be used, which means the JQuery library will be downloaded to the local drive and the file will reside in the /js directory in the webroot.

Hello World

What programming tutorial would be complete without a simple hello world to test the environment is properly set up. Lets dive right in.

tute.js


/* wrap code in .ready */
$(document).ready(function(){
        /* a message to insert into the div */
        $("#msgid").html("Hello World with JQuery");
});

index.php


<html>
<head>
<title>Introduction to PHP and JQuery</title>
<script src="/js/jquery-2.2.0.min.js"></script>
<script src="/js/tute.js"></script>
</head>
<body>
<h2>Introduction To PHP and JQuery</h2>

<div id="msgid"></div>

</body>
</html>

The output from the above code will display something like this

Introduction To PHP and JQuery

Hello World with JQuery

The HTML code now contains another included file called tute.js. This file will be used to hold our JQuery code, and needs to be included after the inclusion of the JQuery library.

Lets look at what this code does. The initial line shows .ready event. What this does is to ensure that the document ready to be manipulated as soon as it is ready.

Following on, there is the message to insert into the div with the id of msgid. The line begins with a dollar sign, which is the access, or definition of our JQuery library. To target the msgid div, JQuery uses a selector in the form of #msgid. The .html() action contains the content which will be inserted into the msgid div.

$() is short for jQuery(), and similar to document.querySelector, and is the Query part of JQuery, which takes a selectory as its arguement.

Selectors

As seen in the above code, JQuery uses selectors to target which elements are going to manipulated. In the above example, the selector #msgid was used to target the div with the id of msgid.

The use of the hash(#) denotes that the selection is an element within the document with a unique id.

The same code could have been executed with a class instead of an id, as there was only one occurance of the div which need to be manipulated. A class selector is prefaced with a dot(.. Lets change our HTML and JQuery code a little to show this.

tute.js


/* wrap code in .ready */
$(document).ready(function(){
        /* a message to insert into a div with class of msgClass */
        $(".msgClass").html("Hello World with JQuery");
});

index.php


<html>
<head>
<title>Introduction to PHP and JQuery</title>
<script src="/js/jquery-2.2.0.min.js"></script>
<script src="/js/tute.js"></script>
</head>
<body>
<h2>Introduction To PHP and JQuery</h2>

<div class="msgClass">This is some content</div>
<div class="msgClass"></div>

</body>
</html>

The output of the above code now looks like this:

Introduction To PHP and JQuery

This is some content
This is some content

So, why are you seeing the content twice? Because there are two divs with the class of msgClass. The JQuery code has targetted all divs with the class of msgClass and replace the content (.html) with the supplied content.

To manipulate only the content required, care needs to be taken that all elements have the correct class or id attributes. The code below shows how to correctly effect the required change.

tute.js


/* wrap code in .ready */
$(document).ready(function(){
        /* a message to insert into a div with class of msgClass */
        $(".msgClass").html("Hello World with JQuery");
});

index.php


<html>
<head>
<title>Introduction to PHP and JQuery</title>
<script src="/js/jquery-2.2.0.min.js"></script>
<script src="/js/tute.js"></script>
</head>
<body>
<h2>Introduction To PHP and JQuery</h2>

<div class="anotherClass">This is some content</div>
<div class="msgClass"></div>

</body>
</html>

The above code now correctly displays this:

Introduction To PHP and JQuery

This is some content
Hello World with JQuery

Events

Events are the heart of JQuery. If you were to define JQuery in any way, it would be as an event driven HTML manipulation library.

In the above examples, a single event has been used. This is the .ready event. However, there are many events that can appen on an HTML document. Click events, mouse events, keyboard events, document and window events and many others.

Lets begin with the .click event.

The .click event occurs, as the name suggests, when an element is clicked upon, with a mouse or via a press from a screen driven device. When an element is clicked, JQuery responds to the .click event with an action.

tute.js


/* wrap code in .ready */
$(document).ready(function(){
        /* a message to insert into a div with class of msgClass */
        $(".msgClass").html("Click To Hide Me");

        /* a .click event */
        $("#msgId").click(function(){
                /* the action to take when clicked */
                $(this).hide();
        });
});

The code above, when loaded will look a little like this:

Introduction To PHP and JQuery

This is some content
Click To Hide Me

The msgClass div has been correctly identified, and filled with the text from the .html() action. Next, the .click event handler is ready for the div with the id of msgId to be clicked. When clicked, the .hide() action takes effect and the div is now hidden.

"OK, great. You hid it, now make it come back".

Targetting Other Elements

In the previous section, the .click event was used to manipulate the Document Object Model (DOM) to hide the div with the id of msgId. However, there was no way to bring it back.

What is required, is another element to act as a switch, or toggle to show or hide div.

tute.js


/* wrap code in .ready */
$(document).ready(function(){
        /* a message to insert into a div with class of msgClass */
        $(".msgClass").html("Click Button To Toggle Me");

        /* a .click event */
        $("#showHide").click(function(){
        /* the action to take when the showHid button is clicked */
                $("#msgId").toggle();
        });
});

index.php


<html>
<head>
<title>Introduction to PHP and JQuery</title>
<script src="/js/jquery-2.2.0.min.js"></script>
<script src="/js/tute.js"></script>
</head>
<body>
<h2>Introduction To PHP and JQuery</h2>

<button id="showHide">Show or Hide</button>
<div class="anotherClass">This is some content</div>
<div id="msgId" class="msgClass"></div>

</body>
</html>

When accessed, the code above will show something like this:

Introduction To PHP and JQuery

This is some content
Click Button to Toggle Me

Once again, the .ready event has used the .html() action to fill the div with the id of msgId with a message. A button has been added to the HTML in the index.php file, with the id of showHide. the .click event handler for the showHide element dictates that when click, the toggle() action is performed, and so, the div is either shown or hidden. The toggle() action is a JQuery effect, which is just a part of the many effects JQuery can perform.

So, at this point, JQuery can be seen as a library to enable the manipulation of the DOM, with events and actions. Events are things that happen, and actions are things that happen when an event occurs.

CSS

JQuery allows many manipulations of the DOM. CSS is no exception. Earlier events were used to trigger actions, here the .mouseover event is used to add CSS to the msgId Element.

tute.js


/* wrap code in .ready */
$(document).ready(function(){
        /* a message to insert into a div with class of msgClass */
        $(".msgClass").html("Click Button To Toggle Me");

        // a mouseover event
        $( "#msgId" ).mouseover(function( event ) {
                // add CSS to the element
                $("#msgId").css("color", "red");
        });
});

index.php


<html>
<head>
<title>Introduction to PHP and JQuery</title>
<script src="/js/jquery-2.2.0.min.js"></script>
<script src="/js/tute.js"></script>
</head>
<body>
<h2>Introduction To PHP and JQuery</h2>

<div id="msgId">Here is some text.</div>
</body>
</html>

As expected, the color of the text changes to red when the mouse is placed over the div with the id of msgId. When the mouse moves away, the text remains the same color. If the text needs to change back when the mouse is removed from the div, another event is required. This time, the .mouseout is used to return the color of the text within the div to black.

tute.js


/* wrap code in .ready */
$(document).ready(function(){
        /* a message to insert into a div with class of msgClass */
        $(".msgClass").html("Click Button To Toggle Me");

        // a mouseover event
        $( "#msgId" ).mouseover(function( event ) {
                // add CSS to the element
                $("#msgId").css("color", "red");
        });

        // a mouseout event
        $( "#msgId" ).mouseout(function( event ) {
                // add CSS to the element
                $("#msgId").css("color", "black");
        });
});

index.php


<html>
<head>
<title>Introduction to PHP and JQuery</title>
<script src="/js/jquery-2.2.0.min.js"></script>
<script src="/js/tute.js"></script>
</head>
<body>
<h2>Introduction To PHP and JQuery</h2>

<div id="msgId">Here is some text.</div>
</body>
</html>

Now when the mouse is removed from the div with the id of msgId, the text color is changed back to black. Great!

This code can be optimised as JQuery supports chaining of methods. This allows multiple events to be attached to a single query selector. The .mouseover and .mouseout events can both to be attached to the msgId selector in a single call.

tute.js


/* wrap code in .ready */
$(document).ready(function(){
        /* a message to insert into a div with class of msgClass */
        $(".msgClass").html("Click Button To Toggle Me");

        // chained mouseover and mouseout events
        $( "#msgId" ).mouseover(function( event ) {
                // add CSS to the element
                $("#msgId").css("color", "red");
        }).mouseout(function( event ) {
                // add CSS to the element
                $("#msgId").css("color", "black");
        });
});

index.php


<html>
<head>
<title>Introduction to PHP and JQuery</title>
<script src="/js/jquery-2.2.0.min.js"></script>
<script src="/js/tute.js"></script>
</head>
<body>
<h2>Introduction To PHP and JQuery</h2>

<div id="msgId">Here is some text.</div>
</body>
</html>

JQuery AJAX and PHP

JQuery and AJAX and PHP go together very simply to create effective data driven content asychonously. What this mean, is that a page can fetch new content without a page refresh. The data is gained from an external source, often a database, and an action is used to insert that data into the DOM.

To enable this to happen, a third file will be added to handle the PHP code.

Most transactions between a server and JQuery will be GET or POST requests. Firstly, the GET request.

GET

The GET request is used when data needs to be gained from an external source. This could be an API, a text file, or almost any sort of resource. JQuery uses the .get() method to gain data from an external source.

request.php


<?php
        
// a message to return to the JQuery request
        
$message 'This is data from ajax request';

        
// display the data
        
echo $message;
?>

index.php


<html>
<head>
<title>Introduction to PHP and JQuery</title>
<script src="/js/jquery-2.2.0.min.js"></script>
<script src="/js/tute.js"></script>
</head>
<body>
<h2>Introduction To PHP and JQuery</h2>

<button id="getData">Get Data</button>
<br><br>
<div id="msgId" class="msgClass"></div>

</body>
</html>

tute.js


/* wrap code in .ready */
$(document).ready(function(){
        /* a message to insert into a div with class of msgClass */
        $(".msgClass").html("Click Button To Toggle Me");

        /* a .click event */
        $("#getData").click(function(){
        /* get data from request.php and assign it to the data variable */
                $.get("request.php", function(data, status){
                        /* put the data from the request into the div with the id of msgId */
                        $("#msgId").html(data);
                });
        });
});

So, there is a bit more going on here. Lets step through the code.

In the request.php file, a simple string is defined, and echo'ed as output from the script. The string may have had it origins anywhere that PHP could fetch it from, often, a database.

The index.php which contains the HTML. As we have seen earlier, there is a container div, with the id of msgId, and class of msgClass. These will be the targets of our events.

In the tute.js file, the msgClass element is assigned the value of "Click Button To Toggle Me". Then, the button itself has an .click event attached to it.

When the button is clicked, the .click event is triggered, and the a GET request is sent to request.php. The request.php file outputs the string "This is data from ajax request". This string is captured in the data variable, which is then used by the .html() action to assign the data string to the msgId element.

The above code works fine when retrieving a single line from an external resource, but most often, requests require which get results sets, or arrays of data from an external source.

request.php


<?php
        
// this may be an array gained from a database or any other source
        
$data = [0=>'dingo'1=>'wombat'2=>'Steve Irwin'3=>'kangaroo'4=>'kiwi'5=>'kookaburra'];

        
// a holder for our table data
        
$table_data "";

        
// loop over the array of data
        
foreach( $data as $key=>$value )
        {
                
// add to the table_data
                
$table_data .= "<tr><td>$key</td><td>$value</td></tr>";
        }

        
// display the data
        
echo $table_data;
?>

index.php


<html>
<head>
<title>Introduction to PHP and JQuery</title>
<script src="/js/jquery-2.2.0.min.js"></script>
<script src="/js/tute.js"></script>
</head>
<body>
<h2>Introduction To PHP and JQuery</h2>

<button id="getData">Get Data</button>
<br><br>
<table id="dataTable">
<thead><tr><th>ID</th><th>Name</th></thead>
<tfoot><tr><th>ID</th><th>Name</th></tfoot>
<tbody>
<tr><td colspan="2">No Data Supplied</td></tr>
</tbody>
</table>


</body>
</html>

tute.js


/* wrap code in .ready */
$(document).ready(function(){
        /* a message to insert into a div with class of msgClass */
        $(".msgClass").html("Click Button To Toggle Me");

        /* a .click event */
        $("#getData").click(function(){
                $.get("request.php", function(data, status){
                        $("#dataTable tbody").html(data);
                });
        });
});

Once again, a lot going on here. In the request.php file, the array has been converted into table rows. The heavy lifting, or conversion, of the data to HTML is handled by the server. This could be done with javascript, but is generally regarded as a Bad Idea(tm).

The index file contains a button which is used again as the trigger event to populate the rows in the table below it. When clicked, a GET request is sent to the request.php file and the table rows are returned, and assigned to the tbody element of the table with the id of dataTable.

The initial page looks like this:

Introduction To PHP and JQuery



ID Name
ID Name
No Data Supplied

Then, when the button is clicked, the table rows are inserted.

Introduction To PHP and JQuery



ID Name
ID Name
0 dingo
1 wombat
2 Steve Irwin
3 kangaroo
4 kiwi
5 kookaburra

POST

POST requests deal with sending data to the server, and getting a response back letting you know if the POST was successful or not. At its simplest, this is as easy to achieve as a GET request.

index.php


<html>
<head>
<title>Introduction to PHP and JQuery</title>
<script src="/js/jquery-2.2.0.min.js"></script>
<script src="/js/tute.js"></script>
</head>
<body>
<h2>Introduction To PHP and JQuery</h2>

<button id="buttonId">Post Me!</button>

<div id="msgId"></div>
</body>
</html>

request.php


<?php
// assign the variables. You may wish to add some validation here..
$name $_POST['name'];
$email $_POST['email'];

// echo the response
echo "The user $name has email address $email";
?>

tute.js


/* wrap code in .ready */
$(document).ready(function(){
        $("#buttonId").click(function(){
                $.post("request.php",
                {
                        name: "Big Kev",
                        Email: admin@qrdvark.com "big@kev.com"
                },
                function(response, status){
                        $("#msgId").html("Response: " + response + "<br>Status: " + status);
                });
        });
});

The code above, should by now, look self evident. The index.php file contains a button with the id of buttonId, and an empty div with the id of msgId.

The button has a .click event attached to it, so when it is clicked, the action is run and the div with the id of msgId is populated with the return data from request.php.

AJAX

Hic Sunt Dracones

index.php


<html>
<head>
<title>Introduction to PHP and JQuery</title>
<script src="/js/jquery-2.2.0.min.js"></script>
<script src="/js/tute.js"></script>
</head>
<body>
<h2>Introduction To PHP and JQuery</h2>

<form id="myForm" method="post">
<input type="text" name="name" id="name" value="Big Kev" /><br /><br />
<input type="email" id="email" name="email" value="big@kev.com" /><br /><br />
<input type="submit" value="Ajax Submit" />
</form>

<div id="formMsg"></div>
</body>
</html>

request.php


<?php

// placeholder for errors
$errors = [];
$success = [];

// 
if( isset( $_POST['email'], $_POST['name'] ) )
{
        if( 
filter_var($_POST['email'], FILTER_VALIDATE_EMAIL ) )
        {
                
// add to the success array
                
$success['email'] = 'valid';
        }
        else
        {
                
// add to the errors array
                
$errors['email'] = 'Email is invalid';
        }

        
// validate the name
        
if( strlen$_POST['name'] ) > && strlen$_POST['name'] ) < 10 )
        {
                
// add to the success array
                
$success['name'] = 'valid';
        }
        else
        {
                
// add to the errors array
                
$errors['name'] = "Name must be between 2 and 10 characters";
        }
}
else
{
        
$errors['name'] = 'Email and Name are mandatory fields';
}

// if there are errors, we send the errors array, else send success array
$return sizeof$errors ) > $errors $success;

// convert to json 
echo json_encode$return );

?>

tute.js


/* wrap code in .ready */
$(document).ready(function(){
        /* a message to insert into a div with class of msgClass */
        $(".msgClass").html("Click Button To Toggle Me");


        $( "form" ).submit(function( event ) {

                // prevent the form from submitting
                event.preventDefault();

                // a little js validation
                if ( $( "#name" ).val() === "" ) {
                        $( "#formMsg" ).html( "Name is mandatory" ).show().fadeOut( 2000 );
                        return;
                }

                // check an email was sent
                if ( $( "#email" ).val() === "" ) {
                        $( "#formMsg" ).html( "Email is mandatory" ).show().fadeOut( 2000 );
                        return;
                }

                // serialize the form data
                dataString = $("#myForm").serialize();

                $.ajax({
                type: "post",
                url: "request.php",
                data: dataString,
                dataType: "json",
                success: function(response) {
                        // check if we have a valid response
                        if( response.email == "valid" && response.name == "valid" ){
                                $("#formMsg").html('All is well');
                        } else {
                                // get the email response if it is set
                                if( typeof(response.email) != "undefined" && response.email !== null ){
                                        // send response message to the div with id formMsg
                                        $("#formMsg").html( response.email );
                                }
                                // get the name response if it is set
                                if( typeof(response.name) != "undefined" && response.name !== null ){
                                        // send response message to the div with id formMsg
                                        $("#formMsg").html( response.name );
                                }

                        }
                },
                error: function (request, status, error) {
                        $("#formMsg").html('Error: ' + request.status + error);
                }

                });

        });
});

OK, so a good deal going on here. The index.php file contains a simple form with two fields. When the form is submitted, the JQuery takes over the handling of the form and prevents the form from submitting. Instead, control of whether the form will be submitted or not is done in the JQuery logic.

Some simple validations are run by JQuery, and if successful, the form data is serialized and sent to the request.php file for processing. Some more validations are done in request.php and if all is well, the form returns with valid values for email and name. The .html() action is run and messages are recieved just below the form in the div with the ID of formMsg.