0

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.

Grufas
  • 1,350
  • 4
  • 21
  • 33
  • 1
    JSON.stringify(yourObject) will convert the object to string in JSON format if that what you need – Yosi Leibman Dec 04 '22 at 12:36
  • Did you try?: [Make XmlHttpRequest POST using JSON](https://stackoverflow.com/q/39519246) – Nick Parsons Dec 04 '22 at 12:41
  • It gives {"first":"a","second":"b","third":"c"} instead of first=a&second=b&third=c Console raw result must be formdata with raw result: first=a&second=b&third=c. I need that to do checks in .php like – Grufas Dec 04 '22 at 12:44

1 Answers1

1

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;
}
andrii
  • 104
  • 5