After a few days struggling with a web application project, I finally got a way out of my problem. My problem was to retrieve data from server using javascript (AJAX). As a beginner in this, with some limitation in tools that I used (only IE and vim), I was stuck in implementing dojo.xhrPost. Apparently there were other Dojo users who had experience pretty much the same problem as mine, however the suggested solution that I could find in the internet wasn’t able to solve it.

These are my original syntax (ignore the line numbering):

 20          dojo.xhrPost({
21                 url:”json.php”,
22                 handleAs:”json”,
23                 postData: “id=100″,
24                 load:function(response){
25                               alert(response);
26                 }
27           })

On line 25, I just wanted to see the data (response) from the server which I expected it would be some json formatted data. Surprisingly, it returns with an array of empty object.

I tried to do minimal debugging on this case, by changing line 22 to ‘handleAs:text’. And the result of running that script (inside html) was an alert which contains a JSON formatted string. So, the retrieving process was actually work, the failure was in the parsing process (remember, this is me without Firebug).

I finally found the solution, by changing that script as follows :

20            dojo.xhrPost({
21                 url:”json.php”,
22                 handleAs:”json”,
23                 postData: “id=100″,
24                 load:function(response){
25                     require(["dojo/_base/array"],function(array){
26                         array.forEach(response,function(value,index){
27                             console.log(value.name);
28                         })
29                     })
30                 }
31
32             });

Value is the object obtained from the JSON formatted text and Value.name returned the’name’ property in it. So, yeah…it’s the parsing.

Advertisement