eirishainjel
eirishainjel

Reputation: 600

Call server side sub after javascript timer is done

The countdown timer in the online exam is implemented using JavaScript. If the countdown reaches 0:0:00, it alerts the user and it proceeds to the next web page (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"
                                  }

And if there are still some time left, options are shown in the web form (shown below): enter image description here

When Proceed Button is click, the questions and answers of the examinee (temporarily stored in a datatable) will be stored in the database.

The problem here is the countdown timer is being run by a client-side script and the insertion of data is coded in the server-side. I can't also make a javascript function that will insert the data because base on what I read on some articles, it is not advisable to access the database through client-side scripts which I see is right base on the concept of ASP.Net. Can someone suggest a good method to do this? Thanks.

Upvotes: 2

Views: 1240

Answers (1)

Karl Anderson
Karl Anderson

Reputation: 34846

Use ASP.NET AJAX Page Methods to call a static (Shared in VB.NET) method on the web server, like this:

Markup:

// jQuery DOM ready function
$(document).ready(function() {
    // Wire up click event handler for proceed button
    $('.Proceed').click(function() {
        $.ajax({
            type: "POST",
            url: "PageName.aspx/SaveToDatabase",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(result) {
                // Navigate to next page or whatever needs to happen here
            }
        });

        // Stop button from trying to post back to server
        return false;
    });
});

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

Note: You can pass data to the ASP.NET AJAX Page Method either through name/value pairs inside of data: "{}", or you can build a JavaScript literal and then use JSON.stringify() to convert the literal into JSON.

Code-behind:

[WebMethod]
public static string SaveToDatabase()
{
    // Save to database logic here
}

Upvotes: 1

Related Questions