Request / Ajax

Framework7 comes with handy Request library to work with XHR requests (Ajax) right from the box.

It is available as a request property of Framework7 class (Framework7.request) and same property on initialized app instance (app.request):

// If we need it in place where we don't have access to app instance or before we init the app
Framework7.request.get('somepage.html').then((res) => {
  console.log(res.data);
});


// After we init the app we can access it as app instance property
var app = new Framework7({ /*...*/ });

app.request.get('somepage.html').then((res) => {
  console.log(res.data);
});

It is also possible to import it when using ES modules:

import { request } from 'framework7';

request.get('somepage.html')

API

app.request(options)

  • options - object - Request parameters

Returns promise that will be resolved with the { data, xhr, status, options } object and rejected in case of error with { xhr, status, message, options } object.

Framework7.request(options)

  • options - object - Request parameters

Returns promise that will be resolved with the { data, xhr, status, options } object and rejected in case of error with { xhr, status, message, options } object.

Let's look at the list of available parameters

ParameterTypeDefaultDescription
urlstringRequest url
asyncbooleantrueIf you need synchronous requests, set this option to false
methodstringGETRequest method (e.g. "POST", "GET", "PUT")
cachebooleantrueIf set to false, it will force requested pages not to be cached by the browser. Setting cache to false will only work correctly with HEAD and GET requests. It works by appending _nocache={timestamp} to the GET parameters
contentTypestringapplication/x-www-form-urlencodedContent type. Also could be multipart/form-data or text/plain. For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server
crossDomainbooleanIf you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. When true additional X-Requested-With: XMLHttpRequest header will not be added to request. By default it will try to guess depending on app and request hosts
dataobject
string
array
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. For POST requests could be FormData instance
processDatabooleantrueBy default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false
dataTypestringtextThe type of data that you're expecting back from the server. Could be text or json
headersobjectAn object of additional header key/value pairs to send along with requests using the XMLHttpRequest transport. For example:
xhrFieldsobjectAn object of key/value pairs to set on the native XHR object
usernamestringA username to be used with XMLHttpRequest in response to an HTTP access authentication request
passwordstringA password to be used with XMLHttpRequest in response to an HTTP access authentication request
timeoutnumber0Set a timeout (in milliseconds) for the request
abortControllerAbortControllerAllows to pass abort controller to have an option to abort the request
Callbacks
beforeCreatefunction (parameters)A pre-request callback function that can be used to modify passed parameters
beforeOpenfunction (xhr, parameters)A pre-request callback function that will be called before XHR opened. Can be used to modify XHR object

If you return false in this callback it will cancel the request

beforeSendfunction (xhr)A pre-request callback function that will be called after XHR opened and before XHR send. Can be used to modify the XHR object before it is sent. Use this callback to set custom headers, etc.

If you return false in this callback it will cancel the request

errorfunction (xhr, status, message)A function to be called if the request fails

This callback is not available with promise API

successfunction (data, status, xhr)A function to be called if the request succeeds

This callback is not available with promise API

completefunction (xhr, status)A function to be called when the request finishes (after success and error callbacks are executed)
statusCodeobjectAn object of numeric HTTP codes and functions to be called when the response has the corresponding code. For example, the following will alert when the response status is a 404:
app.request({
  url: 'somepage.html',
  statusCode: {
    404: function (xhr) {
      alert('page not found');
    }
  }
})

Shorthand Methods

Request comes with some pre configured methods for ease of use. All methods return same Promise as main request method.

get()

app.request.get(url, data, success, error, dataType)- Load data from the server using a HTTP GET request

  • url - string - Request url
  • data - object - A plain object or string that is sent to the server with the request. Optional
  • success - function (data, status, xhr) - A callback function that is executed if the request succeeds. Optional
  • error - function (xhr, status, message) - A callback function that is executed if the request fails. Optional
  • dataType - string - The type of data that you're expecting back from the server. Could be text or json. Optional

Framework7.request.get(url, data, success, error, dataType)- Load data from the server using a HTTP GET request

For example:

var app = new Framework7();

var $$ = Dom7;

app.request.get('blog-post.php', { foo: 'bar', id:5 })
  .then(function (res) {
    $$('.articles').html(res.data);
    console.log('Load was performed');
  })
  .catch(function (err) {
    console.log(err.xhr)
    console.log(err.status)
    console.log(err.message)
  })

post()

app.request.post(url, data, success, error, dataType)- Load data from the server using a HTTP POST request

  • url - string - Request url
  • data - object - A plain object or FormData or string that is sent to the server with the request. Optional
  • success - function (data, status, xhr) - A callback function that is executed if the request succeeds. Optional
  • error - function (xhr, status, message) - A callback function that is executed if the request fails. Optional
  • dataType - string - The type of data that you're expecting back from the server. Could be text or json. Optional

Framework7.request.post(url, data, success, error, dataType)- Load data from the server using a HTTP POST request

For example:

var app = new Framework7();

var $$ = Dom7;

app.request.post('auth.php', { username:'foo', password: 'bar' })
  .then(function (res) {
    $$('.login').html(res.data);
    console.log('Load was performed');
  });

json()

app.request.json(url, data, success, error)- Load JSON-encoded data from the server using a GET HTTP request

  • url - string - Request url
  • data - object - A plain object or FormData or string that is sent to the server with the request. Optional
  • success - function (data, status, xhr) - A callback function that is executed if the request succeeds. Optional
  • error - function (xhr, status, message) - A callback function that is executed if the request fails. Optional

Framework7.request.json(url, data, success, error)- Load JSON-encoded data from the server using a GET HTTP request

For example:

var app = new Framework7();

app.request.json('users.json')
  .then(function (res) {
    console.log(res.data);
  });

postJSON()

app.request.postJSON(url, data, success, error, dataType)- Send JSON data using a HTTP POST request

  • url - string - Request url
  • data - object - A plain object
  • success - function (data, status, xhr) - A callback function that is executed if the request succeeds. Optional
  • error - function (xhr, status, message) - A callback function that is executed if the request fails. Optional
  • dataType - string - The type of data that you're expecting back from the server. Could be text or json. By default is json. Optional

Framework7.request.postJSON(url, data, success, error, dataType)- Send JSON data using a HTTP POST request

For example:

var app = new Framework7();

var $$ = Dom7;

app.request.postJSON('http://api.myapp.com', { username:'foo', password: 'bar' })
  .then(function (res) {
    console.log(res.data);
  });

Request Setup

app.request.setup(options)- Set default values for future Ajax requests. Its use is not recommended

  • options - object - Default requests parameters

Framework7.request.setup(options)- Set default values for future Ajax requests. Its use is not recommended

For example:

// After the following setup all XHR requests will have additional 'Autorization' header
Framework7.request.setup({
  headers: {
    'Authorization': 'sometokenvalue'
  }
})

Original Request Parameters

Each of request methods returns plain XHR object, which is also available in callbacks. This default XHR object is extended with the following properties:

xhr.requestParametersObject with passed XHR request parameters
xhr.requestUrlString with request URL

Abort Controller

Because .request() returns Promise, we don't have access to XHR object before Promise will be resolved or rejected.

For this case we need to create special Abort Controller, pass it to the request and we will be able to abort it in future:

var app = new Framework7(...);

// create Abort Controller
var abortController = app.request.abortController();

// send request
app.request({
  url: 'somepage.php',
  // pass abort controller to the request
  abortController: abortController,
  // ...
});

// now we can abort the request
abortController.abort();