Search code examples
javascriptxmlhttprequest

XMLHttpRequest - Which format does request.send(data) expect for data?


I have to use a XMLHttpRequest, but I don't know which data format is expected by the function request.send(). I searched for too long now.

I tried to pass a JSON object but it does not work:

    var request = new XMLHttpRequest();

    request.open("GET","fileApi");

    var data = {
        action: "read",
        targetFile: "testFile"
    };

       request.addEventListener('load', function() {
          if (request.status >= 200 && request.status < 300) {
             $("#messageOutput").html(request.responseText);
          } else {
             console.warn(request.statusText, request.responseText);
          }
       });
    request.send(data);

I get updateFile:155 XHR finished loading: GET "http://localhost/cut/public/fileApi".

But no data is received on the server. I made this simple check to approve this:

PHP (server side):

$action = filter_input(INPUT_GET, "action");
$targetFile = filter_input(INPUT_GET, "targetFile");

echo ("action = '$action' | targetFile = '$targetFile'");
exit();

Returns: action = '' | targetFile = ''

Unfortunatelly I can't use jQuery in my application, since the target is a C# Webbrowser (Internet Explorer) and it detects errors in the jQuery file and stops my scripts from working...


Solution

  • I don't know which data format is expected by the function request.send()

    It can take a variety of formats. A string or a FormData object is most common. It will, in part, depend on what the server is expecting.

    I tried to pass a JSON object

    That's a JavaScript object, not a JSON object.

    request.open("GET","fileApi");
    

    You are making a GET request. GET requests should not have a request body, so you shouldn't pass any data to send() at all.

    GET requests expect data to be encoded in the query string of the URL.

    var data = {
      action: "read",
      targetFile: "testFile"
    };
    
    var searchParams = new URLSearchParams();
    Object.keys(data).forEach((key) => searchParams.set(key, data[key]));
    var url = "fileApi?" + searchParams;
    console.log(url);
    // and then… 
    // request.open("GET", url);
    // request.send();

    Warning: URLSearchParams is new and has limited browser support. Finding a library to generate a query string is left as a (simple) exercise to any reader who wants compatibility with older browsers.