2

Is there any jQuery.getJSON() equivalent in MooTools? I have a json file named data.json and I want to get its content by calling data.json file using MooTool. Is it possible? I tried Request.JSON() method but it didn't work for me. The below is my code,

var json_req = new Request.JSON({
    url:'../public_html/data/data.json',
    method: 'get',
    secure: true,
    data:{
        json: true
    },
    onSuccess: function (res){
        this.result = res;          
    },
    onFailure: function(){
        this.result = "failed";
    }
}).send(); 

Also from the http://demos111.mootools.net/ I found an Ajax class named Ajax() which they are widely using through out their tutorial. But in MooTools documentation I didn't find this Ajax() class. I tried to use the Ajax() by replacing my Request.JSON(), but got an "Ajax not defined" error. What is this Ajax class and how can we use it in MooTools?

Sergio
  • 28,539
  • 11
  • 85
  • 132
Johncy Binoy
  • 169
  • 3
  • 13

3 Answers3

2

Here is a simple example of the functionality you are looking after. Basically wrapping a function around the Class... you could use the Class directly also.

function getJSON(url, callback) {
    new Request.JSON({
        url: url,
        onSuccess: callback
    }).send();
}

// and invoque it:
getJSON('/echo/json/', function(json) {
    console.log(json);
});

you can check it live here: https://jsfiddle.net/w64vo2vm/

Sergio
  • 28,539
  • 11
  • 85
  • 132
1

This one works for me

window.addEvent('domready', function() {
    new Request.JSON({
        url: url,
        data: {'delay': 1},
        method: 'post',
        onSuccess: function(response) {
        var myJSON = JSON.encode(response)
          console.log(myJSON); 
        }
    }).send();
})

You may see the result here

http://jsfiddle.net/chetabahana/qbx9b5pm/

eQ19
  • 9,880
  • 3
  • 65
  • 77
0

I have a small function for this task. Here's the code

var configJson;

function klak_readJson(fileurl) {
  var myRequest = new Request({
    url: fileurl,
    method: 'get',
    onRequest: function(){
      console.log('loading '+fileurl+'...');
    },
    onSuccess: function(responseText) {
      console.log('received bytes '+responseText.length);
      configJson=JSON.parse(myRequest.response.text);
    }
  });
  myRequest.send();
}

Call the function to store the JSON object into configJson

klak_readJson('/js/test.json');

Hope it helps.

Daniel Faure
  • 391
  • 6
  • 14
  • Why to do sync ajax? I would say that is a _no no_, synchronous requests are being deprecated around the web. Only in rare cases, the use of a synchronous method is preferable to an asynchronous one. – Sergio Mar 03 '16 at 21:23