Request.JSON

sending a JSON request to the jsFiddle backend. Later on parse and display the data.

by Dimitar Christoff

HTML

<div class='wrapper'>
  <p>received by POST</p>
  <ul id='post'></ul>
</div>

<a href="#" rel="get" id="check">fire get</a> 
<a href="#" rel="get" id="check2">fire get2</a>

CSS

.wrapper { 
  padding: 10px; 
  margin: 5px; 
  border: 2px dashed #999;
}

JavaScript

var foo = new Class({
    Implements: [Options,Events],
    options: {
        request: {
            method: "post",
            data: {
                'post_data': 'post test'
            }
        }
    },
    initialize: function(options) {
        this.setOptions(options);
        this.reqHandler = new Request.JSON(this.options.request);
        this.allowRequest = true;
    },
    request: function(options) {
        var options = $merge({
            onComplete: function(data) {
                this.fireEvent("requestDone", data);
                this.allowRequest = true;
            }.bind(this)
        }, options);

        if (this.allowRequest) {
            this.reqHandler.setOptions(options).send();
            this.allowRequest = false;
        }
        else {
            alert("busy, please wait for old requests to finish");
        }
    }

});

var bar = new foo({
    onRequestDone: function(data) {
        console.log("completed", data);
    }
});

document.id("check").addEvent("click", function(e) {
    e.stop();
    bar.request({
        url: '/ajax_json_echo/',
        onSuccess: function(response) {
            document.id("post").set("html", response.post_response.post_data);
        }
    }); 
});

document.id("check2").addEvent("click", function(e) {
    e.stop();
    bar.request({
        url: '/ajax_json_echo/',
        onSuccess: function(response) {
            alert("yay");
        }
    });
});