javascriptxmlhttprequest

Use XMLHttpRequest to replace contents of div after form submit?


I have an html form that filters a list of results in a div.

What I want is that only the contents of the div are reloaded instead of the whole page, and only using vanilla javascript.

This is what I have so far and it is not returning the filtered results:

document.querySelector('form[name="filters"]').addEventListener('submit', function (e) {
    
    e.preventDefault();
    var xhttp = new XMLHttpRequest();
    var action = document.querySelector('form[name="filters"]').getAttribute('action');
    var list = document.querySelector('.list');
    xhttp.responseType = "document";
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          list.innerHTML = this.response.querySelector('.list').innerHTML;
        };
    };
    xhttp.open("POST", action, true);
    xhttp.send();

});

Solution

  • The issue with your current XMLHttpRequest implementation is that you’re making a POST request, but you’re not actually sending the form data. That means your server has no idea what filters you’re applying, so it’s just returning the default results instead of the filtered ones.

    So you need to add the form data to send:

    xhttp.send(new FormData(e.target))