All samples are using Ink.requireModules, please read how to use it at Ink.requireModules section

Ink.Net.Ajax class

Creates a new XMLHttpRequest object

Methods
Method name Description
new Ajax(url, [options]) Constructor
.abort() Aborts the request if still running. No callbacks are called
.evalJSON(strJSON, sanitize) Evaluates a given string as JSON
.getAllHeaders() Gets all the HTTP headers from the response
.getHeader(name) Gets an HTTP header from the response
.getResponse() Gets the ajax response object
.isJSON(str) Checks if a given string is valid JSON
.load(url, callback) Loads content from a given url through an XMLHttpRequest.
.ping(url, callback) Loads content from a given url through an XMLHttpRequest.
.runStateChange() Executes the state changing phase of an ajax request
.setHeaders() Set the necessary headers for an ajax request.
.setRequestHeader(name, value) Sets a new request header for the next http request

new Ink.Net.Ajax(url, [options])

Accepts

  • url

    Request URL
  • options

    Request options, containing:
  • options.asynchronous

    trueIf false, the request synchronous.
  • options.contentType

    Content-type header to be sent. Defaults to 'application/x-www-form-urlencoded'
  • options.cors

    Flag to activate CORS. Set this to true if you're doing a cross-origin request
  • options.validateCors

    If this is set to `true`, perform a CORS request automatically based on the URL being cross-domain or not.
  • options.delay

    Artificial delay. If the request is completed faster than this delay, wait the remaining time before executing the callbacks
  • options.evalJS

    trueIf the request Content-type header is application/json, evaluates the response and populates responseJSON. Use 'force' if you want to force the response evaluation, no matter what Content-type it's using.
  • options.method

    'POST'HTTP request method. POST by default.
  • options.parameters

    Request parameters to be sent with the request
  • options.postBody

    POST request body. If not specified, it's filled with the contents from parameters
  • options.requestHeaders

    Key-value pairs for additional request headers
  • options.sanitizeJSON

    Flag to sanitize the content of responseText before evaluation
  • options.timeout

    Request timeout in seconds
  • options.xhrProxy

    URI for proxy service hosted on the same server as the web app, that can fetch documents from other domains. The service must pipe all input and output untouched (some input sanitization is allowed, like clearing cookies). e.g., requesting http://example.org/doc can become /proxy/http%3A%2F%2Fexample.org%2Fdoc The proxy service will be used for cross-domain requests, if set, else a network error is returned as exception.
  • options.onComplete

    Callback executed after the request is completed, regardless of what happened during the request.
  • options.onCreate

    Callback executed after object initialization but before the request is made
  • options.onException

    Callback executed if an exception occurs. Receives the exception as a parameter.
  • options.onFailure

    Callback executed if the request fails (requests with status codes different from 2xx)
  • options.onHeaders

    Callback executed when headers of the response arrive.
  • options.onInit

    Callback executed before any initialization
  • options.onSuccess

    Callback executed if the request is successful (requests with 2xx status codes)
  • options.onTimeout

    Callback executed if the request times out

Make an AJAX Request with some options

Code

Ink.requireModules(['Ink.Net.Ajax_1'], function(Ajax) {
    var uri = '/endpoint.php';
    new Ajax(uri, {
        method: 'GET',
        parameters: {foo: 'bar'},
        onInit: function(obj) {
            Ink.log('Init request');
        }, 
        onSuccess: function(xhrObj, req) {
            // ... 
            // var text = xhrObj.responseText;
            // var xml = xhrObj.responseXML;
            // var json = xhrObj.responseJSON; 
        }, 
        onComplete: function() {
            Ink.log('Request completed');
        },
        onFailure: function() {
            Ink.log('Request failed');
        },
        on404: function() {
            Ink.log('404 request');
        }, 
        onTimeout: function() {
            Ink.log('Request timeout');
        },
        timeout: 5
    });
});

Submit a form using AJAX POST, serialized with Ink.Dom.FormSerialize

Code

 
<form id="form" method="post" action="#">
  <p>
    <label for="name">Name:</label>
    <input type="text" id="name" name="name">
  </p>
  <p>
    <label for="email">Email:</label>
    <input type="text" id="email" name="email">
  </p>
  <p>Choices:</p> 
  <p>
    <input type="checkbox" name="choice[]" id="choice_a" value="A"> <label for="choice_a">A</label>
  </p>
  <p>
    <input type="checkbox" name="choice[]" id="choice_b" value="B"> <label for="choice_b">B</label>
  </p>
  <p><button type="submit">Submit</button></p>
</form>
<script>
Ink.requireModules(['Ink.Net.Ajax_1', 'Ink.Dom.Event_1', 'Ink.Dom.FormSerialize_1'], function(Ajax, InkEvent, FormSerialize) {

    var form = Ink.i('form');
  
    function doPost(event) {
        InkEvent.stopDefault(event);

        var formData = FormSerialize.serialize(form);
    
        var uri = '/endpoint.php';
        new Ajax(uri, {
            method: 'POST',
            postBody: formData,
            onSuccess: function(obj) {
                if(obj && obj.responseJSON) {
                    var req = obj.responseJSON;
                }
            }, 
            onFailure: function() {
                Ink.warn('Ajax request failed');
            }
        });    
    }
  
    InkEvent.observe(form, 'submit', doPost);
});
</script>

Make an AJAX request to SAPO Photos using CORS and print the images

Code

<div id="container"></div>
<script>
Ink.requireModules(['Ink.Net.Ajax_1'], function(Ajax) {

    var uri = 'http://services.sapo.pt/Photos/JSON2';
    new Ajax(uri, {
        method: 'GET',
        cors: true,
        parameters: {u: 'codebits', limit:'3'},
        onSuccess: function(obj) {
            if(obj && obj.responseJSON) {
                var req = obj.responseJSON;
                var aItems = req.rss.channel.item;
                var container = Ink.i('container');
                var curImg;
                for(var i=0, total=aItems.length; i < total; i++) {
                    curImg = new Image();
                    curImg.src = aItems[i]['media:thumbnail'][0].url;
                    container.appendChild(curImg);
                }
            }
        }, 
        onFailure: function() {
            Ink.warn('Ajax request failed');
        }
    });
});
</script>

.abort() method

Aborts the request if still running. No callbacks are called

.evalJSON(strJSON, sanitize) method

Evaluates a given string as JSON

Accepts

  • strJSON

    String to be evaluated
  • sanitize

    Flag to sanitize the content

.getAllHeaders() method

Gets all the HTTP headers from the response

.getHeader(name) method

Gets an HTTP header from the response

Accepts

  • name

    Header name

.getResponse() method

Gets the ajax response object

.isJSON(str) method

Checks if a given string is valid JSON

Accepts

  • str

    String to be evaluated

.load(url, callback) method

Loads content from a given url through an XMLHttpRequest.

Shortcut function for simple AJAX use cases. Works with JSON, XML and plain text.

Accepts

  • url

    Request URL
  • callback

    Callback to be executed if the request is successful

Code

Ink.requireModules(['Ink.Net.Ajax_1'], function(Ajax) {

    var doSomething = function(type, data) {
        Ink.log(type, data);
    };

     Ajax.load('/some/text/file', function (responseText) {
        doSomething('Text', responseText);
     });
     Ajax.load('/some/xml/file', function (responseXML) {
        doSomething('XML', responseXML);
     });
     Ajax.load('/some/json/file', function (responseJSON) {
        doSomething('JSON', responseJSON);
     });
});

.ping(url, callback) method

Loads content from a given url through an XMLHttpRequest.
Shortcut function for simple AJAX use cases.

Accepts

  • url

    Request url
  • callback

    Callback to be executed if the request is successful

.runStateChange() method

Executes the state changing phase of an ajax request

.setHeaders() method

Set the necessary headers for an ajax request.

.setRequestHeader(name, value) method

Sets a new request header for the next http request

Accepts

  • name

    Header name.
  • value

    New header value.