Getting the JSON examples to work on PHP4.x

  • The examples provided by ext using JSON via XHR assume your php to support json_encode().
    For those running php 4.x that might not work out of the box. But it is really easy to fix:

    1.) Download JSON.php from:
    http://mike.teczno.com/JSON/JSON.phps

    2.) copy JSON.php to the example dir of ext.

    3.) Change the php file in the example as follows:
    (here i use the "ext tree" as an example)

    In: example/tree/get-nodes.php add /remark:

    require_once("../JSON.php");
    ...
    ...
    ...
    ...
    //echo json_encode($nodes);
    $json = new Services_JSON();
    echo $json->encode($nodes);


    Then it should work.

    Btw.: For those new to JSON here is a good wrap up from ibm of how to turn xml into json:
    http://www-128.ibm.com/developerworks/xml/library/x-xml2jsonphp/

    Wolfgang


  • Hi ,

    I am new to this ext js. Trying to learn now only.

    I have done some code to parse data to to the grid. But its not working fine. Please help me out. Even i downloaded the code from this link also and tried no result getting errors.
    http://www.rich-waters.com/blog/2007/11/ext-tae-boston-examples-and-slides.html

    And my code is


    echo "{'data': [
    {'Company': 'Apple', 'Price': '29.89', 'change': '0.24', 'pctChange': '0.81', 'lastChange': '09/01/2007'},
    {'Company': 'Ext', 'Price': '83.81', 'change': '0.28', 'pctChange': '0.34', 'lastChange': '09/12/2007'},
    {'Company': 'Google', 'Price': '71.72', 'change': '0.02', 'pctChange': '0.03', 'lastChange': '10/01/2007'},
    {'Company': 'Microsoft', 'Price': '52.55', 'change': '0.01', 'pctChange': '0.02', 'lastChange': '07/04/2007'},
    {'Company': 'Yahoo!', 'Price': '29.01', 'change': '0.42', 'pctChange': '1.47', 'lastChange': '05/22/2007'}]}";



    And here is Js code which i am using

    Ext.onReady(function(){
    Ext.get('okButton').on('click', function(){

    var store = new Ext.data.Store({
    // load using script tags for cross domain, if the data in on the same domain as
    // this page, an HttpProxy would be better
    proxy: new Ext.data.ScriptTagProxy({
    url: 'ajax-example.php'
    }),
    // create reader that reads the Topic records
    reader: new Ext.data.JsonReader({
    root: 'data',
    fields: [
    'Company',
    {name: 'Price', type: 'float'},
    {name: 'change', type: 'float'},
    {name: 'pctchange', type: 'float'},
    {name: 'lastChange', mapping: 'lastChange', type: 'date', dateFormat:'date'}
    ]
    }),
    // turn on remote sorting
    remoteSort: true
    });
    // create the grid
    var grid = new Ext.grid.GridPanel({
    store: store,
    columns: [
    {header: 'Company', width: 120, sortable: true, dataIndex: 'company'},
    {header: 'Price', width: 90, sortable: true, dataIndex: 'price'},
    {header: 'Change', width: 90, sortable: true, dataIndex: 'change'},
    {header: '% Change', width: 90, sortable: true, dataIndex: 'pctChange'},
    {header: 'Last Updated', width: 120, sortable: true,
    renderer: Ext.util.Format.dateRenderer('m/d/Y'),
    dataIndex: 'lastChange'}
    ],
    renderTo:'content',
    width:540,
    height:200
    });
    grid.render();
    store.load();

    });
    });

    Please find the mistake i have done in this and can you send the corrected code. Or else let me know where i can found the predefined dynamic grid data code which just i can integrate and make it run.

    Thanks in advance.
    chandra


  • I am totally confused,

    Why and where should I use the given code?
    $result = json_encode($nodes);

    and what is $nodes?

    Please help!

    the $nodes variable was only an example. You can use any variable name if you want.

    the json_encode() function turns a PHP associative array (with string, number, boolean values) into a string that will be translated into a javascript object. It's a way of formatting data for communication means just like XML. Read more about it here: http://www.json.org/


  • oh,Good!


  • This was the only thing holding me back from trying to get a working extjs webapp on the feet ..
    Thanks for this.. I didn't understand what JSON was all about till i read a little on JSON.org I have only been using XML for ajax calls so didn't understand there could be something else to pass between server and client ..

    If someone could write up a really good tutorial on PHP and JSON with extJS .. with a few examples where u use arrays and the like, I would really apreciate it.

    A simple example where you pass some data from a database to a div field .. I just need something to get started without me using hours trying with error ..

    My javascript knowledge is not good enough I guess, but this gives me hope .. I already build menu systems and pages because its so insanely simple to build with this library..


  • perfect Rich .. thx for the examples :)


  • just a small idea

    why dont the tutorial of PHP-JSON extended, and put ExtJS simple form or grid there.

    F


  • Zend Framework also has support for serializing JSON data.

    http://framework.zend.com/manual/en/zend.json.html

    i prefer to recomend reading the comparison chart (http://gggeek.altervista.org/sw/article_20061113.html), and let user decide wich one use.


  • ahh .. I was looking for PHP examples.. but thx

    I just posted a couple of very simple PHP examples (Grid & Form) that I wrote for The Ajax Experience presentation. I was using php5 so you would need to look to the above solutions in this thread if you're on an older setup.

    http://www.rich-waters.com/blog/2007/11/ext-tae-boston-examples-and-slides.html


  • Thanks Wolfgang - the penny finally dropped when I read your post - all makes perfect sense now..


  • To make things a little easier you can use the following code:


    if(!function_exists('json_encode'))
    {
    include_once('Services/JSON.php');
    $GLOBALS['JSON_OBJECT'] = new Services_JSON();
    function json_encode($value)
    {
    return $GLOBALS['JSON_OBJECT']->encode($value);
    }

    function json_decode($value)
    {
    return $GLOBALS['JSON_OBJECT']->decode($value);
    }
    }
    /*
    You can now use:
    $result = json_encode($your_variable);

    $result now contains the json-encoded version of $your_variable.
    */


    For those of you that have access to the apache config, the json module that php5 uses is downloadable here: http://www.aurore.net/projects/php-json/. I really recommend this since it is a lot faster than the php4 implementation.


  • EDIT: I see you were quicker than me :) Well, two answers to a question should help you along nicely :)



    I updated my example to be a bit clearer. The $nodes was just a copy-paste from my own source, you should use your own variable that you want encoded.

    When you use the JsonReader in the grid. The url you supply to the HttpProxy should supply an json-encoded array as a result.

    In the url you supply you have to build up an array with results and encode it with json_encode. You should then echo the result so it will be passed to the jsonReader.


  • EDIT: I see you were quicker than me :) Well, two answers to a question should help you along nicely :

    :D there was actually 2 questions and I answered to only one part of the Why one.

    Then When's answer is anytime PHP has to communicate with your web app!


  • Thanks Wolfgang , this is useful to me


  • Zend Framework also has support for serializing JSON data.

    http://framework.zend.com/manual/en/zend.json.html


  • I am glad that this thread still is helpful :)


  • i got this link

    http://extjs.com/learn/Tutorial:Using_Ext_grid_form_dialog_to_achieve_pag ing_list%2C_create%2C_edit%2C_delete_function

    and i am working with proxy,

    Animal said it is easy, but for me. amazing hard. ;)

    still learning, hope can contribute, but if anyone faster that will be awesome.

    F


  • ahh .. I was looking for PHP examples.. but thx


  • Couldn't get some of the examples (tree view) etc to work in PHP4 either, until I read this thread and understood that the json_encode function was missing! Thanks to Wolfgang for suggesting a solution, and to mnugter for further improvements.

    To make things even worse my ISP seems to disallow XHR calls to files with suffixes like .json, .html etc (only .php seems allowed), like in the Customizing TreePanel example from the Ext 2.0 alpha examples. The server will simply throw the following error "405 Method Not Allowed, The requested method POST is not allowed for the URL" if your not calling a php-file.

    So I wanted to come up with a generic solution that didn't involve hacking every php file in the Ext examples or renaming .json files with .php suffixes.. This is what I did:

    I created a new directory at my site root called XHRfixer. In this directory I put the JSON.php file downloaded from http://mike.teczno.com/JSON/JSON.phps and another file called fix.php with the following content:


    if(!function_exists('json_encode'))
    {
    include_once('JSON.php');
    $GLOBALS['JSON_OBJECT'] = new Services_JSON();
    function json_encode($value)
    {
    return $GLOBALS['JSON_OBJECT']->encode($value);
    }

    function json_decode($value)
    {
    return $GLOBALS['JSON_OBJECT']->decode($value);
    }
    }
    $dir=explode('/',$_SERVER['HTTP_REFERER'],4);
    $dir=dirname('../'.$dir[3]);
    chdir($dir);
    $file=$_GET['xhrfile'];
    chdir(dirname($file));
    $file=basename($file);
    if(substr_count($file,'.php')==1){
    include_once($file);
    }
    else {
    echo file_get_contents($file);
    }
    ?>

    I then added the following code at the end of the ext-all.js file:

    (function(){
    var org=Ext.Ajax.request;
    Ext.Ajax.request=function(o){
    o.url='/XHRfixer/fix.php?xhrfile='+o.url.split('?').join('&');
    return org.apply(this,[o])
    }
    })();This seems to make all the examples work as far as I can tell.


  • @Josh101
    Thank you. Glad the posting was helpful.

    @jason
    Hopefully this might additionally save someone some time - if you browse to /ext/examples/tree/get-nodes.php in your browser you might see various warnings and notices about undefined indexes and such. These can all be ignored, however the output goofs up the JSON output and so the treeview and other examples don't work.

    In addition to the JSON code mentioned above, you can tell PHP to not output all the notices by adding this line somewhere at the top of the script:

    error_reporting(E_ERROR);

    You are right. On the other hand i really recommand to write php code in a way that you do not get warnings and the like. In the long run, it really pays off.

    Regards

    Wolfgang


  • Hopefully this might additionally save someone some time - if you browse to /ext/examples/tree/get-nodes.php in your browser you might see various warnings and notices about undefined indexes and such. These can all be ignored, however the output goofs up the JSON output and so the treeview and other examples don't work.

    In addition to the JSON code mentioned above, you can tell PHP to not output all the notices by adding this line somewhere at the top of the script:

    error_reporting(E_ERROR);


  • Hi!
    I am trying to do this example using Json:
    http://extjs.com/tutorial/loading-data-submitting-form
    But it is yielding me this error: Fatal error: Cannot instantiate non-existent class: in services_json
    Does anyone know the cause of this?
    Thanks!


  • I am totally confused,

    Why and where should I use the given code?
    $result = json_encode($nodes);

    and what is $nodes?

    Please help!


  • Thank you Wolfgang. I am going to sticky this.







  • #If you have any other info about this subject , Please add it free.#
    Your name:
    E-mail:
    Telphone:

    Your comments:


    If you have any other info about Getting the JSON examples to work on PHP4.x , Please add it free.

    16 March 2010 | cameltoepants.com | edit