Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery serialize in javascript

I'd want to know if there is something in javascript that can do the same job as .serialize() does. I'll need to use it someform.onsubmit = funct... or <form onsubmit=".... I need just to get all the data in that form (just as jQuery does) as a string.

Thank you in advance

like image 766
AMD Avatar asked Jun 01 '26 08:06

AMD


1 Answers

I think the closest thing would be to use FormData. Something like:

document.querySelector('form').addEventListener('submit', function (e) {
    e.preventDefault();

    xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            console.log(xhr.responseText);
        }
    }
    xhr.open("POST", "/echo/json");
    xhr.send(new FormData(this));
});

This is arguably even simpler than calling .serialize on the form collection, but note that you can't inspect what is inside the FormData object apparently. This is also relatively new, so not so cross-browser compatible.

like image 61
Explosion Pills Avatar answered Jun 03 '26 20:06

Explosion Pills



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!