0

I am sending an AJAX request to my backend application using the following code:

function add() {
    ajax('add', 'POST', {
      content: ['abc', 'xyz,123']
    });
}

function ajax(endpoint, method, payload, callback) {
  const xhttp = new XMLHttpRequest();
  const url = 'http://localhost:3000/' + endpoint;

  xhttp.onreadystatechange = function() {
    console.log('readyState: ', this.readyState);
    if (this.readyState === 4) {
      if (this.status === 200) {
          console.log('success!');
          if (callback) {
            callback();
          }
      } else {
          console.log('error: ', JSON.stringify(this));
      }
    }  
  };
  xhttp.open(method, url, true);
  xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  if (payload) {
    xhttp.send(new URLSearchParams(payload));
  } else {
    xhttp.send();
  }
}

As you can see, I am passing an array of strings to the ajax function. The function formats the array using URLSearchParams() before sending it with the request. This results in a url formatted string of parameters that looks like this:

content=abc,xyz,123

But you'll notice that the original array consisted of only two strings, one of which was "xyz,123". Because of the comma, however, the url formatted string ends up looking like 3 strings: "abc", "xyz", "123".

The backend needs a way of distinguishing between the case where there really are n original strings and the case where there are < n original strings, one or more of which contain commas. Is there a different way of formatting the array of strings other than using URLSearchParams(), or is there something I can do with commas in the strings before calling URLSearchParams()? Or is there another way of accomplishing my goal?

Thanks.

gib65
  • 1,709
  • 3
  • 24
  • 58
  • What is the expected result? If not `content=abc,xyz,123`, what should the result look like instead? That is, what does the backend expect it to look like? – sideshowbarker Feb 15 '23 at 05:36

0 Answers0