Ajax requests on jsFiddle

Did you know that you could create XHR requests on jsFiddle? If you didn’t know,  just keep reading..

To improve user experience jsFiddle has created the echo features. One of its features is to provide to developers the possibility to create XHR requests. It is very simple to use:


  <div class='wrapper'>
  <p>JSON will be received in 3 seconds</p>
  <div id='post'></div>
  </div>

This is my HTML, a simple div with id=post will be appended with the response from the request.

To make a request, I have used jQuery and it looks like this:


// My request

$.ajax({
  type: "POST",
  url: '/echo/json/',
  dataType: "json",
  data:{
    json: JSON.stringify({
      text: 'Response from server',
    }),
    delay: 3
  },
  }).done(function(response) {
    show_response(response);
});

// append data from response to my div
show_response = function(obj, result) {
    $('#post').append(obj.text);
};

My request is just a simple jQuery ajax() call. There are some things that we have to provide.

The data has to be a POST call.  The url points to   ‘/echo/json/’ because I’ve chosen json to represent my data, but there is other types available (including XML).  The ‘json’ object that you define on the request, will be the object that you’ll get on the response. The optional ‘delay’ parameter, it’s a time in seconds after which data should be returned.

And this is pretty much it! Simple and very useful if you, like me, use jsFiddle to share code samples, help anyone or just quick testings!

You can see the live example here.

Leave a comment