Tips for invoking a Server-Side Function from within a JavaScript Function

When my button is clicked, it triggers the following code:

protected void Button6_Click(object sender, EventArgs e)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), 
                    "myScript", "AnotherFunction();", true);
}

In addition, I have a server-side function called Delete():

public void Delete()
{
  //Delete Code
}

After the button click, control is passed to this javascript function:

To achieve my goal of calling the Delete() function on the SERVER side, here's what I've attempted so far in my javascript function:

function (isConfirm) 
{
   if (isConfirm)
   {
       //CALL DELETE FUNCTION HERE Delete();
       swal("Deleted!", "Your imaginary file has been deleted.", "success");
   }
   else
   {
       swal("Cancelled", "Your imaginary file is safe :)", "error");
   }
 });

I'm seeking advice on how to successfully call that server-side function. Any suggestions?

Answer №1

To accomplish this task, there are two main approaches you can take: using Ajax/Web Service or triggering a button click in JavaScript. The simplest method is to trigger the button click event. Here is a sample code snippet:

ASPX:

<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" ClientIDMode="Static" style="display:none;"/>

C#:

protected void Button1_Click(object sender, EventArgs e)
{
      Delete();
}

JavaScript:

document.getElementById('Button1').click();

// jQuery
$("#Button1").click();

If you prefer not to reload the page, then consider using Ajax. For this, create a webpage (e.g., data.aspx) and add the following C# code to the backend class of data.aspx:

Ajax. C#

[WebMethod]
public static int DoSomething(int Id)
{
       return 1;
}

You can now call this function from JavaScript:

$.ajax({
            url: APP_PAGE_RELATIVE_PATH + "Data.aspx/DoSomething",
            data: "{'Id':5}",
            type: "POST",
            cache: false,
            headers: { "cache-control": "no-cache" },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {

                // Perform desired action

            },
            error: function (xhr, status, error) {
                //DebugAlert("Error: " + xhr.responseText);
            }
        });

Answer №2

To enhance the functionality of the page, I recommend adding a ScriptManager and enabling PageMethods.

Here's how you can implement it:

In your ASPX file:

<asp:ScriptManager runat="server" EnablePageMethods="true" />

In your JavaScript code:

<script>
     PageMethods.Update();        
</script>

And in your ASPX.cs file:

[System.Web.Services.WebMethod]
public static void Update()
{
     //Update Code
}

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

Tips for implementing gsap animations in React

I need to incorporate a hover effect into my react project but I don't have the time to learn gsap and threejs. After implementing it, nothing seems to be happening. What should be my next step? Here is the code in my menu.js: import {hoverEffect ...

When the confirm button on a Bootstrap modal is clicked, generate and save a file using jQuery or Knockout.js

My issue involves a bootstrap modal (bootbox) where, upon confirming an action, I need to generate a file with certain numbers and have it downloaded as a text file. I already checked out Create a file in memory for user to download, not through server, b ...

Potential Security Vulnerability in DNN 8.0.3.5 due to Outdated jQuery 1.9.1

Our security audit is currently failing due to a specific issue related to jQuery. You can find more information about this at this link. Upon inspecting the folder structure of our installation, it appears that jQuery version 1.9.1 is pre-installed in th ...

The function necessitates achieving the desired outcome

My Code: import dataclasses from dataclasses import dataclass from dataclasses import dataclass, asdict, field import pandas as pd @dataclass class BusinessObject: Job_Trade: str = None def __repr__(self): attrs = [f'{attr}={getattr( ...

Steps for implementing virtual scroll to render items in a CDK table

Utilizing CDK VIRTUAL SCROLL within a table to load data from an API service, I encountered an issue where removing all columns and then requesting them back only brings the columns back but not their respective items. Is there a solution for this proble ...

An error occurred in Angular2 when attempting to resolve a Promise: The type 'Promise<Hero[]>' is not compatible with the type 'Hero[]'

Recently updated. Currently, I am working through an Angular2 tutorial which can be found at this link Highlighted below is the code snippet for calling the HeroService from heroes.component.ts, Heroes.component.ts import { Component , OnInit } from ...

You cannot define headers once they have been sent to the client. If you encounter a NextJS redirect issue, consider using res

I encountered an error when redirecting to a link from NextJS -> _app.js -> getInitialProps. I am trying to cache the last user language in cookies and redirect to it when the page is reloaded. It's working and the user is redirected, but I&apos ...

What is the root cause behind the recurring appearance of this line in Angular/D3.js?

I recently came across an excellent tutorial on integrating the D3.js library with AngularJS by following this link: . The guide provided has been extremely helpful in getting me started (big thanks to Brian!) However, I'm eager to delve deeper into ...

Implementing ordering and limiting of elements in NestJS TypeORM relations

I am new to typeorm and relationships. I am currently facing some challenges and feeling a bit confused. I have a question regarding sorting relations in typeorm by id or createdDate without explicitly mapping them and limiting the number of elements. Here ...

How can I access a PHP variable by passing it through JavaScript?

I've been trying to pass my variable through an AJAX request in JavaScript. How can I properly assign the value of this variable to a new one in the tabs.php file? JavaScript code snippet: var build = { m_count : document.getElementById('count& ...

Using AngularJs, eliminate parameters prior to hashing

I am facing an issue that may appear to be a duplicate, but I have already tried the following solutions without success: $location.search('lang', null) $location.url($location.path()); $location.$$search = {}; The Issue: Upon initial redirec ...

Can you guide me on utilizing filter in an Apps Script array to retrieve solely the row containing a particular user ID within the cell?

I am using an Apps Script that retrieves data from four different columns in a spreadsheet. However, it currently fetches all the rows instead of just the row that matches the randomly generated 8-digit user ID. function doGet(req) { var doc = Spreadshe ...

Showing only the initial result retrieved by the GridView

Although I am able to retrieve all the necessary records from my database, I am facing a problem where only one record is being displayed in my GridView. I have spent the past few days trying to troubleshoot this issue, but unfortunately, I have exhausted ...

Is the username you want available?

I am facing a challenge in my registration form validation process where I need to verify the username input using javascript and flask in python, but the implementation is unclear to me. The requirement is to utilize $.get in the javascript segment along ...

Navigating through radio button groups in AngularJS

I am currently developing a survey application using AngularJS. My goal is to display tasks one at a time, each containing one or more questions with radio button answers. I am looking to store the question and answer pairs in a new array. While I have ma ...

Attention: React is unable to identify the X attribute on a DOM component

Encountering an error while attempting to pass props in a basic manner. interface Props extends Omit<React.HTMLAttributes<HTMLElement>, 'color'>, ChakraProps { handleMoveAll: () => void } export const MyWrapper: FC<Props> ...

EJS forEach method not displaying output

Trying to work with this .ejs file that's supposed to loop through an object and retrieve data from an API. However, after fetching the data, it appears that nothing is being displayed on the screen. I've checked the API results in the console l ...

Attempting to conceal the select input and footer components of the Calendar component within a React application

I am currently working on customizing a DatePicker component in Antd and my goal is to display only the calendar body. Initially, I attempted to use styled components to specifically target the header and footer of the calendar and apply display: none; st ...

Creating artistic masterpieces on a digital canvas with the use of touch

After conducting some research, I am struggling to find a solution that allows touch screen users to draw on the canvas tag using raw JavaScript. Despite my best efforts, I keep hitting a dead end and my canvas remains unresponsive. The canvas is located ...

Struggling with a Python CGI script that refuses to open a file sent to it via AJAX

After encountering multiple issues while attempting to upload a file to a server using HTML and Javascript in my previous post, I decided to take a different approach. I now have an HTML form and a Python script located in the cgi directory of my webserver ...