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.

3
  • 1
    JSON.stringify(yourObject) will convert the object to string in JSON format if that what you need Commented Dec 4, 2022 at 12:36
  • Did you try?: Make XmlHttpRequest POST using JSON Commented Dec 4, 2022 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 <?php if($_POST['first']=='a')... Commented Dec 4, 2022 at 12:44

1 Answer 1

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;
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.