Ajax Server Interaction

Example

The button below will call a Django server via an Ajax POST request. The server will return a message, which will be displayed in the panel.


Enter data to post in the tag element of the request
Awaiting Response...

Django Interaction via Hidden Form

Sadj Hidden Form

The easiest way to POST to a Django server is via a standard Django form, with a {% csrf_token %} template tag. A CSRF token can be appended directly to an XMLHttpRequest object in Javascript, but it can be fiddly; working with Django's usual flow is far more robust.

You should include the hiddencontrols.html template in your application frame to use this functionality. You should also include the pagecontrols.html template to automatically pass around details such as the page name (especially helpful in tracking asynchronous requests across page changes in a single-page application).

The Sadj default frames therefore include a simple hidden form, which is used to send a string representation of generic Json data to the Sadj server. This is wrapped with two POST helper methods in sadjcore.js, plus corresponding GET methods:

  • ajaxPOST(targetAction, JSONValue, page , onLoadFtn) - POST a generic request
    • targetAction - the url to access
    • payload - the JSON data to send in the request
    • page - the current page; if blank, this will be picked up from the hidden templateKeys element.
    • success - the function to call to handle the response
  • promisePOST(targetAction, JSONvalue, success, page, checkStatus=true) - obtain a promise to POST a generic request
    • targetAction - the url to access
    • payload - the JSON data to send in the request
    • success - optional processing function to apply to the response
    • page - the current page; if blank, this will be picked up from the hidden templateKeys element.
    • checkStatus - flag to indicate that the response should be checked for a Sadj status, and reject the response if this is not 'success' (optional, default true)
  • ajaxGET(targetAction, success) - helper function to access the 'targetAction' url and apply the 'success' function to the response; does not utilise the Django form.
  • promiseGET(targetAction, asJSON=true) - helper function to return a promise to access 'targetAction' url, and optionally convert the response to Json; does not utilise the Django form.

The code on the Files and Folders page uses the promiseGET method to pull in the json file containing the folder definition.