fiddle ajax json

by Akram kamal

HTML

<script src="http://jquery-json.googlecode.com/files/jquery.json-2.2.min.js"></script>
<button id='buttonJSON'>Echo JSON</button>
<button id='buttonHTML'>Echo HTML</button>
<button id='buttonJSONP'>Echo JSONP</button>
<div id='result'></div>

JavaScript

$('#buttonJSON').click(function() {
    /**
    * create a data object to send to the server, it must have two properties
    * json: the encoded (i use jQuery - Json library to do that) JSON that you will receive back
    * delay: how long the server waits before responding in seconds
    */
    var data = {
        json: $.toJSON({
            text: 'Echo JSON'
        }),
        delay: 1
    }
    $.ajax({
        //post the request to /echo/json/ and specify the correct datatype
        url: '/echo/json/',
        dataType: 'json',
        data: data,
        success: function(data) {
            //you get back exactly what you sent in the json 
            alert(data.text);
            $('#result').html(data.text);
        },
        type: 'POST'
    });
});


$('#buttonHTML').click(function() {
    //No need to encode this time, just set the html property of the object
    //to what you want back
    var data = {
        html: "<p>Text echoed back to request</p>",
        delay: 1
    }
    $.ajax({
        //post the request to /echo/html/ and specify the correct datatype
        url: '/echo/html/',
        dataType: 'html',
        data: data,
        success: function(data) {
            //As in the other example you get 
            alert(data);
            $('#result').html(data);
        },
        type: 'POST'
    });
});

$('#buttonJSONP').click(function() {
    //this time you can use a standard javascript object
    //you get back everything you sent minus the delay property
    var data = {
        text: 'ECHO JSONP',
        par1: 'another param',
        delay:1
    }
    $.ajax({
        //this time you have to make a GET request to http://jsfiddle.net/echo/jsonp/
        url: 'http://jsfiddle.net/echo/jsonp/',
        dataType: 'jsonp',
        data: data,
        success: function(data) {
            //you get back the same object you sent minus the delay property
            alert(data.text);
            $('#result').html(data.par1);
     ...