title: how to convert a nested JSON object to a URL query string to pass by AJAX?
body: <p>I am trying to write an Ajax request using JavaScript (without jQuery) and related to <a href="https://plainjs.com/javascript/ajax/send-ajax-get-and-post-requests-47/" rel="nofollow noreferrer">this tutorial</a>, I have this function now:</p>
  <pre><code>function postAjax(url, data, success) {
          var params = typeof data == 'string' ? data : Object.keys(data).map(
                  function(k){ return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) }
              ).join('&amp;');
  
          var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;);
          xhr.open('POST', url);
          xhr.onreadystatechange = function() {
              if (xhr.readyState&gt;3 &amp;&amp; xhr.status==200) { success(xhr.responseText); }
          };
          xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
          xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
          xhr.send(params);
          return xhr;
      }
  </code></pre>
  <p>and I can send data using JSON format like this:</p>
  <pre><code>postAjax(MY_SERVER_URL, { p1: 1, p2: 'Hello World' }, function(data){ console.log(data); });
  </code></pre>
  <p>and on the server, I only have <code>print_r($_POST)</code>, then the output is:</p>
  <pre><code>Array
  (
      [p1] =&gt; 1
      [p2] =&gt; Hello World
  )
  </code></pre>
  <p>But when I have a nested JSON, it will show me <code>[object Object]</code> as output instead of each array and object in my JSON. for example:</p>
  <pre><code>postAjax(url, { p1: 1, p2: {'test_name':'Hello World'} }, function(data){ console.log(data); });
  </code></pre>
  <p>Output:</p>
  <pre><code>Array
  (
      [p1] =&gt; 1
      [p2] =&gt; [object Object]
  )
  </code></pre>
  <p>Can you please guide me how I should convert a nested JSON to a URL query string to pass by AJAX?</p>
  <h1>Update</h1>
  <p>Please note that I can convert whole of my nested JSON to a string using <code>JSON.stringify</code> and pass it to the server, but as you probably know, if I use some libraries like jQuery, you can send nested JSON to the server and you don't need to decode the string on the server. the <strong>point of this question</strong> is exactly how some library like jQuery is passing data to the server that you can get it directly without any decoding?</p>