Ajax In Vanilla Javascript

Jan 31, 2017 ajax vanilla javascript jquery
I was sending in a request via jQuery for my new project and was curious what the code was to do it in vanilla javascript. So here it is below.

Vanilla Javascript

var data = JSON.stringify({lat: parseFloat(latCoord), lng:parseFloat(longCoord)});
var xhr = new XMLHttpRequest();
var url = '{{ url('/dropnote/markers') }}';
xhr.open('POST', url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('X-CSRF-TOKEN', csrfContent);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
//console.log(xhr.status); // 'This is the returned text.'
//console.log("Response Text" + xhr.responseText);
else {
//console.log('Error: ' + xhr.status); // An error occurred during the request.


headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token-post-marker"]').attr('content')
var id = 12; // A random variable for this example

method: 'POST', // Type of response and matches what we said in the route
url: '/dropnote/markers', // This is the url we gave in the route
data: {'id' : id}, // a JSON object to send back
success: function(response){ // What to do if we succeed
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);

As we can see that both approaches are similar as they should be, but the vanilla javascript has structure and the jQuery approach is condensed and organised, with a lot less fiddling around. It’s good to understand both, as one shows the steps it takes to contact the server and receive the information back, and the other a quick approach without the need to remember many different methods.

However because the vanilla javascript is much more concise with the error codes it’s possible that the code may miss error codes that the server could potentially return; such as a successful response of 200 to 299. An easy fix in the if condition but something small enough that could cause havoc. On the jQuery side, it automatically covers you and is no need to think about successful responses further.

If you’re working on an existing backend jQuery would be less of a hassle but if you’re building it from scratch server/client it can be a bit of fun and a great learning experience to taste the vanilla flavour.

If you found the following info helpful, I'm happy to accept any donations of the following cryptocurrencies.

  • Bitcoin - 17DTiPExzP9StqveW428acEyB4mVMfKbiK
  • Ethereum - 0x87B8307FD20dc90cc05c94905Ec593134D32B6FF
  • Litecoin - LZMiz5U5sVq9doMLYE3gfLJrxCQDKuyCmU
  • Neo - AXv71WB38ajc1KUUEnxQKhynLLPc4BapVb