Don’t hesitate to contact us if you have any feedback.

Javascript – Simplified AJAX Request functions

This JavaScript module introduces a concise and flexible way to handle HTTP requests with a primary request function and specialized get and post helper functions. The system is designed to support both GET and POST methods with easy parameter management and response formatting.

Function Definition

The request function serves as the core utility, enabling:

  • Dynamic URL Parameter Handling: For GET requests, query parameters are serialized and appended to the URL.
  • Form Data Preparation: For POST requests, if the params are an object, they are converted to FormData.
  • Flexible Response Formatting: The function returns a promise that resolves to either JSON or plain text, based on the format argument.
const request = (url, params = {}, method = 'GET', format = 'json') => {
  const options = {
    method,
  }

  if (method === 'GET') {
    url += `?${new URLSearchParams(params)}`
  } else {
    // Check if the parameters is suited for post request
    let formData = params
    if (typeof params === 'object' && !(params instanceof FormData)) {
      formData = new FormData()
      for (const key in params) {
        formData.append(key, params[key])
      }
    }

    options.body = formData
  }

  return fetch(url, options).then((response) =>
    format === 'json' ? response.json() : response.text()
  )
}

export const get = (url, params, format) => request(url, params, 'GET', format)
export const post = (url, params, format) => request(url, params, 'POST', format)

Usage Examples

POST Request with JSON Response

const params = { id: 1 }

post(url, params, 'json')
  .then(response => console.log('response'))
  .catch(err => console.log(`${err} - Ajax error`))
  .finally(() => {/* ... */ })

POST Request with Form Data and Text Response

const formData = new FormData()
formData.append('id', 1)

post(url, formData, 'text')
  .then(response => console.log('response'))
  .catch(err => console.log(`${err} - Ajax error`))
  .finally(() => {/* ... */ })

GET Request with JSON Response

get(url, params, 'json')
  .then(response => console.log('response'))
  .catch(err => console.log(`${err} - Erreur ajax`))
  .finally(() => {/* ... */ })

GET Request with Text Response

get(url, params, 'text')
  .then(response => console.log('response'))
  .catch(err => console.log(`${err} - Erreur ajax`))
  .finally(() => {/* ... */ })

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *