Mating Jquery and PHP

 Programmers now adays are all about the dynamic generation of pages. This means that a single page's content is generated on the fly and is not hardcoded or handwritten by the programmer. Today I want to show you how we can change the look and content of a webpage without ever hitting the refresh button.

This Hub assumes that you have some knowledge of the basics of PHP and HTML. I will explain all the ajax / jquery stuff in here, so don't worry about that! I will also be using some SQL queries to access a database but that should be pretty straight forward.

PHP
PHP
JQuery
JQuery

There are many uses for PHP. Most sites are written in either PHP or ASP (though more and more languages are popping up over the internet these days). AJAX Just adds to the usefulness of it.

Let's Define!

One of the first things that some people like to know is: what am I even saying? PHP stands for "PHP: Hypertext Preprocessor". Yes, I know. the acryonym is in the name itself. You could go on forever saying what PHP stands for, literally. AJAX stands for "Asynchronous, JavaScript, And XML".

I like meat and potatoes, do you?

Let's jump right into the main example for this hub. While there are many applications such as form validation, updating tables, searching, anything that requires an SQL query, etc. We are going to focus on updating a simple table on the fly.

As im sure you have all been to facebook before, you know that as you type in the search box, your friends automatically appear and filter via the current string you have in the box. We are going to do something very similar here. (Facebook doesn't use JQuery, the use straight up AJAX DOM coding with javascript. Lame, I know, right?)

First let's define what our database table will look like for reference:

 id
firstname 
lastname 
birthday
1
John 
Smith 
January 4th 
2
Jack 
Brown 
April 7th
3
Daniel 
Gordon 
November 2nd

 So looking at our table we see we have 3 entires, It is easy enough to print these values out onto the screen with PHP, but what if you wanted to search for someone's birthday just by typing in their name, but you don't want to submit a form or refresh the page. Let's take a look at how we will setup the HTML

...
<input id="search-box" /><br />
<div id="info-box">
Enter in a search above to get the content of the database
</div>
...

This is a very basic example as you can see. We are going to requery the database everytime you life your finger. So let's take a look at the JQuery code for this, then I will explain it.

$(document).ready(function() {
   
  $('#search-box').keyup(function(e) {
       var box = $('#search-box').attr('value');

       if(box == '')
       {
          $('#info-box').html('Enter in a search string');
          return false;
       }

       $.post('get_query.php', {query: box}, function(data) {
            $('#info-box').html(data);

       }); // end ajax call (post method)
 
  }); // end keyup event


}); // end jquery

 This shouldn't look too overwhelming to you, as it's very simple. Ofcourse, make sure this code is inside of a SCRIPT tag in your HTML, preferably in your HEAD section.

$(document).ready(function() { ... });

This line starts the jquery. You will put all of your jquery commands inside of this function. Basically this means that once the document is ready, run the functions inside, which are your events. this makes sure all of your HTML objects are loaded before mixing them with the javascript code.

$('#search-box')

This is a selector. this is similar to CSS in that the # sign means 'id' and the . means 'class'. since we gave our input box an id called 'search-box' we will use this select to tell the javascript which object we mean, in this case, the input box.

.keyup(function(e) { ... });

the . after the select means what event or function you want to use on that object. There are many different events you can use such as .click() .live() .hover()  just to name a few. Once we lift our finger off a key, it will execute the nested function, and pass the key that was pressed to 'e'.  now in our example we don't really care which key was pressed so we don't pay attention to the variable e but it's good to know it's there.

var box = $('#search-box').attr('value');

Assign a variable in javascript named box, and give it the value of the attribute 'value' from the object with the id 'search-box'. Lots of words, but basically it means get the content from the input box. we use the word 'value' in .attr() because that is what the value is saved to in HTML. you can access any attribute with this command.

Our if statement basically says that if the box is empty, don't run a search, it would be a waste of our time. Just update the box to say 'Enter in a search string' and then return out of the function

Now for the AJAX fun!

$.post('get_query.php', {query: box}, function(data) { ... });

This sends a POST method to the first parameter, the provided PHP script. just like with regular HTML form submission, you have $.post and $.get and they both work the same way, but your browser screen will never see the URL for this unless someone looks at the code (which isn't difficult).

Next you have {query: box} these are the variables you want to send to the script. we are sending to the PHP script a variable named 'query' and passing it the value of 'box' that we set earlier. You can pass multiple variables to a script by seperating them with a , (comma). {query: box, number: 1, other: 16}

functoin(data) { ... }

this function will execute when the data is returned from the script successfully, and the value of data is what is returned. In our example, this value will be the names of the people and their birthday. We display it with $('#info-box').html(data); Set the HTML code inside of the HTML object with the ID 'info-box' to be the value of 'data'

Now let's take a look at our PHP code

<?php

...
// you might want to have a safe() function of sorts to make sure what the user is sending you isn't an SQL injection, tricky hackers!

$query = safe($_POST['query']);

$q = mysql_query('SELECT * FROM `table_name` WHERE `firstname` LIKE "'. $query .'"%;', $connection);
while($row = mysql_fetch_array($q))
{
    echo $row['firstname'] .' '. $row['lastname'] .' has a birthday on '. $row['birthday'] .'<br />';
}


?>

One of the major things to remember as a programmer is to trust no one. While most of your users will most likely be using your site properly and nothing will go wrong, there are some other there that don't work the same way.

While I can't really show you an example with this on here, you should try it out on your own and tweak it to work the way you want!

The code above put together will update all the information you want on the screen in real time without having to hit refresh or load a new page!

By hitting 'D' the content of the box will be:

  • Daniel Gordon has a birthday on November 2nd

By hitting 'J' the content of the box will be:

  • John Smith has a birthday on January 4th
  • Jack Brown has a birthday on April 7th

and by hitting 'Jo" the content of the box will be:

  • John Smith has a birthday on January 4th

I hope this hub was helpful and you all become JQuery masters!! Best of luck, and feel free to leave any questions in the comments section!

More by this Author

  • Regex for BBCode in PHP
    5

     Regular Expressions (Regex) are a way to parse information and match it with a larger string. For example, If you wanted to validate an email address, you could write a regular expression that would try and match...


Comments 2 comments

agvulpes profile image

agvulpes 6 years ago from Australia

Interesting topic I have just started learning PHP , cos I believe I will need it to get full use of Joomla and wordpress.


thesinkfiles profile image

thesinkfiles 6 years ago Author

This is true, while many aspects of CMS (content management systems) are customizable via a control panel they supply, getting knee deep into the code will really help make it your own and get things exactly how you want them.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working