Friday, July 22, 2011

Three jquery ajax problems encountered and solved

Recently, we decided to retrieve data from our website using jquery's ajax remote data access method, but encountered three problems that we did not know how to solve immediately.

The first problem was obtaining the information in javascript itself. Because we did not know what to do, we used the examples provided in jquery. Writing the remote function was easy. All we had to do was provide a url, specify 'GET', and provide a callback function. To test the working of this script, we wrote a simple script on our remote server to echo back the data. Once we received the data, we would process it later.
  • PROBLEM: It appeared that the data was never being returned but it really was. The problem was that we expected the processing to occur in sequential order, but by default, ajax processes in asyncronous mode. Thus, the data returned much later. 
  • TRICK: To solve this, we added the "async: false," option to the ajax call and it worked!
The second problem was once the data was received, it was a JSON formatted text string. In order to use it, we had to convert it to a javascript object. To do this, we used the "eval" function.
  • PROBLEM: On our first tries, this kept failing.
  • TRICK: Then we discovered that we needed to bracket our returned data with surrounding parenthesis characters and the eval returned an object.
Lastly, the third problem occurred when we began using real data. We wrote and debugged our application using Firefox and all seemed to work.
  • PROBLEM: But, a user informed us that our pages did not work in the IE and Safari browsers.
  • TRICK: The problem was that the json variable "return" in our data structure was being interpreted literally by IE and Safari, and the object conversion failed. When we changed the variable to "returnval", our problem was solved.
A sample of the code data that we were using are shown in the table below. Note that the items we added to correct our problems a highlighted in green. Erroneous values are shown in red.

JavaScript Sample

var remotedata = null;

function getData( ) {

   var dataurl = 'http://www.myurl/getsampledata ;

    var retval = $.ajax({
    type: 'GET',
    url: dataurl ,
     async: false,
    success: function( JSONObject ) {
                       remotedata = eval( '(' + JSONObject + ')' );
                 }
    });
}

Data Sample

Bad
{ data: [ { key:'matchstring', datapoint1:25, return:45.2, age:42 } ] } 

Correct
{ data: [ { key:'matchstring', datapoint1:25, returnval:45.2, age:42 } ] } 



While this information is detail specific, we are publishing our experiences to help you utilize jquery's ajax in your future applications.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...

Earn Money - Join the Leading Affiliate Program