Delete an element using JavaScript when clicked and then store the data in an SQL database

My goal is to implement a feature in a web application that allows users to remove a div by clicking on an "x" button placed over the div. The web app is built using ASP.NET and I also need to update a value in an SQL table to indicate that the user has closed the div, so it doesn't display next time they visit the page. The challenge here is to achieve this without reloading the page (postback), enabling me to animate the div sliding or fading away using jQuery while ensuring that the app remembers the action. Below is the code I have implemented so far.

ASP.NET

<asp:Button ID="ConCloseButton" class="CloseBut" runat="server" OnClientClick="closeConPanel();return false;;" OnClick="ConClose_Click"  Text="&#10006;" />

Here is my JavaScript

function closeConPanel() {
    document.getElementById('con-feed').style.display = 'none';
}

And here is the C# server-side code

protected void ConClose_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection("Data Source=xxxx;Initial Catalog=xxxxxx;User ID=xxxxxx_user;Password=xxxxxxxx_user");
    conn.Open();
    SqlCommand cmdUpdate = new SqlCommand("Update CookieInfo Set ConstNewsData='0' where UserEmailId='" + (Label1.Text).ToString() + "'", conn);
    cmdUpdate.ExecuteNonQuery();
    conn.Close();
    HttpCookie cookie = Request.Cookies["Dashboard"];
    cookie["ConstNews"] = "0";
    cookie.Expires = DateTime.Now.AddYears(1);
    Response.Cookies.Add(cookie);
}

In summary, when a user clicks on the ASP Button, the "con-feed" div should be hidden and the app should remember this preference based on their email address stored in the SQL table. If the user closes the div, its state will be set to '0' and it won't be displayed upon subsequent visits. However, if the state is '1', the div will remain visible. Everything is functioning as intended, but I am aiming to accomplish this without triggering a postback.

Answer №1

Instead of linking your ConClose_Click logic to an event, consider creating a separate page that can be called directly through AJAX, like "RemoveDivFromDB.aspx".

Update your javascript function to include:

function closeConPanel() {
    document.getElementById('con-feed').style.display = 'none';
    $.ajax({
          url: "/RemoveDivFromDB.aspx?id=con-feed",
          type: "get"
     });
}

Make sure to handle success and failure cases with appropriate javascript methods. More information can be found on the jquery site: http://api.jquery.com/jQuery.ajax/

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

Error encountered in the auth service Observable for the Metronic Angular 8 login page. The issue persists when utilizing the same source code in the default component, where it functions

Issue with Observable in Metronic Theme Angular 8 I have encountered an error while using the auth service in another component of the Metronic Theme for Angular 8. The same service works without any errors in the default logic component. this.auth ...

Cookies in Chrome must be set with the assistance of a server

I recently completed a small project that does not rely on a server for functionality. In this project, I utilized cookies to store and retrieve values. Surprisingly, the project works seamlessly in Firefox, Safari, and IE 9 as it successfully sets and ret ...

What is the best choice for a base image when containerizing an API that relies on .NET Framework 4.6.1?

Seeking advice on how to dockerize a Rest API built on .Net framework 4.6.1. I've tried using the mcr.microsoft.com/dotnet/framework/aspnet:4.8 image, but the issue persists as most solutions are geared towards other versions like 4.6.2 or 4.7.0. Bel ...

What is the best way to insert text into a paragraph tag using JQuery?

As part of my learning journey on Codecademy, I decided to challenge myself by creating my very first Chrome extension using HTML/CSS, jQuery, and Javascript. My initial goal is to learn how to append text to a paragraph tag when a button is clicked. Here ...

Unusual Glitch in Bootstrap 3 Dropdown Menu

I am currently developing a website using Bootstrap 3. I am encountering an issue with the navbar dropdown. When I click on the link, it changes to show "expand child menu" and "collapse child menu". To clarify, here is the image I am referring to: Initi ...

Adding a new key-value pair to an array of objects in JavaScript based on a specific condition

My collection consists of dictionaries var nodes = { A: {'name' : 'A'}, B:{'name' : 'B'}, C:{'name' : 'C'}, D:{'name' : 'D'} E:{'name' : 'E'}} as well as ...

Guide on transferring three js variable to an HTML label element

For my project, I am looking to pass three js values to the label of a div. The desired output is: stWay: stProposer: stTime: hello John 2017-09-07 I have successfully programmed a button to make div1 a ...

What is the best method to transform URI data encoded in base64 into a file on the server side?

Looking for a solution to save a URI-data string as a jpg on the server using only Javascript. The alternative of writing it to a canvas and reading the image from there is not ideal. Any ideas? ...

What is the best method for concealing a Link React component entirely?

I have implemented a sidebar feature with settings that allow the user to toggle the visibility of desired sections. Here is an example of how this component appears: <List> {section.elements.map((subsection) => ( <ListItem key={subsection ...

Is there a way to eliminate the initial text from a string using jQuery?

var selectedCustomers = document.getElementById("hfCustomerID"); display: "|1|2|3" This hidden field contains stored pushed values. The values in the hidden field are formatted as "|1|2|3". When this string is split and pushed into a ...

Ask the user for their input regarding upcoming modifications

On my ASP.NET page, I have various editable dropdowns, textboxes, and display-only fields. I am seeking a way to monitor any changes made by the user to dropdown values or textbox entries. If the user clicks the goBack button, I want to provide a warning ...

The function dispatch is not recognized and will be removed from the database. An error will be generated indicating that dispatch is not a valid function

There seems to be an issue with the delete function in Ticket Actions as it is giving an error that dispatch is not a function. The goal here is to enable users to delete specific tickets by clicking on them and also provide an option to edit the ticket. ...

Unable to retrieve grade from API JSON

After making a request to the API, I received the following data results: "tabledata": [ { "itemname": { "class": "level1 levelodd oddd1 b1b b1t column-itemname", "colspan": 7, " ...

When making an Ajax request, the response is received successfully, however, the success, complete, and error

I am attempting to retrieve SQL results from a database using an AJAX call and display them on another PHP page. Here is my AJAX call code: function newfunc(){ start += 10; var params = parseURLParams(document.URL); var datastring = "nextStart="+start+"&a ...

Looking for assistance with changing the class of a span when a radio button is selected

I'm facing an issue with toggling the class of a <span> when a radio button is clicked. <html> <head></head> <style type="text/css"> .eHide { display:none; } </style> <script type="text/javas ...

Error: Unable to locate attribute 'indexOf' within null object in vuejs when using consecutive v-for directives

I've been struggling with this issue for hours. I'm using vuejs' v-for to render items in <select> element's <options>, but I keep getting a type error. I've tried changing the :key values, but it still won't rende ...

Evaluating the existence of a particular character sequence within a PDF document using iText 7 (version 8.0)

Currently conducting a basic benchmark to select a suitable C# PDF library for my project. The aim is to extract text from a PDF file and check for specific strings, such as in an invoice document with OCR capabilities. Using DYNAMIC PDF as an example mak ...

What is the method for checking the pathname condition?

Hello, I am attempting to create an if statement for the pathname, but I am having trouble getting it to work properly. if (pathname == "/") { category = 'home'; pagetype = 'homepage'; } If the pathname matches "/", the script ...

Deep Dive into TypeScript String Literal Types

Trying to find a solution for implementing TSDocs with a string literal type declaration in TypeScript. For instance: type InputType = /** Comment should also appear for num1 */ 'num1' | /** Would like the TSDoc to be visible for num2 as well ...

Using JQuery to delete data from a cookie

I have a delicious cookie that I want to savor before removing one element from it based on the widget ID. if (thisWidgetSettings.removable) { $('<a href="#" class="remove">CLOSE</a>').mousedown(function (e) { ...