jQuery - AJAX - PHP:

Create JSON response for jQuery

Description

jQuery-PHP is a PHP library that allows to tie jQerry 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
  1. require_once 'libraries/jQuery.php';
  2. // many actions
  3. // ...
  4.  
  5. // get JSON response
  6. jQuery::getResponse();
HTML: initialize jQuery and jQuery.php
  1. <script src="javascript/jquery.js" type="text/javascript"></script>
  2. <script src="javascript/jquery.php.js" type="text/javascript"></script>
JavaScript: call AJAX (example)
  1. // do an ajax post request (example)
  2. jQuery.extend({
  3. php: function (url, params) {
  4. // do an ajax post request
  5. $.ajax({
  6. // AJAX-specified URL
  7. url: url,
  8. // JSON
  9. type: "POST",
  10. data: params,
  11. dataType : "json"
  12. })
  13. }
  14. });

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):
  1. jQuery('#test0') -> html('new content');
This is PHP code equal JavaScript (click to run):
  1. // set new content to element with ID test0
  2. $('#test0').html('new content');
old content

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

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

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

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

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

Send a Form

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

Result:

HTML:
  1. <form id="form" onsubmit="formAjax();return false;">
  2. <input type="hidden" name="act" value="form"/>
  3. Field 1: <input type="text" name="field1" maxlength="255"/>
  4. Field 2: <input type="text" name="field2" maxlength="255"/>
  5. Field 3: <input type="text" name="field3" maxlength="255"/>
  6. <input type="submit" name="submit" value="submit"/>
  7. </form>
JavaScript (use jQuery Form plugin):
  1. formAjax = function () {
  2. $.php(url, $('form#form').formToArray(true));
  3. return false;
  4. }
JavaScript (advanced):
  1. formAjax = function () {
  2. // do an ajax post request
  3. $.ajax({
  4. // AJAX-specified URL
  5. url: url,
  6. // JSON
  7. type: "POST",
  8. data: $('form#form').formToArray(true),
  9. dataType : "json",
  10.  
  11. /* Handlers */
  12. // Handle the beforeSend event
  13. beforeSend: function(){
  14. return php.beforeSend();
  15. },
  16. // Handle the success event
  17. success: function(data, textStatus){
  18. return php.success(data, textStatus);
  19. },
  20. // Handle the error event
  21. error: function (xmlEr, typeEr, except) {
  22. return php.error(xmlEr, typeEr, except);
  23. },
  24. // Handle the complete event
  25. complete: function (XMLHttpRequest, textStatus) {
  26. return php.complete(XMLHttpRequest, textStatus);
  27. }
  28. });
  29. return false;
  30. }
PHP:
  1. $field1 = isset($_REQUEST['field1'])?$_REQUEST['field1']:'';
  2. $field2 = isset($_REQUEST['field2'])?$_REQUEST['field2']:'';
  3. $field3 = isset($_REQUEST['field3'])?$_REQUEST['field3']:'';
  4. $response = 'Field 1 = "'.htmlentities(stripslashes($field1)).'"<br/>'.
  5. 'Field 2 = "'.htmlentities(stripslashes($field2)).'"<br/>'.
  6. 'Field 3 = "'.htmlentities(stripslashes($field3)).'"<br/>';
  7.  
  8. jQuery('#testform')->html($response);

Handle System Events

Create loading image (like under right menu), click to run:
  1. // example registering custom beforeSend function
  2. php.beforeSend = function (){
  3. $('#loading').slideDown('fast');
  4. }
  5.  
  6. // example registering custom complete function
  7. php.complete = function (){
  8. $('#loading').slideUp('slow');
  9. }

Change default error reporting:
  1. // example registering custom error function
  2. php.error = function (){
  3. alert("Something wrong");
  4. }
  5. // example registering still error function
  6. php.error = function (){
  7. return true;
  8. }

Additional Actions

addMessage():

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

addError():

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

addData():

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

evalScript():

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

Change Callback functions


Show "Loading..." status

Element with id = "loading" - is our "Loading..." image:
<script type="text/javascript">
$(document).ready(function(){
    php.beforeSend = function() {
        $('#loading').show();
    };
    php.complete   = function(XMLHttpRequest, textStatus) {
        $('#loading').hide();
    };
});
</script>

Change error callback

Change to alert (O_o):
<script type="text/javascript">
php.error = function(xmlEr, typeEr, except) {
    alert(xmlEr);
}
</script>

Mute mode:
<script type="text/javascript">
php.error = function(xmlEr, typeEr, except) {}
</script>

Menu

  1. Introduction
  2. Requirements
  3. Download
  4. Examples