jQuery: self-processing AJAX request

In PHP, self-processing pages are those pages that are able to process the data passed along an HTTP URL in the form of a GET or POST request. In this post I'm going to show you what happens when we use these pages together with a jQuery AJAX request. The first thing we need to do is to set up our server-side code at the very top of our page, like so:

<?php

$q = $_GET['q'];

if(isset($q)) {

    if($q != 'Test') {

    	echo 'Invalid parameter';
    	exit();

    }

    echo $q . ' OK';

    exit();

}
?>

The GET parameter called q must be set and contain only the string 'Test'. Note that when our script has finished, we exit from the PHP code. This is due to the fact that otherwise our AJAX request will return the entire page and not only the message we want. Now jQuery:

$(document).ready(function() {

    $('#run').click(function(e) {

    	$.ajax({
    	  type: 'GET',
    	  url: location.href,
    	  data: 'q=Test',
    	  success: function(message) {

    	      alert(message);

    	  }
    	});

    e.preventDefault();
    });

});

We've used the href property of the location object to make sure that our AJAX URL points to the page in use, that is, our self-processing page. You can see the demo below.

Demo

Live demo

Comments are closed.