Plain JS http GET
On one simple web project, I just surprised myself that I don’t know how to do AJAX with just plain JS.
It’s not quite make sense to install a package to do just one AJAX request-response. So I find the way here.
Built-in HTTP GET
This is the simplest request and response cycle without error handling. Let’s explain some code here.
line 1: we declare function in order to bind this with html e.g. button onclick
Warning: binding within <form>
have default behavior you need to override
line 2: XMLHttpRequest is the native object here
line 4: onreadystatechange is config everything will work only when you xhr.send()
in line 13
line 6: make sure to parse this response is just text string
line 10: true
mean asynchronous with callback function. You have no choice here since false
for synchronous i.e. wait for the response is deprecated.
line 13: everything won’t be happened without xhr.send()
More Control
There are method like onerror
, onload
, onloadstart
etc. to give you a comprehensive handling of events. But if it turns more complicated and you have more than just few AJAX, I would recommended Fetch API which is Promise object providing chaining syntax like .then() .error() which makes code shorter, cleaner and less redundant.
Note: fetch
is now widely default to browser. Check here if you need to poly-fill it or not.
Software house, IoT and AI service
www.codemonday.com