Board index   FAQ   Search  
Register  Login
Board index PHP Your Scripts

javascript ajax with JSON

This is where you share YOUR scripts with others

Moderators: macek, egami, gesf

javascript ajax with JSON

Postby AeroX » 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 );
}
User avatar
AeroX
New php-forum User
New php-forum User
 
Posts: 142
Joined: Sun May 11, 2008 1:40 am
Location: London, UK

Re: javascript ajax with JSON

Postby AeroX » Thu Jun 26, 2008 8:31 am

I'll post up the php half of this script when i'm not busy.
User avatar
AeroX
New php-forum User
New php-forum User
 
Posts: 142
Joined: Sun May 11, 2008 1:40 am
Location: London, UK


Return to Your Scripts

Who is online

Users browsing this forum: No registered users and 1 guest

Sponsored by Sitebuilder Web hosting and Traduzioni Italiano Rumeno and antispam for cPanel.

cron