Can AJAX Delete requests be executed without using jQuery?

Is it possible to use AJAX delete request without using jQuery? My JSON object at localhost:8000 appears like this:

{
    "Students":[{"Name":"Kaushal","Roll_No":30,"Percentage":94.5},
    {"Name":"Rohit","Roll_No":31,"Percentage":93.5},
    {"Name":"Kumar","Roll_No":32,"Percentage":45.5}]}

I am looking for a way to incorporate a delete button that can remove a single record. Any help with the code would be greatly appreciated.

 

function loadDoc(){ 
        
        var table2="<tr><th>Name</th><th>Roll_No</th><th>Percentage</th></tr>"
         var url2="http://localhost:8000/Students"
         var xhttp2=new XMLHttpRequest();
           xhttp2.onreadystatechange = function(){
            if(xhttp2.readyState === 4 && xhttp2.status === 200){
                var jsonArr = JSON.parse(xhttp2.responseText);   
                for(i in jsonArr){
                    table2 += "<tr><td>"+jsonArr[i].Name +
                              "</td><td> "+jsonArr[i].Roll_No+
                            "</td><td>"+jsonArr[i].Percentage+"</td><tr>"     
                        }
                        document.getElementById("mytable").innerHTML = table2;
  

            }
            
        
       
        }
        
        xhttp2.open('GET',url2,true);
        xhttp2.send();
 

 table,th,td{
            border:1px solid black;
            border-collapse: collapse;
        }
 <button onclick="loadDoc()" >Get Data</button>
    <br>
    <br>
    <table id="mytable">
    </table>

Answer №1

Here is a solution that should get the job done:

function httpRequest() {
    this.request = new XMLHttpRequest();
}

httpRequest.prototype.remove = function(url, callback) {
    this.request.open("DELETE", url, true);
    var self = this;
    this.request.onload = function() {
        if (self.request.status === 200) {
            callback(null, "Item Deleted");
        } else {
            callback("Error: " + self.request.status);
        }
    };
    this.request.send();
};

Alternatively, here's another example which might be easier to understand:

deleteItem('https://jsonplaceholder.typicode.com/posts/1');

function deleteItem(url) {
    var xhr = new XMLHttpRequest();
    xhr.open("DELETE", url);
    xhr.send();
    xhr.onload = function() {
        if (xhr.status != 200) {
            console.log('ERROR');
        } else {
            console.log('ITEM DELETED!');
        }
    };
    xhr.onerror = function() {
        console.log('NO CONNECTION');
    };
}

Answer №2

One way to achieve this is by utilizing the JS Fetch API:

const apiUrl = 'https://www.website.com/endpoint';

const deleteData = async (apiUrl) => {
  const response = await fetch(apiUrl, {
    method: 'DELETE'
  });
  
  const responseData = await response.json();  // parsing the response data as JSON
  return responseData;
}

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

reconfigure form credentials with JavaScript

I am currently working on a form that includes a textbox and a button for submitting data using ajax. <input type="password" id="password" /> <button id="addaccount" onclick="showload();">Add</button> When the user clicks on the button, ...

Having trouble with a single GET request not functioning properly on Safari due to an Authorization issue in Angular 6

I've encountered this issue in several locations, yet haven't found a clear solution. Only one GET request is showing as unauthorized (401), but when I check the debugger, everything seems to be fine and all other requests are functioning properl ...

The information retrieved from the API is not appearing as expected within the Angular 9 ABP framework

I am facing an issue with populating data in my select control, which is located in the header child component. The data comes from an API, but for some reason, it is not displaying correctly. https://i.stack.imgur.com/6JMzn.png. ngOnInit() { thi ...

How to Restrict the Use of Conditional "If" Statements in Another Function in Angular 7

How can I use an IF condition inside a function to only execute once for a specific action and not for another action? I have a function that is called twice, but I want the first "IF" condition inside the function to only be triggered when the add bank b ...

What is the best method for pulling in a static, plaintext JSON file into JavaScript through a GET request?

Currently, I am running a test with this specific link: accessing static json data I have encountered several issues with cross-site request errors. It is puzzling to me why it should be any different from loading an image that is hosted on the same site ...

Modify an HTML table and record any modifications as POST requests using Javascript

As a beginner in JavaScript and HTML, I am open to corrections if I am not following the correct practices. Recently, I delved into editing an HTML form table. {%extends 'base.html'%} {%block content%} <html> <body> <h4> Search ...

Is it possible for search engines like google to index Javascript content that is stored within divs and loaded onto the page?

My website utilizes JavaScript to dynamically add content to div elements, like so: <script> //This content is generated by PHP var contents = [ "Item 1", "Item 2" ]; //Display the first item document.getElementById( "item" ).textCo ...

Leveraging a unique JavaScript function in AngularJS from a separate controller or directive

I am currently working on a JavaScript file named 'linechart.js' which functions as a library. Inside this file, there is an object that contains a function responsible for generating a line chart using D3 when provided with some data. The code s ...

JSON payload with an array that includes nested JSON objects

I am struggling with JSON objects and need to create a JSN structure similar to the following: { name: 'root', children: [ name: 'son1', children: [....] ] } Could someone please guide me on how to construct it using Java ...

Make the header stretch to the top of the page using CSS rounded edges

I'm trying to eliminate the white space above my blue header on a webpage with rounded corners. The header is at the top of the wrapper, but there's some empty space before it starts. Is there a way to make the header start right at the top edge ...

random mongoose response 500

I came across a nodeJS code recently that was supposed to retrieve random documents from my mongoose collection using the mongoose-random plugin. However, whenever I call the findRandom() method, it returns a 500 error. test.js Below is the code snippet: ...

Creating a diagonal division border using CSS alongside a background image

I've been attempting to place 2 divs next to each other with a diagonal space between them. While I've come across several tutorials and discussions on Stack Overflow about creating diagonal divs, they often involve using borders with solid color ...

What is the best way to ensure that this header remains adaptable to different screen

Looking for guidance on creating a fluid and responsive header design similar to the curved images shown at this link or this link. How can I ensure that my design maintains its shape without distortion when viewed on different devices? Any suggestions a ...

Navigating through a JavaScript object array within another object

I am looking to iterate through a JavaScript object array Here is my object response: { "kind": "calendar#events", "etag": "\"p3288namrojte20g\"", "summary": "pedicura", "updated": "2019-05-01T14:25:51.642Z", "timeZone": "America/Argentina ...

What steps should I follow to successfully incorporate Zurb Foundation 4 Sections (tabs) into my Javascript Ajax functionality?

I am currently incorporating Zurb Foundation 4.1.5 into my application and I am faced with the challenge of implementing Zurb Section Javascript to handle "tabs" on the page. The content within these tabs is dynamic and fetched via Ajax calls. I am seeking ...

PHP reCAPTCHA integration with AJAX functionality

I have been attempting to integrate a reCAPTCHA into my PHP contact form using AJAX. The goal is to present the user with the reCAPTCHA challenge and allow them to input it. If the input is incorrect, an error message should be displayed without refreshing ...

What is the best way to style radio boxes in HTML to resemble checkboxes and display X's when selected?

I'm looking to create a form with radio boxes that resemble checkboxes and display a glyphicon x when selected. I've experimented with various solutions such as: input[type="radio"] { -webkit-appearance: checkbox; /* Chrome, ...

Using CSS to Put Text in the Back of Other Text

After being inspired by the structure of view-source:, I attempted to layer one instance of text behind another using z-index. However, my initial attempt failed as it became clear that utilizing z-index required the position attribute to work effectively. ...

Changing the background color of the canvas using Javascript

I want to create a rect on a canvas with a slightly transparent background, but I don't want the drawn rect to have any background. Here is an example of what I'm looking for: https://i.stack.imgur.com/axtcE.png The code I am using is as follo ...

Hello there! I'm a beginner in React js and I was wondering if you could assist me in transforming this class component into

Hey there! I have the following code snippet and I'm looking to convert this class component to a functional component in React js. I'm new to React and could use some guidance on how to achieve this. My goal is to create a button that, when clic ...