Tutorial: AJAX Through PHP and jQuery

Here is a simple example of using AJAX with PHP and jQuery. The AJAX just outputs the GET variables that were sent back to the page, and the jQuery handler adds that to the div with id of “content”. You might also want to check out the jQuery.ajax() documentation after looking over this example.

Caveat 1: Normally when doing AJAX, I’d recommend having the “server” page (that accepts AJAX requests and returns a response) be a separate PHP file, but for ease of explanation I’ve included everything in one big file here.

Caveat 2: In production you’ll also probably want to use POST instead of GET, and send data over an https connection for security. The GET data itself is still encrypted when it goes over https, but it is kept in plaintext in server logs, and your browser’s history, so the data in there is not actually all that secure.

<?php
 /*
  * This page just demonstrates a simple AJAX call using jQuery.
  * by: Mike Todd (http://thezencoder.com)
  */

// Check to see if we are doing something AJAX-y
if ($_GET['ajax_call'] == 1) {
 	// Connect to database
 	try {
		$db = new PDO("mysql:host=localhost;dbname=db_here", "db_user", "db_pass");
	} catch (PDOException $e) {
		die(json_encode(array('status'=>'fail', 'message'=>'Could not connect to database: '.$e->getMessage())));
	}

	// Do some database stuff -- insert, select, or whatever...

	sleep(1); // DEBUG: Add in a delay, just for testing purposes so you can see the "loading" icon

	// Return some JSON data
	$ret = array('status'=>'success', 'message'=>'GET variables sent: '.print_r($_GET, true));
	echo json_encode($ret); // Have PHP encode the result as JSON, which jQuery is expecting due to dataType parameter
	die(); // Stop output here since we've handled the AJAX response
}
?>

<html>
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
    <script type="text/javascript">
    function doAjax() {
        //generate the parameters for the AJAX call
        var send_data = 'ajax_call=1&text=' + encodeURIComponent($('#send_message').val());

        $.ajax({
            url: "<?php echo basename($PHP_SELF); ?>", // Post to the current page (in production you should send to another page)
            type: "GET",
            data: send_data,
            dataType: "json",  // Return data type
            cache: false,
            success: function (data) {

                $('#loading').hide();  // We've got the result, so hide the "loading" icon

                if (data['status'] == 'success') {
                    // Add the content retrieved from ajax and put it in the #content section
                    $('#content').append('<br />'+data['message']);
                } else {
                    // Maybe add some error handling here
                    $('#content').append('<br /><font color="red">Failure:</b> '+data['message']);
                }

            }
        });
    }
    </script>
</head>
<body>

 Some text: <input id="send_message" type="text_field" value="test" />
 <button id="submit_input" onclick="$('#loading').show(); doAjax();">Click me</button>
 <img id="loading" style="display: none;" src="http://www.freeiconsweb.com/Icons-show/loading/loading1.gif" alt="" />
 <span style="text-decoration: underline;">Messages</span>

</body>
</html>

Category(s): Code Snippets, Web Design
Tags: , , ,

One Response to Tutorial: AJAX Through PHP and jQuery

  1. Facebook had a cross-posting application which was being wonky, so apologies if you saw this twice. I’ve uninstalled the one from Facebook, and gone back to the tried and true Wordbooker plugin.

Leave a Reply

Your email address will not be published. Required fields are marked *