PHP Classes

File: ajax.php

Recommend this page to a friend!
  Classes of Kristo Vaher   Smart AJAX Controller   ajax.php   Download  
File: ajax.php
Role: Example script
Content type: text/plain
Description: AJAX backend file that jQuery submits data to and waits for a response from
Class: Smart AJAX Controller
Generate AJAX request responses in JSON format
Author: By
Last change:
Date: 14 years ago
Size: 1,454 bytes
 

Contents

Class file image Download
<?php

   
//including the class file
   
require('class.smartajaxcontroller.php');
   
   
//Initializing the controller
    //Output buffer will be used to later on return the result in gzip
   
$ajax=new SmartAjaxController();
   
   
//If AJAX has submitted a serialized string to be parsed to variables.
   
if(isset($_POST['data'])){
       
//These variables can be used by $ajax->getVar funtion
       
$ajax->setInputVariables($_POST['data']);
    }

   
//This is dependant on javascript front-end controller, used as an example
   
if(!empty($_POST) && isset($_POST['action'])){
   
       
//this assumes that action is defined by jQuery before being submitted to back-end
       
switch($_POST['action']){
       
           
//This is the same example used in javascript file
           
case 'alertLowercaseString':
               
$ajax->setKey('action','alert');
               
$ajax->setKey('message','Your string lowercased: '.strtolower($ajax->getVar('string')));
            break;

            default:
               
//If no action is found, execute frontend error callback
               
$ajax->setKey('error',1);
               
$ajax->setKey('message','This system action does not exist!');

        }
       
    } else {
       
//Since no action was defined or no post was used at all, we simply set the response to return errors to front-end
       
$ajax->setKey('error',1);
       
$ajax->setKey('message','This system action does not exist!');
    }
   
   
//Here we return the result in gzipped JSON string
    //This also sets proper headers to the file
   
$ajax->output();

?>