jQuery - AJAX - PHP:

Create JSON response for jQuery

Description

jQuery-PHP is a PHP library that allows to tie jQuery with PHP most natural way. You don't need to think in terms of transmission, parsing and other boring staff. Now you have a bridge that brings DOM right onto your server :) and you can ealisy manipulate it in jQuerry-style way.

Zend Framework

It's easy, read article how integrate jQuery-PHP with Zend Framework

Initialize

PHP: require jQuery library
                require_once 'libraries/jQuery.php';
                // many actions
                // ...
                
                // get JSON response
                jQuery::getResponse();
HTML: initialize jQuery and jQuery.php

JavaScript: call AJAX (example)
                // do an ajax post request (example)
                jQuery.extend({
                   php: function (url, params) {
                      // do an ajax post request
                      $.ajax({
                          // AJAX-specified URL
                          url: url,
                          // JSON
                          type: "POST",
                          data: params,
                          dataType : "json"
                      })
                   }
                });
                

Requirements:

System requirements

  • PHP 5.2.0 or higher (with JSON extension)
  • jQuery 1.1.2 or higher

Download:

Google Code

Web Access: SVN Command-Line Access:
svn checkout http://jquery-php.googlecode.com/svn/trunk/ jquery-php-read-only

Ads:

Google Ads

Examples:

Should be work...

jQuery

Assign html by ID (click to run):
jQuery('#test0') -> html('new content');
This is PHP code equal JavaScript (click to run):
// set new content to element with ID test0
$('#test0').html('new content');
old content

Assign html and chage CSS by ID (click to run):
jQuery('#test1') -> html('new content')
                 -> css('backgroundColor' , '#ffff00');
This is PHP code equal JavaScript (click to run):
// set new content to element with ID test1 and change CSS options
$('#test1').html('new content')
           .css('backgroundColor' , '#ffff00');
old content

Assign html and chage CSS by Path (click to run):
jQuery('#test2 div') -> html('new content');
jQuery('#test2 div.red') -> html('new content')
                         -> css('backgroundColor' , '#ff0000');
This is PHP code equal JavaScript (click to run):
// set new content to element by Path and change CSS options by another Path
$('#test2 div') .html('new content');
$('#test2 div.red').html('new content')
                   .css('backgroundColor' , '#ff0000');
old content
old content
old content

Bind event by Path(click to run):
// event function
function eventAlert(event) {
    alert('Run "eventAlert": ' + event.data.test);
}
jQuery('#test3 div') -> bind('click', array('test'=>'answer'), 'eventAlert')
                     -> css ('cursor', 'pointer')
                     -> css ('color', '#0000ff')
                     -> css ('textDecoration', 'underline');
This is PHP code equal JavaScript (click to run):
// set event to elements by Path and change CSS options
$('#test3 div').bind('click', {'test':'answer'}, eventAlert)
               .css('cursor', 'pointer')
               .css('color', '#0000ff')
               .css('textDecoration', 'underline');
Element 1
Element 2
Element 3

Use animate (click to run, restore):
jQuery('#test4 div.hide') -> css ('color', '#ff0000')
                          -> animate (array('opacity'=>'show'), 1000);
This is PHP code equal JavaScript (click to run):
$('#test4 div.hide').css ('color', '#ff0000')
                    .animate ({'opacity':'show'}, 1000);
old content

Use animate with callback (click to run, restore):
var eventHideCounter = 0;
function eventHide() {
    alert('Run "eventHide" (count:'+ ++eventHideCounter +')');
}
jQuery('#test5 div.hide')-> slideUp(500, 'eventHide');
This is PHP code equal JavaScript (click to run):
$('#test5 div.hide').slideUp(500, eventHide);
content
old content
content

Send a Object as JSON

This is example use json2.js library.
Click here for send a Array to server side:

HTML:
                    Click here ...
                    
JavaScript:
                    getJson = function () {
                      // isn't requried
                      var args = Array.prototype.slice.call(arguments);
                      $.php(url,{act:'json',data:JSON.stringify(args)});
                    }
                    
PHP:
                    ob_start();
            	    var_dump(json_decode(stripslashes($_REQUEST['data'])));
            	    $data = ob_get_contents();
            	    ob_end_clean();
            	    jQuery('#testjson')->html('
'.$data.'
');

Send a Form

Form Example:
  • Field 1:
  • Field 2:
  • Field 3:

Result:

HTML:
                    
Field 1: Field 2: Field 3:
JavaScript:
                    formAjax = function () {
                        $.php(url, $('form#form').serialize());
                        return false;
                    }
                    
PHP:
                    $field1 = isset($_REQUEST['field1'])?$_REQUEST['field1']:'';
                    $field2 = isset($_REQUEST['field2'])?$_REQUEST['field2']:'';
                    $field3 = isset($_REQUEST['field3'])?$_REQUEST['field3']:'';
                    $response = 'Field 1 = "'.htmlentities(stripslashes($field1)).'"
'. 'Field 2 = "'.htmlentities(stripslashes($field2)).'"
'. 'Field 3 = "'.htmlentities(stripslashes($field3)).'"
'; jQuery('#testform')->html($response);

Handle System Events

Create loading image (like under right menu), click to run:
// example registering custom beforeSend function
php.beforeSend = function (){
    $('#loading').slideDown('fast');
}
 
// example registering custom complete function
php.complete = function (){
    $('#loading').slideUp('slow');
}

Change default error reporting:
// example registering custom error function
php.error = function (){
    alert("Something wrong");
}
// example registering still error function
php.error = function (){
    return true;
}

Additional Actions

addMessage():

Return message (click to run):
jQuery::addMessage('Message 1...');
jQuery::addMessage('Message 2...');
Message handler: you can reset default callback function:
// example registering simple callback function for messages
php.messages.defaultCallBack = function (msg, params){
    alert ("My messages CallBack func: " + msg);
}
Or create own callback function (click to run):
// example registering simple callback function for messages
php.messages.myCallBack = function (msg, params){
    alert ("My messages CallBack func: " + msg);
}
and call it from PHP:
jQuery::addMessage('Message...', 'myCallBack');

addError():

Return error (click to run):
jQuery::addError('Error 1...');
jQuery::addError('Error 2...');
Errors handler equal to messages handler

addData():

Return data (click to run):
jQuery::addData('key1', 'value1');
jQuery::addData('key2', 'value2', 'myCallBack');

evalScript():

Eval script (click to run):
jQuery::evalScript('alert("Eval script...");');

Change Callback functions


Show "Loading..." status

Element with id = "loading" - is our "Loading..." image:

Change error callback

Change to alert (O_o):


Mute mode: