Bucky
Bucky

Reputation: 929

Is it possible to use AJAX POST data for the constructor values in a PHP class?

I want to call a PHP class via AJAX to process some form data. Since when you instantiate a class in PHP you can pass in values to be used in the classes constructor I wondered if the same thing was possible via AJAX?

I'm currently using the POST method with a separate function in the class to detect the post values and then process them, but I could save time by pre-loading the values in the contructor if this is possible!

Update: Code example

class myAjaxClass {
    private $data;
    public function __construct($could, $this, $be, $post, $data) {
        $this->data = $data;
        ...etc...

Upvotes: 1

Views: 2287

Answers (3)

Bucky
Bucky

Reputation: 929

In the end I decided to write a base Ajax handler class to prepare and load the POST data etc. I can then extend this with other classes for specific purposes such as 'AjaxLogin' and 'AjaxRegister'.

Here it is:

class Ajax {

    protected $data = array();
    protected $command; // Used to request a specific method.
    protected $count; // Counter for multi-page forms (Really needed?)

    /**
     * Response is the output array to be serialised using `json_encode()`
     * @var Boolean - Used to imply the success or failure of the AJAX function (i.e. form validation)
     * @var Array (optional) - An array of output / error messages [ Defined as: 'messages' => ... ]
     */
    protected $response = array('valid' => true); // Output to be serialised using 'json_encode()'

    public function __construct() {
        /* Redirect empty or insufficient POST data with 'Forbidden' response header (overwrite false) */
        if( !$_POST OR count($_POST) < 1 ) {
            header('location:'.$_SERVER['HTTP_REFERER'], false, '403');
            exit();     
        }

        /* Session validation (if 'hash' sent) */
        if( isset($_POST['hash']) AND $_POST['hash'] != md5(session_id()) ) {
            header('location:'.$_SERVER['HTTP_REFERER'], false, '403');
            exit();
        }

        $this->processRequest($_POST['data']);
    }

    protected function addMessage($message) {
        $this->response['valid'] = false;
        $this->response['messages'][] = $message;
    }

    /**
     * Unserialise AJAX data. Accepts data from either:
     * - jQuery.serialize()         [String]
     * - jQuery.serializeArray()    [Array of Objects]
     */
    private function unserializeData($data) {
        // -- from jQuery.serialize()
        if( is_string($data) ) {
            $array = explode('&', $data);
            foreach($array as $key => $value) {
                $string = preg_split('/=/', $value);
                $this->data[$string[0]] = $string[1];
            }
        }
        //  -- from jQuery.serializeArray()
        elseif( is_array($data) ) {
            $array = (array) $data;
            foreach($array as $element) {
                $this->data[$element['name']] = $element['value'];
            //  $this->addMessage($element['name'].' => '.$element['value']);
            }
        }
        else $this->addMessage('Unable to process your request, Please contact our Technical Support!');
    }

    // TODO: Use strip_tags or something for security??
    private function processRequest($data) {
        /* Process serialised data in to an Array */
        $this->unserializeData($data);

        /* Process additional POST data (if present) */
        if( isset($_POST['command']) ) $this->command = $_POST['command'];
        if( isset($_POST['count']) ) $this->count = $_POST['count'];
        // Add additional POST data processing here!!
    }
}

Feel free to use, modify, pass judgement etc. as you see fit, I hope this helps someone! ;)

Upvotes: 0

Ian Wood
Ian Wood

Reputation: 6573

The post values are superglobals so you don't need to pass them to anything. If your ajax request is calling the correct obj all you need do is use $_POST within the methods of that class...

Upvotes: 1

shadyyx
shadyyx

Reputation: 16055

By AJAX You can call only some script, e.g. my_script.php, that will look like

<?php
$myAjaxClass = new MyAjaxClass($_POST['could'], $_POST['this'], $_POST['be'], $_POST['post'], ...);
var_dump($myAjaxClass);
?>

and within JS AJAX call You have to provide the data for post, e.g. with jQuery:

$(document).ready(function(){
    $.post(
        "my_script.php",
        {could: "COULD", this: "THIS", be: "BE", ... },
        function(data) {
            alert(data); // data must be a string... when object, use data.property, when array, use data['index']
        }
    );
});

Upvotes: 1

Related Questions