JQuery get $.getJSON data

Imagine you have server side data return to your Javascript client side using Ajax and JSON as datatype return.

var groupid = null; //try outer scope
$.getJSON(url, data, function(result){

    groupid = result.groupid;  //json type data
    //do whatehever you like here
    //you wanted to return the data that you have been parsed or assign

});
alert(groupid); //error : will return null because the JSON already happern after the callback executed.

So instead doing that, we need to use delegate or callback function that JQuery have provided to us.
Remember the $.fn. thing.

Now, let see how we can use the delegate function to return us the data:

$.getJSON(path +'?request=url', function( data ) {

var selectOption = '';
//do what ever you like with the json data

selectOption =  selectOption + 'testing' + data; //example only
$.fn.delegateJSONResult( selectOption ); 

} ); 

$.fn.delegateJSONResult = function{  alert( data );  }

With JQuery delegates, it makes your life easier as developer and the most common used to all my event handling.

To understand better about delegates, look at JQuery code to see how it actually works behind the background or alternatively try to play around with this sanbox.

The above source code highlighting was proudly developed by WordPress. Many thanks.

Advertisements

About Charles Ling
Web/Android/IPhone Developer. Very very interested in Web Architecture, Web Standard and and how to use Web to improve human social life and doing cool stuff.

One Response to JQuery get $.getJSON data

  1. RRaveen says:

    Dear Friends,

    I hope you are doing well. I have launched a web site http://www.codegain.com and it is basically aimed C#,JAVA,VB.NET,ASP.NET,AJAX,Sql Server,Oracle,WPF,WCF and etc resources, programming help, articles, code snippet, video demonstrations and problems solving support. I would like to invite you as an author and a supporter. Looking forward to hearing from you and hope you will join with us soon.

    Please forward this email to all of your friends who are related IT. Send to us your feed about site also.

    Thank you
    RRaveen
    Founder CodeGain.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: