Calling JavaScript functions from ASP.NET code-behind

A question has been updated.

Reference:

The following HTML link "Add Regular" is functioning correctly. When clicked, it displays the notification showing that the related .js and .css files are working.

HTML Link

<a href="#" id="add-regular">Add regular notification</a>

JavaScript

<script type="text/javascript">

    $('#add-regular').click(function () {

        var unique_id = $.gritter.add({
            // (string | mandatory) the heading of the notification
            title: 'This is a regular notice!',
            // (string | mandatory) the text inside the notification
            text: 'This will fade out after a certain amount of time.',
            // (string | optional) the image to display on the left
            image: '/content/gritter/images/success.png',
            // (bool | optional) if you want it to fade out on its own or just sit there
            sticky: false,
            // (int | optional) the time you want it to be alive for before fading out
            time: '',
            class_name: 'gritter-info'
        });
        return false;
    });

</script>

I have converted the above JavaScript into a function with parameters, and I am attempting to call it from the code-behind (ASP.NET / Web Forms) to show the notification, but it is not functioning as intended!

Codebehind

Page.ClientScript.RegisterStartupScript(Me.GetType(), "return", "stickyalert('Property Upload', 'property data uploaded successfully', 0, 'success');", True)

JavaScript

<script type="text/javascript">
    function stickyalert(title, text, sticky, success) {
        var unique_id = $.gritter.add({
            // (string | mandatory) the heading of the notification
            title: title,
            // (string | mandatory) the text inside the notification
            text: text,
            // (string | optional) the image to display on the left
            image: '/content/gritter/images/success.png',
            // (bool | optional) if you want it to fade out on its own or just sit there
            sticky: sticky,
            // (int | optional) the time you want it to be alive for before fading out
            time: '5000',
            // (string | optional) the class name you want to apply to that specific message
            class_name: 'gritter-info'
        });
        return false;
    }
</script>

Answer №1

To ensure smooth functionality, it is recommended to encapsulate your code within a separate function. Besides triggering this function from the click event, you can create a script in your webpage that automatically executes the function using the jquery api upon page load.

<script type="text/javascript">

    function myFunc() {
        $.gritter.add({
            // (string | mandatory) the heading of the notification
            title: 'This is a regular notice!',
            // (string | mandatory) the text inside the notification
            text: 'This will fade out after a certain amount of time.',
            // (string | optional) the image to display on the left
            image: '/content/gritter/images/success.png',
            // (bool | optional) if you want it to fade out on its own or just sit there
            sticky: false,
            // (int | optional) the time you want it to be alive for before fading out
            time: '',
            class_name: 'gritter-info'
        });
    }

    //Call it when the page loads
    $(document).ready(function() {
        myFunc();
    });

    //Call it on the click event
    $('#add-regular').click(function () {
        myFunc();
        return false;
    });
</script>

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 the "Redirect after POST" pattern in ASP.NET [Revised]

I'm new to implementing Redirect After Post in ASP.NET and need guidance. Due to the time-consuming nature of my business objects, I'm unsure about the order and syntax to use. Can someone provide some advice? For instance: User makes a POST ...

Hover without proper anchoring / move to section on click without anchor tag

I need assistance with a jump tab feature I am implementing on my portfolio website. I have encountered a couple of issues that I could use some help with. https://i.sstatic.net/8hwgL.png <ul class="section"> <li><span>home& ...

Tips on displaying hyperlinks within a text area in an Angular application

In my Angular application, I am facing an issue with displaying hyperlinks within a text area box for dynamic content. The hyperlinks are not recognized and therefore cannot be clicked. Can someone please advise on how to properly display hyperlinks with ...

The bond between two tables in ASP.NET

I'm currently learning about Asp.Net and Entity Framework, and I've encountered a minor issue. I believe you can assist me with this since it seems straightforward, especially coming from a PHP background XD Here are my 2 models: public class ...

What is the best way to ensure that JavaScript is loaded in a specific sequential order?

I'm having trouble ensuring that JS files load in the correct sequence, despite my efforts to research async and defer on various platforms. This is the structure of my code: <script src="lang.js"></script> <!--loading either ...

Adjust the appearance using Timeout within a React component

I am facing a challenge with updating the style in React - specifically, the opacity of a Div element is not updating despite successfully updating the opacity in a timeout event. import React from 'react'; function PortItem(props){ let style ...

javascript utilizing the canvas feature to resize and add graphics to an image

Is it possible to leverage Canvas for drawing over images that have been downloaded by users, all while adjusting the scale? For instance: User uploads an image Starts drawing on the image Zooms out and continues adding more drawings All modifications ...

Transfer the text entered in one textbox to another textbox located within a dynamic table

Is there a way to automatically copy the input from a textbox into another textbox within a dynamic table using JavaScript? I need the value entered in the first textbox to be replicated in the textbox inside the dynamic table. Any guidance or assistance o ...

Having trouble choosing multiple options from autocomplete drop-down with Selenium web-driver in Python

I am currently in the process of automating a webpage built with Angular that features an auto-complete dropdown with numerous elements. My goal is to click on each individual element and verify if it populates all the fields below accordingly. Below is th ...

Button missing post ajax loading

I've encountered a problem with my code that populates a table and contains buttons, which trigger an AJAX load. The content is loaded into a DIV with the ID 'DIV1', but when I try to access the buttons in that DIV1 by clicking on them, they ...

What is the optimal method for storing a binary tree on a server?

I am looking to efficiently store a binary tree on my server for use in the IOS and Android applications of all my users. What is the most optimal method (in terms of speed) to accomplish this task? Edit: It is necessary for all my users to be able to up ...

Are there any outcomes from using Angular in conjunction with httpService for POST and DELETE requests?

I've created an Angular service to handle all the HTTP requests necessary for my controllers to communicate with my API. export interface IDummyEntityApiService { getAllDummies() : ng.IPromise<Array<Entities.IDummy>>; } class DummyEn ...

What is the Key Ingredient I'm Overlooking in Bringing JSON Data into my Controller via AJAX?

I am working on a function that involves sending data via AJAX and I need to access the result of JSON.stringify in my controller. Below is the code snippet: // fbi: Files batch info $.ajax({ xhr: function() { var xhr = new wi ...

Adjusting the width of a DataBound column in an ASP.NET GridView

One of the challenges I'm facing is trying to set a maximum width for my UserInfo column in a GridView that utilizes BoundField for its columns. No matter how many different approaches I've attempted, none seem to have worked so far. Below is th ...

Flickering effects in THREE.js using Frame Buffer Objects

I've encountered a strange flickering issue while working on a THREE.js scene that involves using a Frame Buffer Object. The flickering disappears when I comment out the line: mesh.material.uniforms.fboData.value = renderTargetA.texture. THREE.FBO ...

Errors encountered in the ajax request, specifically 404 and 401 errors

Using jQuery's ajax method, I am submitting an ajax request in the following manner: $.ajax({ type: "PUT", url: specifiedURL, contentType: "application/json", data: JSON.stringify(data), dataType: "json" ...

Is it necessary to use JavaScript if jQuery has already been declared?

Is it possible to utilize javascript alongside jquery if jQuery has already been declared in the head section of the webpage? Personally, I believe that javascript is more suitable for specific tasks, while jQuery may be better suited for others. Currently ...

What is the best way to isolate the elements from the specified dictionary that contain valid data?

I need to extract only the data for Flipkart from this array and create a new array containing just that information. json = [ { "amazon": [] }, { "flipkart": { "product_store": "Flipkart", ...

Creating Dynamic Popover Content with Bootstrap 5 Using an Asynchronous Function

Trying to create a bootstrap 5 popover with dynamic content by using an asynchronous function has been quite a challenge. Here is how I am setting up my popover: document.querySelectorAll('[data-bs-toggle="popover"]').forEach(function ( ...

The API delete request results in a 404 error code being returned

I've been scratching my head for the past few hours trying to figure out why my DELETE request is failing. Instead of success, I keep getting a 404 not found response. Strangely, my POST, PUT, and GET requests are all working perfectly fine. For maki ...