Initiate server side subroutine once JavaScript timer completes

The timer for the online exam countdown is created using JavaScript. If the timer reaches 0:0:00, it alerts the user and proceeds to the next webpage as shown below:

function myTimer(startVal,interval,outputId, dataField){
...
var current = this.value;
    this.OutputCntrl.innerHTML = this.Hours(current) + ':' + this.Minutes(current) + ':' +  this.Seconds(current);
    this.currentTimeOut = setTimeout("Timer.go()", this.interval);
                     }
    else             {
    window.alert("Time is up! Exam will proceed to next module.");
    window.location = "Conf_English.aspx"
                                  }

If there is still time remaining, options are displayed on the web form as shown below:

When the Proceed Button is clicked, the examinee's questions and answers (temporarily stored in a datatable) will be saved in the database.

The issue here is that the countdown timer is controlled by client-side script while the insertion of data is handled in the server-side code. Creating a JavaScript function to directly insert data into the database is not recommended due to security concerns in ASP.Net. Can someone suggest a better method for achieving this? Thank you.

Answer №1

To utilize ASP.NET AJAX Page Methods for calling a server-side static method (or Shared in VB.NET), follow these steps:

Markup:

// Make use of the jQuery DOM ready function
$(document).ready(function() {
    // Set up click event handler for the proceed button
    $('.Proceed').click(function() {
        $.ajax({
            type: "POST",
            url: "PageName.aspx/SaveToDatabase",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(result) {
                // Perform necessary actions like navigating to the next page
            }
        });

        // Prevent the button from posting back to the server
        return false;
    });
});

<asp:Button id="ButtonProceed" runat="server" Text="Proceed" CssClass="Proceed" />

Note: Data can be passed to the ASP.NET AJAX Page Method using name/value pairs within data: "{}", or by constructing a JavaScript literal and then converting it to JSON with JSON.stringify().

Code-behind:

[WebMethod]
public static string SaveToDatabase()
{
    // Implement database saving logic here
}

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

My Angular project is experiencing issues with Socket.IO functionality

After successfully using a post method in my endpoint, I encountered an error when integrating it with socket io. The error pertained to a connection error and method not being found. Any help or source code provided would be greatly ap ...

The specified userID cannot be located within the array of objects

Trying to understand a tutorial on nodejs and expressjs that teaches how to implement user permissions on routes. However, I'm facing issues with a simple middle ware function designed to set the req.user as it keeps showing up as undefined. Below is ...

What is the best way to swap out the if else statement with a Ternary operator within a JavaScript function?

Is there a way to replace the if else statement in the function using a Ternary operator in JavaScript? private getProductName(productType: string): string { let productName = 'Product not found'; this.deal.packages.find(p => p.isSele ...

What techniques can I use to achieve a seamless transition using Javascript and CSS?

I'm striving for a seamless CSS transition. The concept of transition had me puzzled. Even though I utilized the setTimeout method in JavaScript to make my CSS functional, it lacks that SMOOTH feel! Check out my code below. function slideChange( ...

Sending auth0 token as a parameter in $http.get request in Angular

I am encountering difficulties when trying to attach the auth0 token to a http.get request for an API that requires the token. The token is generated upon user login and stored in the browser's local storage, which is functioning properly. The challen ...

What is the correct method to remove an item from local storage?

Using localStorage, I have stored multiple objects in an array. Is there a way to remove just one object from this array? If I use localstorage.removeItem(keysofthelocalstorage), I can delete the entire array, but I specifically want to remove only certai ...

I'm feeling a bit lost with this JSON example - specifically with JSON.parse, JSON.stringify, as well as localStorage.setItem

As a beginner in learning JSON, I find that W3schools does not provide clear explanations of what each line of code does. While I can interpret some parts, there are sections that still remain unclear to me. // Data storage process: 1. myObj = {name: "Jo ...

What is the trust rating for elements within the Default ASP.NET MVC project in Visual Studio 2015?

I am encountering issues with the required trust level while working with my web host on an ASP.NET MVC application developed in Visual Studio 2015. To troubleshoot, I set up a "dummy" application using the default template (without any custom code - just ...

Steps for successfully sending data to a MenuItem event handlerExplanation on how to

My issue arises when I attempt to render a Menu for each element in an array, as the click handlers for the items only receive the final element in the array rather than the specific element used for that particular render. The scenario involves having a ...

"Utilizing a Handlebars Helper to Evaluate if Two Values (v1 and v2) are Equal, and Displaying Content from

To make the actual call, I require something along these lines: <script id="messagesTemplate" type="text/x-handlebars-template"> {{#each messages.messages}} {{#each to}} {{#ifCond username messages.sessionUserName}} <h1> ...

ExtJS does not automatically trigger a resize after a new element is inserted

I am currently developing a plugin for Nexus OSS that utilizes the ExtJS framework internally. If you need to access the original Nexus website, you can find it here. My goal is to add an iframe above the Sonatype header panel. In order to achieve this, ...

What is the method for determining the dimensions of the rectangle that the camera can capture at a specific location?

In my latest project, I developed a small three.js application that showcases the movement of multiple circles from the bottom to the top of the canvas: let renderer, scene, light, circles, camera; initialize(); animate(); function initialize() { re ...

Ways to implement functional component in ReactJs

I am currently working with Reactjs and utilizing the Nextjs framework. In my project, I am attempting to retrieve data from a database using Nextjs. However, I am encountering an error that states "TypeError: Cannot read property 'id' of undefin ...

Using JavaScript on an iPhone to automatically launch Safari when clicking on a link from a non-default iOS

When "googlechrome://www.lego.com" is opened in mobile Safari, it switches to the Google Chrome iOS app to open the URL. This feature allows for scriptlets like the following one, which enables you to open the current page in the Google Chrome iOS app from ...

Unable to transmit form data to the controller

I am currently working with asp.net MVC5 and have encountered an issue with a page that displays a simple list of materials requiring a search function. To implement the search function, I utilized an Ajax form based on a tutorial I found. The method had ...

What is the most efficient method for assigning a JSON array?

let vehicles = [{"x":1,"y":2},{"y":3,"z":5}]; let temporary=[]; [...vehicles].map((item)=>{ temporary.push(item) }) temporary[0]["x"]=3 console.log(vehicles[0]["x"]) // output -> 3`enter code here` How can we prevent the values in the vehicles arra ...

Ways to retrieve the value from a button when it is clicked

I am facing an issue where I have buttons that are generated dynamically depending on the number of phone numbers available in the database. For example, if there are 3 phone numbers in the database, there will be three buttons displayed. The aim is that w ...

The functionality of binding a button command is not functioning as expected

After creating a new UserControl with a button inside, I attempted to bind the button command to a dependancy property of the UserControl in the following manner. <Grid> <Button Name="Button1" Command="{Binding Button1Command}" /> </Grid& ...

Apply a specific class to the input field when the name matches x

I have a website that loads a JavaScript file from a commercial service, so I am unable to customize this file. The output of this JavaScript file is a form with various input fields, all of which have the class name "wf-input". I now want to add a jQuery ...

Adjust the fixed navbar position in MaterializeCSS as you scroll

First of all, I apologize for my limited proficiency in English. I have a website with a company logo at the top and a navigation bar below it. My goal is to change the position of the navigation bar to the top when scrolling past the company logo. I att ...