Marc Ermshaus’ avatar

Marc Ermshaus

Linkblog

Algorithmic Advent: 14 – PHP/jQuery Ajax testing template

Published on 14 Dec 2010. Tagged with php, algorithmicadvent.

I wrote this template because I was getting tired of always having to piece together all of the different components and the exact syntax of the jQuery .ajax() method whenever I wanted to build a simple testing environment for Ajax calls.

<?php

if (isset($_GET['ajax'])) {
    if (!isset($_POST['action'])) {
        exit;
    }

    switch ($_POST['action']) {
        case 'demo1':            
            echo json_encode(array('test' => 'Hello world!'));
            break;
        default:
            break;
    }

    exit;
}

?><!DOCTYPE html>

<html>

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Ajax testing template</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>

        <script type="text/javascript">

            function ajaxCallDemo1()
            {
                $.ajax({
                    type     : "POST",
                    async    : true,
                    url      : "?ajax",
                    cache    : false,
                    data     : {action      : 'demo1'},
                    dataType : 'json',
                    success: function(data) {
                        $('#demo1').html(data['test']);
                    },
                    error: function() {
                        alert("Something went wrong");
                    }
                });
            }

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

        </script>
    </head>

    <body>
        <div id="demo1"></div>
    </body>

</html>