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):

  1. // If we need it in place where we don't have access to app instance or before we init the app
  2. Framework7.request.get('somepage.html', function (data) {
  3. console.log(data);
  4. });
  5. // After we init the app we can access it as app instance property
  6. var app = new Framework7({ /*...*/ });
  7. app.request.get('somepage.html', function (data) {
  8. console.log(data);
  9. });

API

app.request(parameters)- Load data from the server

  • parameters - object - Request parameters

Returns plain XHR object

Framework7.request(parameters)- Load data from the server

  • parameters - object - Request parameters

Returns plain XHR 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
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)A function to be called if the request fails
successfunction (data, status, xhr)A function to be called if the request succeeds
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:
  1. app.request({
  2. url: somepage.html’,
  3. statusCode: {
  4. 404: function (xhr) {
  5. alert(‘page not found’);
  6. }
  7. }
  8. })

Shorthand Methods

Request comes with some pre configured methods for ease of use.

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) - 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

Returns plain XHR object

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

Returns plain XHR object

For example:

  1. var app = new Framework7();
  2. var $$ = Dom7;
  3. app.request.get('blog-post.php', { foo:'bar', id:5 }, function (data) {
  4. $$('.articles').html(data);
  5. console.log('Load was performed');
  6. });

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) - 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

Returns plain XHR object

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

Returns plain XHR object

For example:

  1. var app = new Framework7();
  2. var $$ = Dom7;
  3. app.request.post('auth.php', { username:'foo', password: 'bar' }, function (data) {
  4. $$('.login').html(data);
  5. console.log('Load was performed');
  6. });

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) - A callback function that is executed if the request fails. Optional

Method nothing returns

Framework7.request.json(url, data, success, error)

Method returns nothing

For example:

  1. Framework7.request.json('items.json', function (data) {
  2. console.log(data);
  3. });
  4. var app = new Framework7();
  5. app.request.json('users.json', function (data) {
  6. console.log(data);
  7. });

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) - 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

Returns plain XHR object

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

Returns plain XHR object

For example:

  1. var app = new Framework7();
  2. var $$ = Dom7;
  3. app.request.postJSON('http://api.myapp.com', { username:'foo', password: 'bar' }, function (data) {
  4. console.log(data);
  5. });

Request Setup

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

  • parameters - object - Default requests parameters

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

For example:

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

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