javascript ajax with JSON

This is where you share YOUR scripts with others

Moderators: egami, macek, gesf

Post Reply
User avatar
AeroX
New php-forum User
New php-forum User
Posts: 140
Joined: Sun May 11, 2008 1:40 am
Location: London, UK
Contact:

Wed Jun 25, 2008 2:13 pm

I've made a small ajax with JSON script which is 321 bytes. But i'm not sure if i left anything out (i don't normaly use javascript) browser compatibility wise.

It's used by doing:

Code: Select all

<script>
function myFunction( data )
{
    alert( data.myMessage );
}
</script>
<a href="javascript:void(0);" onClick="JSONGet( 'http://mysite.com/json.php', 'myFunction' )">Load JSON</a>
321 byte version (it could be less than 200 bytes if I used shorter var names):

Code: Select all

var JSONreq,JSONdata,JSONcall;function JSONHandler(){if(JSONreq.readyState==4){JSONdata=eval("("+JSONreq.responseText+")");eval(JSONcall+"(JSONdata)");}}function JSONGet(addr,callback){JSONcall=callback;JSONreq=new XMLHttpRequest();JSONreq.open("GET",addr,true);JSONreq.onreadystatechange=JSONHandler;JSONreq.send(null);}
Readable Version:

Code: Select all

var JSONreq, JSONdata, JSONcall;

function JSONHandler()
{
    if( JSONreq.readyState ==  4 )
    {
        JSONdata = eval( "(" + JSONreq.responseText + ")" );
        eval( JSONcall + "(JSONdata)" );
    }
}

function JSONGet( addr, callback )
{
    JSONcall = callback;
    JSONreq = new XMLHttpRequest();
    JSONreq.open( "GET", addr, true );
    JSONreq.onreadystatechange = JSONHandler;
    JSONreq.send( null );
}
AeroX.

When posting code to be reviewed please enclose it in the [ code ] [ /code ] tags as it makes it a lot easier for people to read as it correctly formats itself on screen.

Image
    Click Here to Visit[/url]

    User avatar
    AeroX
    New php-forum User
    New php-forum User
    Posts: 140
    Joined: Sun May 11, 2008 1:40 am
    Location: London, UK
    Contact:

    Thu Jun 26, 2008 8:31 am

    I'll post up the php half of this script when i'm not busy.
    AeroX.

    When posting code to be reviewed please enclose it in the [ code ] [ /code ] tags as it makes it a lot easier for people to read as it correctly formats itself on screen.

    Image
      Click Here to Visit[/url]

      Post Reply