tags:

views:

31

answers:

1

I have constructed a class in js/jQuery:

function JSONRequest(request_id, type){
    this.request_id = request_id;
    JSONsvc ='json_dispatch.php';
    this.type = type;
}

JSONRequest.prototype.query = function() {
    $.getJSON(JSONsvc,
            {request_id:this.request_id, type:this.type},
            function(data) {
                return data;
            }           
    );  
}
JSONRequest.prototype.buildKeyValues = function(data) {
    $.each(data.items, function(i,item){
        //$('textarea').text(item.comment); //hack
        $.each(item, function(j,key){
            $("#"+j).val(key);
        })
    })
}

JSONRequest.prototype.buildTableRows = function(data) {
    var tbodyContainer;
    tblRows = "";
    $.each(data.items, function(i,row){ 
        tblRows += "<tr>";      
        $.each(row, function(j,item){   
            tblRows +="<td>"+item+"</td>";
        })
        tblRows += "</tr>";
    })
    return tblRows;
}

I use it like this:

var e = new JSONRequest(this.id,this.type);
e.query();
alert(e.data); //returns Undefined

How do I get the returned JSON object for use in my other class methods?

A: 

You can't really return data from a callback like that. Another, more serious problem that you have, is that getJSON is asynchronous. So what you should do is pass a callback in your query function so that you can have access to the data like that:

JSONRequest.prototype.query = function(callback) {
    $.getJSON(JSONsvc,
            {request_id:this.request_id, type:this.type},
            function(data) {
                if(callback) {
                   callback(data);
                }                    
            }           
    );  
};

Then:

var e = new JSONRequest(this.id,this.type);
e.query(function(data) {
   alert(data);
});

which should work.

Vivin Paliath
That definitely seems to have the desired effect so far.
Jim Wharton