Skip to content

ajaxRequest

Mike Byrne edited this page Jan 25, 2022 · 5 revisions

description

Performs ajax requests

requires

  • queryStringHandler (handled automatically)

parameters

settings object - required:

  • url - required - url to send request to
  • type - required - HTTP method to use ('POST', 'GET', 'PUT', 'DELETE')
  • data - optional - data object sent as data in the request
  • requestHeaders - optional - an array of request header objects with header/value pairs eg: [{ header: 'X-Requested-With', value: 'XMLHttpRequest' }]
  • onSuccess - optional - function to run on request success, returns the responseText, in whatever format that is and the status code
  • onError - optional - function to run on request error, returns the responseText, if there is any, in whatever format that is and the status code

returns

  • nothing

example usage:

import { ajaxRequest } from '@area17/a17-helpers';

ajaxRequest({
  url: '/form-post.php',
  type: 'POST',
  data: {
    param1: 'param1value',
    param2: 'param2value'
  },
  requestHeaders: [
    {
      header: 'Content-Type',
      value: 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    {
      header: 'X-Requested-With',
      value: 'XMLHttpRequest'
    }
  ],
  onSuccess: function(data){
    el.innerHTML = data;
  },
  onError: function(data){
    alert(data);
  }
});

You can abort the ajax request by assigning your request to a variable:

import { ajaxRequest } from '@area17/a17-helpers';

let myReq = ajaxRequest({
  url: '/data.php',
  type: 'GET',
  onSuccess: function(data){
    el.innerHTML = data;
  },
  onError: function(data){
    alert(data);
  }
});

if (OH_NOES_WE_NEED_TO_CANCEL_RIGHT_NOW_OR_ELSE) {
  myReq.abort();
}