2

How do I write this peace of Ajax call that is written in jQuery, completely in vanilla JavaScript

What should be converted into vanilla javascript

$.ajax({
 type: "DELETE",
url: "/users/delete/" + $(".deleteUser").data('id');
}}

What I think it should be, but the console log gave me the following error message : request is not defined. And I am afraid it would not pick up the id.

request.open("DELETE", "/users/delete/" + this.dataSet('id')); 
Frontend employee
  • 719
  • 2
  • 12
  • 26

3 Answers3

4

You can't get any more vanilla then good old xmlhttprequest.

var xhr1 = new XMLHttpRequest();
xhr1.open('DELETE', "http://127.0.0.1:80/users/delete/", true);
xhr1.onreadystatechange = function() {
    if (this.status == 200 && this.readyState == 4) {

        dostuff = this.responseText;
  };//end onreadystate
 xhr1.send();

Enjoy.

Hunter
  • 388
  • 4
  • 11
3

You can simply use the new fetch API:

fetch(url, { method: 'DELETE' })
    .then((res)=>{
        res.json()
        window.location.href = '/'
    });
RWAM
  • 6,760
  • 3
  • 32
  • 45
Ayman THEE
  • 51
  • 3
1

request is node module, it is not available in browser (altho there is a fork for browser, still it is not vanilla JS, but a library instead).

If you are fine with not supporting IE (just IE, edge should be fine), you can use fetch API:

fetch("/users/delete/" + $(".deleteUser").data('id'), {
    method: "DELETE",
}}.then(function (response) {
    console.log(response);
});

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

Btw I guess you also want to get rid of the $.data call, this is vanilla JS version:

var id = document.querySelector('.deleteUser').getAttribute('data-id');
Martin Adámek
  • 16,771
  • 5
  • 45
  • 64