Modifying Requests

This demo shows how to modify intercooler requests on the client side using Javascript

Explanation

  • You can add a listener for the beforeAjaxSend.ic event on the document object. This will be passed in the ajax setup hash which you can modify to add headers, parameters, etc. By setting the cancel property to true, you will cancel the ajax request.

Demo

Send Request...

Response:



          <a class="btn btn-default" ic-post-to="/req" ic-target="#response" data-custom-data="myCustomData">Send Request...</a>

          <div>
            <label>
              <input type="checkbox" id="stop-request"> Stop Requests
            </label>
          </div>

          <h2>Response:</h2>
          <div id="response">
          </div>

  <script>

    $(function(){
      $(document).on('beforeAjaxSend.ic', function(event, ajaxSetup, elt){

        // Add a parameter
        ajaxSetup.data = ajaxSetup.data + "&timestamp_from_javascript=" + new Date().getTime().toString();

        // Add a custom HTTP header
        ajaxSetup.headers['X-My-Custom-Header'] = "A header value";

        // Cancel the requests if the "Stop Request" checkbox is checked
        ajaxSetup.cancel = $('#stop-request').is(":checked");

        // Add some custom data from the triggered element
        ajaxSetup.data = ajaxSetup.data + "&from_elt=" + elt.data('custom-data');

      });
    });

    //========================================================================
    // Mock Server-Side HTTP End Point
    //========================================================================
    $.mockjax({
      url: "/req",
      response: function (settings) {
        var params = parseParams(settings.data);
        var str = "<h4>Parameters</h4><ul>";
        for (var property in params) {
          str += "<li><strong>" + property + "</strong>: " + params[property] + "</li>"
        }
        this.responseText =  str + "</ul>"
      }
    });


  </script>