Creating a unique Ajax delete method for a specific id using vanilla JavaScript

How can I translate this Ajax call from jQuery to vanilla JavaScript?

What needs to be changed in order to convert it to vanilla JavaScript

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

I attempted to rewrite it myself, but encountered an error message in the console stating 'request is not defined'. I am concerned that it may not recognize the id.

request.open("DELETE", "/users/delete/" + this.dataSet('id')); 

Answer №1

There's nothing quite as basic as the classic xmlhttprequest method.

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.

Answer №2

If you want to interact with a server and delete data, consider utilizing the modern fetch API:

fetch(url, { method: 'DELETE' })
    .then((res)=>{
        res.json()
        window.location.href = '/'
    });

Answer №3

request is a node module that is not compatible with browsers (although there is a browser-friendly fork available, it is still not pure vanilla JS, but rather a library).

If you are okay with not supporting Internet Explorer (only Edge), you can utilize the 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

By the way, if you want to eliminate the $.data call, here is a plain JavaScript alternative:

var id = document.querySelector('.deleteUser').getAttribute('data-id');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using NodeJS in conjunction with mongoose to efficiently handle subqueries

I am dealing with two models: ModelA and ModelB. My goal is to transfer a tags = Array() column from ModelB to ModelA. Here's the approach I am taking: function run() { ModelA.find({}).limit(500).cursor() .on('data', function(doc) { ...

Create movement for an object when it is clicked and when the mouse cursor enters or leaves the object, as well as other

I am struggling with the layout of my webpage, which consists of 3 main div elements. https://jsfiddle.net/wpztofb7/ <body> <div id="topBox" class="otherBox"> TEST TOP </div> <div id="middleBox" class="middleBox"> ...

Sharing State with a Secure Route in Vue Router (using the script setup method)

Hello everyone, I'm encountering an issue while trying to send a state to the protected routes in vue-router. The error that I faced mentioned "Discarded invalid param(s) "_id", "dish_name", "description", "img" ...

Arrows within modal image (adjusting size based on image)

In my modal carousel, the position of the arrows changes based on the image resolution. I would like the arrows to always remain inside each image, regardless of resolution. ...

What is the process for invoking an Express route using Ajax?

I encountered a problem with calling an Express route in my Node.js application using Ajax when submitting a form. Here is the code for my route: router.post("/user", function(req, res) { console.log("FORM DATA: " + JSON.stringify(req.body)); res ...

Angular element for dynamic background image based on conditions

I am searching for a directive that can automatically set the background image to a specific image if it exists, or default to another image. The url is generated using the form /images/cards/card{{$index}}.jpg within an ng-repeat, however, not all images ...

Can we split the PHP Photo Gallery into a second page after displaying 12 images?

I recently developed a simple PHP photo gallery for my website that pulls data from a MySQL database. By using a while loop, I am able to display three images (from ID 1 to 3) in a single row, continuing this pattern until a total of 12 images are shown. ...

Navigating data flow between tabs in Ionic

I am working on a straightforward project that involves 3 tabs. One of the requirements is to move an item from the first tab to the second tab and vice versa when a button is clicked, with a notification sent to the server upon this action. Is there a way ...

The Webix text area does not adapt to different screen sizes

I'm just starting out with Webix. I have created a form that includes a textarea. webix.ui({ rows:[ { view:"form", id:"log_form", elements:[ { view:"textarea" ,height:700}, { margin:5, cols:[ { view:"button", value:"Save" , type:"form" }, { view:"b ...

Issues encountered when rendering textures from a canvas in Three.js

I've been working on creating a texture from a canvas. I managed to successfully render a blank canvas, but encountered issues when trying to draw an image on the canvas and then render it. This is the code snippet I am currently using: var canva ...

The mysterious Vue.js and Nuxt.js custom element

Encountering an issue https://i.sstatic.net/imRbe.png Seeking assistance with identifying my mistake. Attempting to create reusable components, starting with a button for example. I have created it in the file path: /components/MusicPlayer.vue: <temp ...

Using Typescript to establish a connection between ngModel and an object's property

Let's talk about how we can dynamically bind an input to an undefined property in an object. For example, we have an object named user: let user = {}; How can we bind an input to a property that doesn't exist yet? Like this: <input [(ngMode ...

jasmine and protractor test failing due to use of byID

My HTML markup is all set and valid. While using WebStorm to debug my test cases, I am able to view this specific element without any issues... <a id="privacyPolicy1234" on-tap="goPrivacyPolicy()" class="disable-user-behavior">Privacy Policy</a&g ...

Tips for creating an output directory when the TypeScript files are stored in the './src' location

Here is what I currently have: ./src/myfile.ts ./test/mytest.spec.ts I want tsc to output a javascript file (myfile.js) and a definition file (myfile.d.ts) in the ./build directory. This is my tsconfig.ts: { "compilerOptions": { "module": "common ...

javascript Transform an object into an array of objects

How can I transform an object into an array of objects? Input: { AF: 'Afghanistan', AX: 'Åland Islands', AL: 'Albania', DZ: 'Algeria' } Output: [ {value: 'AF', label: 'Afghanis ...

Sending data from JavaScript to PHP in the same function

Currently, I am encountering an issue related to passing JavaScript variables to PHP within the same function. Here is a snippet of my code: else if(msg_type[i] == 'code' ){ var code_action = 'test'; <?php function foob ...

Is there a way to customize the color of the HR element in a Material-UI Select Field?

https://i.stack.imgur.com/DYeX7.png https://i.stack.imgur.com/CN0T6.png Hi there, I am currently working on a website and using a Select Field component from Material-UI. I am faced with the challenge of customizing the style to change the default light ...

JavaScript array containing objects remains static

I'm facing an issue with a complex array of objects (I will only display the necessary nodes to explain the problem): var arr = [ { json: { doc: { id: 1, atualizacao:{ ...

Transform form array elements into JSON format using solely JavaScript or other client-side libraries

Currently, I'm developing a Joomla component and facing some issues with the serialization of my form data. To address this, my plan is to create a hidden textarea. This textarea will be populated with the JSON data generated as the form is filled out ...

Modifying various properties of a nested array of objects in a state using a dynamic object

I am attempting to modify a nested state array using an object with dynamic keys, but I seem to be running into some issues and could use some guidance: state array: [ 0: { createdTime: 'XXX', id: 'XXX', fields: { ...