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!
- 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.
- 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.
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