Learning how to use jQuery AJAX with PHP [video tutorial]

Getting started with AJAX is super easy when you use the jQuery library. That works well for the client side, but how do you work with a server side language like PHP? It’s easier than you think.

In this article, I’ll show you how to create a simple call to a PHP document that will process something you type into a form field and update an element without needing to refresh your browser. Once you learn how to get jQuery talking to PHP, your web applications will never be the same.

What is AJAX?

AJAX, stands for Asynchronous JavaScript and XML. It’s just a way to have the client request data from the server without having to reload the page. jQuery has a number of built-in AJAX functions.

Most of the time, you’ll use one or two of them, but there is one method that rules them all. It’s the generic version of the call and it’s simply called ajax(). Learning how to use that method will take care of most of the types of request you’ll need for your apps.

Setting up your PHP

Before we dig into the AJAX call, let’s create a small PHP script that we can use. It doesn’t have to be too complicated. Our script will take a domain name and return the IP address of the server it belongs to. The IP address is the physical location of the server on the internet. When you type in a domain into a browser like http://iviewsource.com, the domain gets converted to an IP address that your browser knows how to find on the internet.

PHP has a built in function called gethostbyname(). It returns the IPv4 address of a hostname.

You would use it like this:

    echo(gethostbyname('iviewsource.com'));

So the script we’ll write will use the server variable $_GET and output the IP address. Your finished code should look like this:

<?php
    if ($_GET['ip']):
        $ip = gethostbyname($_GET['ip']);
        echo($ip);
    endif;  
?>

Coudn’t be simpler. To make sure this is working save this file as reverseip.php and upload it somewhere on your server. To test it out, type in a URL to it like:

http://yourwebsite.com/getip.php?ip=iviewsource.com

Assuming you placed the file in the root of your browser, this should return a number like 64.207.155.59. Don’t type in the http://, just the domain name or it won’t work.

If that’s working fine, you’re ready for some AJAX.

Preparing the page

First, we need to create a page that use the jQuery library. That code will look like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Get Reverse IP</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
</body>
</html>

This shell is just an empty page that calls the jQuery library from Google’s CDN. A Content Delivery Network that keeps a copy of popular libraries like jQuery.

Now, we’ll need to create a couple of elements. One that will let us type in the domain, and one that will display what we get back from our PHP document.

Let’s keep it simple and use this:

Please enter a domain name
<input type="text" id="searchip">
<div id="resultip"></div>

Now, let’s start writing the script that will trigger our AJAX call. This is usually placed at the bottom of the screen right before the closing <body> tag.

<script>
    $(document).ready(function() {
    }); //document.ready
</script>

This script will just execute our code as soon as the document has finished loading. The next step would be to run a function when something happens. So, since we’re using an input field, we can check to see when the input changes.

<script>
    $(document).ready(function() {

        $('#searchip').change(function(){
        }); //event handler

    }); //document.ready
</script>

This is called an event handler. Different types of html elements require that you use different types of event handlers. jQuery event handlers are similar, but a little different than JavaScript event handlers. In our case, we’re interested in the change() event that happens when an input field or a select field change in value.

Ready for the AJAX

We’re now ready for the AJAX call. We’ll use the generic ajax() jQuery method. It looks like this.

<script>
    $(document).ready(function() {
        $('#searchip').change(function(){

            $.ajax({
            }); // Ajax Call

        }); //event handler
    }); //document.ready
</script>

The AJAX call can be done in a couple of ways: You can pass along a URL as well as some settings, or just pass a JSON object with the settings. This second way works really well. I need to set up four variables.

<script>
    $(document).ready(function() {
        $('#searchip').change(function(){
            $.ajax({

                type: "GET",
                url: "getip.php",
                data: 'ip=' + $('#searchip').val(),
                success: function(msg){
                    $('#resultip').html(msg);
                }

            }); // Ajax Call
        }); //event handler
    }); //document.ready
</script>

The type variable tells the browser the type of call you want to make to your PHP document. You can choose GET or POST here just as if you were working with a form.

tweNext is the URL of the php file you want to call. Since this file is in the same folder, you can just use the name, otherwise use the full http:// url.

Note: The files should be in the same domain name in order to work. Also, because you’re working with an external server, some browsers (like Chrome) won’t let you call in a server from a local file, so make sure both of these files are in a server.

data is the information that will get passed onto your form. We want to pass a single variable called ip, so we start off by using the text ip= and then we add the value of whatever is in our form field.

success is what jQuery will do if the call to the PHP file is successful. I’m passing along a variable called msg. That will have anything we echo or print from our php document. This can get more complicated, but all we need to do for our simple application is to set the html of #resulttip to this message.

If you’ve done everything correctly, you should see the IP address of the domain you typed in. That means you successfully called a PHP script that did something and send some information back to your HTML page. A classic AJAX call in just a few lines of code.

8 thoughts on “Learning how to use jQuery AJAX with PHP [video tutorial]

  1. therion31Nick

    I’m new to ajax and have watched and read a couple of your videos (including the video on Lynda). I am having problems being able to see the json file when working in WordPress. Basically, I have json file with a bunch of information and I want to be able to load the info based on user input (almost 90% similar to your Ajax Search Video on Lynda). The problem is that I keep getting a 404 error that the file can’t be found. Is there something that needs to be done differently to access a json or txt file that is on the same server as the rest of the files?

    Thanks for the videos as well.

    Reply
  2. Michael

    I know no other way of contacting you. With reference to your Lynda.com course Javascript and Json. I get the following error for excercise 3-03 Uncaught Error: SecurityError: DOM Exception 18 db.get GPLCOMM.receiveMessage

    Reply
    1. Michael

      After much frustration I finally found the error. It was mine, I included wrapper dataHandler({.. But it was all worth while as I will now visit your tutorials. I’m about to view your companion Lynda.com course. Thanks.

      Reply
  3. Pingback: Getting Undefined index: url from ajax result | BlogoSfera

  4. Robert

    I’m trying to view info from a database table when a user is selected from a dropdown menu. I’ve been told that I need to use AJAX to do this. However, I’ve been unable to find any help. Could you possibly provide assistance?

    Reply
  5. andre

    Thank you, after years working with a paired vanilla ajax and php app, i am finally taking the time to get with the jquery stride. My first order of business was to learn the how to ajax with my favorite db using jquery and 2 searches later i discovered your post ! I appreciate the time you took to share your knowledge.

    Reply

Leave a Reply