PHP JSON Functions

The 2 functions contained in the above file can be used to take a PHP array and convert it into JSON format so it can be passed to a javascript function via an AJAX callback. If the json_encode() function exists, as with most recent versions of PHP5, then json_encode() is used. If not, a simple helper function is used instead. The sendAjaxResponse() function contains several lines which are specific to using this function with CakePHP that have been commented out.

View Source Code for json_functions.php

JSON Tutorial Using the Above Functions

The JSON format is ideal for sharing data between PHP and Javascript. Among other uses, JSON can be used to pass the results of a database query or PHP function to a javascript function via an AJAX call. In the example below, we have set up a PHP function to check whether a given login name is available or has been used already.

<?php

// Read in the provided login name from the AJAX request's
// query string
$loginName $_GET['login_name'];

// Create the $returnArray we'll use to send data back 
// to the javascript callback function
$returnArray = array();

// Include the login name they provided in the results
$returnArray['providedLogin'] = $loginName;

// Determine if the login name is available
$sql "SELECT login FROM accounts WHERE login='{$loginName}'";
list(
$loginExists) = custom_fetch($sql);

// Store the availability of the login name in $returnArray
if ($loginExists) {
    
$returnArray['loginExists'] = true;
    
    
// Get a list of login suggestions
    
$returnArray['loginSuggestions'] = loginSuggestions($loginName);
} else {
    
$returnArray['loginExists'] = false;
}

// Finally, we convert the $returnArray into JSON format, send
// the appropriate content-type header, and output the result
// to the page via the sendAjaxResponse() function. This is the
// function which is included in the json_functions.zip file.
sendAjaxResponse($returnArray);
exit;
?>

The above PHP code would send something resembling the following to the callback javascript.

If the login is available:
{"providedLogin":"GaiusBaltar","loginExists":false}

If the login is not available:
{"providedLogin":"GaiusBaltar","loginExists":false,"loginSuggestions":["GaiusBaltar1","Gaius_Baltar","Gaius-Baltar"]}

Here is some sample javascript showing how to access the JSON data and use it to display some meaningful feedback to the user.
<script type="text/javascript">

    function handleLoginResponse(rawResponse) {
        // Callback functions from the Prototype library
        // place the content in the responseText property
        if (typeof rawResponse.responseText!='undefined') {
            rawResponse = rawResponse.responseText;
        }

        // Convert the JSON data into a javascript object
        // via the eval() function
        try {
            var response = eval('(' + rawResponse + ')')
        } catch(e) {};

        // Handle the result
        if (response.loginExists) {
            $('statusDiv').innerHTML = 'Login Available';
        } else {
            $('statusDiv').innerHTML = 'Login Not Available';
        }
    }

</script>

dlg
kruger