Using ASP, create an AJAX request to execute a straightforward SQL DELETE query

Hello, I am looking to delete all the information from a SQL server table using an AJAX function. Below is my C# method:

[WebMethod]
    public static  void deleteCertificado()
    {
        SqlConnection conn = new 
        SqlConnection(ConfigurationManager.ConnectionStrings["default"].ToString());
        string strsql = "DELETE * FROM Fiel";
        SqlCommand comando = new SqlCommand(strsql, conn);
        comando.CommandTimeout = 36000;
        comando.ExecuteNonQuery();
    }

Here is my JavaScript function:

function testDel() {
if (confirm('Are you sure you want to delete this?')) {
    $.ajax({
        url: 'Delete.asmx/deleteCertificado',
        type: 'Delete',
        data: {},
        success: function () {
            alert("Record deleted successfully");
        }
    });
} else {}

I just want to call the method without any specific user ID or data. How can I achieve this? My field "data" is empty as I simply want to delete all the information of the table.

Answer №1

Before we dive into the code, I want to reference a similar question on Stack Overflow from 5 years ago. It emphasizes the importance of using newer technologies like web API over the outdated asmx.

Now, looking at your code, there are a couple of issues that need addressing:

  1. ASMX doesn't support delete requests, so you should switch your request type from 'Delete' to 'Post' in your jQuery ajax code.
  2. Your WebMethod should not be static.

Another improvement is to utilize the using statement for proper resource disposal. Here's a better version of your Webmethod:

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public void deleteCertificado()
    {
        using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["default"].ToString()))
        {
            string strsql = "DELETE * FROM Fiel";
            using (var comando = new SqlCommand(strsql, conn))
            {
                comando.CommandTimeout = 36000;
                comando.ExecuteNonQuery();
            }
        }                
    }

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 Jquery to delete the parent element containing text that does not match

I need to search for text in a table cell that matches the text in an h1 heading and then eliminate all other table rows containing text that does not match. The code snippet provided only works if there is one .tablerow with a .tablecell, so I am looking ...

Promise.each encountered an unhandled rejection

I'm currently facing a challenge in making multiple database queries using bluebird's Promise.each(). So far, I haven't been able to effectively handle rejections, especially when multiple promises fail. Interestingly, when attempting the sa ...

Ensuring file extensions are validated prior to file uploads

When uploading images to a servlet, the validation process checks if the uploaded file is an image by examining the magic numbers in the file header on the server side. I am wondering if there is a way to validate the extensions on the client side before s ...

What is the best way to iterate through an array of objects with JavaScript?

I'm encountering an issue while attempting to iterate through an array of objects, as I keep receiving the error message: "Cannot set property 'color' of undefined". Could someone please help me troubleshoot this problem? var ObjectTest = ...

Tips for retrieving the chosen value from a dropdown list in HTML

I'm having an issue with exporting specific values from multiple HTML tables into an excel file. My goal is to only export the selected values from each table, with each table being on a separate tab in the excel file. Currently, when I export the ta ...

Could this task be accomplished within a C# ASP.NET web application?

My goal is to create a Web Application with two buttons that will allow users to open two simple text files from their browser. The selected files will then have their contents read into two strings. The challenge lies in the fact that the files are not kn ...

Exploring Enum properties within an angular js select drop down

I am working with an enum in Java that looks like this: public enum myEnum{ enum1("enumDisplayVal1"), enum2("enumDisplayVal2") myEnum(String displayValue) { this.displayValue = displayValue;} private String displayValue; public String getDisp ...

"Exploring the new features of Node.js 14 with ECMAScript modules

When exploring Node's official documentation regarding its built-in support for ECMAScript modules, it is mentioned that There are different types of specifiers: ... Bare specifiers such as 'some-package' or 'some-package/shuffle&apo ...

Guide on retrieving just the time from an ISO date format using JavaScript

let isoDate = '2018-01-01T18:00:00Z'; My goal is to extract the time of 18:00 from the given ISO date using any available method, including moment.js. ...

Disappear text gradually while scrolling horizontally

There is a need to create a special block that displays fading text on horizontal scroll. However, the problem is that the block is situated on a non-uniform background, making the usual solution of adding a linear gradient on the sides unsuitable. Click ...

The partial class within the entity framework does not undergo serialization for its string property

I'm having trouble serializing a string property within a partial class in Entity Framework. public partial class TableTest : EntityObject { public String TestA { get { return "ok"; } } [XmlElement ...

How do you modify the attribute of a Label in the ItemTemplate within a FormView?

Within my ASP.NET application, I am utilizing a FormView that is connected to an ObjectDataSource. The FormView contains an ItemTemplate with a Delete button and a Label. I am using the OnItemDeleted event of the FormView to catch any exceptions that may o ...

When downloading text using Angular, the file may not display new line characters correctly when opened in Notepad

When downloading text data as a .txt file in my Angular application using JavaScript code, I encountered an issue. Below is the code snippet: function download_text_as_file(data: string) { var element = document.createElement('a') eleme ...

Flickering of image in JavaScript when mouse is hovered over and removed

I recently encountered an issue while attempting to create a mouseover effect that would display a larger image when hovering over a smaller default image. The problem arose when the larger image started flickering uncontrollably upon hover. Check out the ...

Utilizing AXIOS in React functional components for REST API integration

When trying to parse Rest API responses with JSON using AXIOS in a functional component, the issue arises where it initially returns an empty array before displaying the exact API response data after rendering. This can be confusing as the return function ...

Transferring information from user control to main page during a postback操作

I am looking to develop a user control that can retrieve and filter datasets. The challenge I am facing is that the controls that need to be populated are located on the main page where the user control is embedded, rather than within the user control itse ...

Switch the page direction in Aspx to go from right to left

Looking for advice on transitioning a LTR direction page to also support RTL direction. My main concern is ensuring that the content in the center of the page maintains a polished appearance. Any tips on achieving this transition smoothly without creating ...

Tips for transferring a geolocation lat lng to the `ll` property of a different function in React

I have a Geolocation.js file that retrieves the geolocation data and logs it to the console. This file is imported into an index.js file and I need to use the lat and lng values that are logged to replace the hardcoded values in the ll parameter in the fol ...

The parameter type 'NextHandleFunction' does not match the expected type 'PathParams' in the argument

After successfully setting up TypeScript with a basic Express server, I've encountered an issue. import bodyParser from 'body-parser'; import express, { Express } from 'express'; const app: Express = express(); app.use(bodyParser ...

Issue with setting position to the right using jQuery CSS

I have a div with the CSS property position:absolute. I am attempting to align it to the right using jQuery, but for some reason it is not working as expected. In the code snippet below, I am removing the left positioning and adding right:0 in order to m ...