Menü schliessen
Created: April 22nd 2022
Last updated: April 27th 2022
Categories: Common Web Development,  JavaScript Development
Author: Tim Fürer

JavaScript AJAX: POST Request Helper Function Using Fetch API

Tags:  Ajax,  async,  Javascript,  js
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Ever got tired from writing POST Requests? Wish it could be simpler? All without the use of any bloated libraries such as jQuery?


The SOlution

This nifty little helper-function here is all you need:

function qpost(t,e,o=!1){let c=!1;switch(typeof e){case"object":if(e instanceof FormData)break;for(const t of Object.keys(e))"object"==typeof e[t]&&(e[t]=JSON.stringify(e[t]));e=new URLSearchParams(e).toString(),c="application/x-www-form-urlencoded";break;case"string":let t=!0;try{JSON.parse(e)}catch{t=!1}t&&(c="application/json")}const r={};return c&&(r["Content-Type"]=c),o&&(Array.isArray(o)?r.Accept=o.join(", "):r.Accept=o),fetch(t,{method:"POST",headers:r,body:e})}

< 500 Characters | < 500 Bytes

Reference

qpost(url, data, accept?): Promise<Response>

Sends POST request with provided data to specified url via the Fetch API and returns a promise that resolves into a response. If defined, only allows responses of accepted MIME type/s.

Parameters

  • url
    (string) The URL to send the POST request to.
  • data
    (object | JSON string | FormData) The data to send along with the request. Note that nested objects are automatically converted into JSON strings.
  • accept
    (string | Array<string>) (Optional) Expected MIME type/s of response.

Return

(Promise<Response>) A promised response to the sent request.


Examples (vs Fetch)

Example A

qpost does not require you to research and provide the correct Content-Type, it does this for you. It also converts your data into a parameter string if needed. These aspects allow qpost to function with only two simple parameter inputs.

Test Data

const Data = {
    action: 'login',
    email: login_email
}

fetch

fetch(url, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: new URLSearchParams(Data).toString()
})

qpost

qpost(url, Data)

qpost automated:

  • setting the method to POST
  • setting the Content-Type to the correct value ("application/x-www-form-urlencoded" for parameter strings)
  • converting the data into a parameter string (new URLSearchParams(Data).toString())

Example B

qpost will automatically convert nested objects contained within your data into JSON strings. No need for you to further complicate the way you structure things.

fetch

const Data = {
    action: 'save',
    data: JSON.stringify({
        a: 'foo',
        b: 'bar',
        c: 'hello',
        d: 'world'
    })
}

qpost

const Data = {
    action: 'save',
    data: {
        a: 'foo',
        b: 'bar',
        c: 'hello',
        d: 'world'
    }
}

qpost automated:

  • converting nested objects into JSON strings

Useful Resources