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