Search code examples
javascriptxmlhttprequest

Convert Javascript object to a form data result like Jquery Ajax does


I send POST data with XMLHttpRequest. I want to pass multiple parameters. As far as I know, this is the only way to do it:

xhr.send('first=first&second=second&third=third');

Is there a way to use Javascript object instead?

let formDataObject = {
    first: 'a',
    second: 'b',
    third: 'c'
};

Jquery converts objects exactly how I need, but I no longer want to use Jquery.

By passing Javascript object to xhr.send, I want final result to look like: enter image description here

The reason I need the request result to be Form data type and not Json, because on PHP side I want access POST data like so:

<?php if($_POST['first'] == 'a') {...

I know that I can decode Json on php side and do the required check, but I want to achieve exactly the same result as Jquery Ajax does.


Solution

  • This function should help!

    function encodeURI(obj) {
      var result = '';
      var splitter = '';
      if (typeof obj === 'object') {
        Object.keys(obj).forEach(function (key) {
          result += splitter + key + '=' + encodeURIComponent(obj[key]);
          splitter = '&';
        });
      }
      return result;
    }