Executing Controller Actions within a JavaScript Timer

Presenting my latest timer:

         var eventDate = new Date(Date.parse(new Date) + 3600);

            function countdown() {

                var elapsed = Date.parse(eventDate) - Date.parse(new Date());

                var seconds = Math.floor((elapsed / 1000) % 60);
                var minutes = Math.floor((elapsed / 1000 / 60) % 60);

                minutes = (minutes < 10) ? "0" + minutes : minutes;
                seconds = (seconds < 10) ? "0" + seconds : seconds;

                return {
                    'minutes': minutes,
                    'seconds': seconds,
                    'total': elapsed
                }
            }

            function initializeClock() {
                var minutes = document.getElementById('minutes');
                var seconds = document.getElementById('seconds');

                var timeInterval = setInterval(function() {
                        minutes.innerHTML = countdown().minutes;
                        seconds.innerHTML = countdown().seconds;

                        if(minutes.equals(0) && seconds.equals(0))
                         {
                            timeInterval().stop();

                            $.ajax({
                                    url: "Finish/Test",
                                    type: 'POST',
                                    success: function (result) {
                                   if (result.success) {
                                  $('#htmlElement').html(result.htmlElement);
                                  }
                               }
                           }); 
                        }
                    },1000);
            }

            initializeClock();

    <h2>@ViewBag.Title</h2>
        <div id ='hmtlElement'>

.... continued in html format

     [HttpPost]
            public ActionResult Finish(ExamineTest examineTest)
            {
                var question = examineTest.Question.ToList();

                _questions.AddRange(question);
                _testService.SaveSolvedTest(examineTest);

                return Json(new { success = true, htmlElement = RedirectToAction("Preview", "Test") });

            }




   [HttpGet]
        public ActionResult Preview()
        {
            SolvedTest solvedTest = _testService.GetSolvedTest();

            SolvedTestModel solvedTestModel = EntitySolvedTestConverter.ToModel(solvedTest);
            return View("Finish", solvedTestModel);
        }

Answer №1

To implement this functionality, you can utilize ajax and json as suggested by @Bharat. Below is a code snippet demonstrating how to use an ajax method to call a controller.

function countdown(){
// logic for checking minutes and seconds
if(minute second equals 0)
    //var firstName = textbox where name is stored
    //var list = listbox where list is stored.
    var url = "Test/Finish?" + firstName + "&" + list;
    // url format: Test/Finish?John&ListofElements
    $.ajax({
            url: url,
            type: 'POST',
            success: function (result) {
                if(result.success){
                    $('#htmlElement').html(result.htmlElement);
                }
            }
        });

}

In the above code snippet, MVC route can be used as the url parameter.

The controller would resemble the following:

[HttpPost]
public ActionResult Finish(ExamineTest examineTest)
{
    var question = examineTest.Question.ToList();
    _questions.AddRange(question);
    _testService.SaveSolvedTest(examineTest);

    SolvedTest solvedTest = _testService.GetSolvedTest();
    SolvedTestModel solvedTestModel = EntitySolvedTestConverter.ToModel(solvedTest);

    return Json(new { success = true, htmlElement = View("Finish", solvedTestModel)});
}

Simply trigger this logic when the minutes and seconds reach 0.

<body>
<h2>@ViewBag.Title</h2>
<div id='htmlElement'>
<!-- ..... stuff .... -->
<!-- end of html form -->
</div>

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

Using external URLs with added tracking parameters in Ionic 2

I am looking to create a unique http link to an external URL, extracted from my JSON data, within the detail pages of my app. Currently, I have the inappbrowser plugin installed that functions with a static URL directing to apple.com. However, I would lik ...

Arranging images next to each other using CSS and HTML

I've been trying to arrange four images side by side, with two on the top row and two on the bottom. I want to ensure they stay consistent across all browser sizes except for mobile. Here is what I have attempted so far: #imageone{ position: absol ...

encountering an issue while working with Selenium on Google Colab

I'm attempting to perform web scraping with selenium in Google Colab and running into some errors https://i.sstatic.net/egDf7.png The webpage is prompting me to enable JavaScript and disable any ad blockers. I tried enabling JavaScript by adding the ...

Updating an array in Vue.js without the need to reload all the data

Recently delving into Vue.js and JavaScript, I'm seeking guidance on updating an array (on Add/Edit/Delete) without having to reload all the data. The goal is to load all data only when initially opening the page with Addresses. Take a look at my cod ...

Tips for bringing a particular tab into focus when a page initially loads

My webpage features custom links (tabs) that display content when clicked. By default, the first tab is selected and its content is shown, while the rest are set to display:none. Clicking on any other link will assign the 'selected' class to it, ...

Tips for showing JSON data within multiple <div> elements on an HTML page with AngularJS and ng-repeat

I am looking to display JSON values on my HTML page, each in a separate div based on the image URL value from the .json file. However, I am encountering difficulties in displaying these values in the divs. Can someone please guide me on how to iterate and ...

Using one payload.js file for all Nuxt static generated routes with identical data

I am facing a challenge with my NuxtJS site where I have only one page /pages/matrix/index.vue but numerous dynamic routes pointing to this page, all utilizing the same data set. During static build generation for deployment on Netlify, the size of the dis ...

Adding an OrganizationToken to a WCF Endpoint through code: A step-by-step guide

My current task involves connecting to a SOAP API provided by a vendor. I have a sample project from the vendor that is functional, but now I am trying to replace their endpoint defined in the app.config file with one created programmatically. The goal is ...

Struggling to pass command line arguments to index.ts with yarn?

My objective is to pass arguments through the command line using yarn start to index.ts. "scripts": { "start": "tsc-watch --onSuccess \"ts-node --pretty -r tsconfig-paths/register' src/index.ts\"", } When I attempt something like: yarn ...

Changing the fill color of an SVG pattern remains unchanged

I have been working with Vue.js to create SVGs with shape patterns as background. The patterns themselves are functioning correctly, but I am encountering an issue when attempting to dynamically change the color of the pattern filling by passing props. D ...

Warning: Unhandled Promise Rejection - Alert: Unhandled Promise Rejection Detected - Attention: Deprecation Notice

Encountering the following error message: (node:18420) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'name' of undefined at C:\Users\ohrid\Desktop\backend2\routes\categories.js:27:24 at Layer.han ...

In C#, how can the HTMLAgilityPack be utilized to extract a value from within a script tag?

I'm currently working with HTMLAgilityPack and I need to extract a value from a script tag. Here is the code: <div id="frmSeller" method="post" name="frmSeller"> <div class="clear"></div> <script type="text/javascript" language=" ...

The fixed navigation bar shows a flickering effect while scrolling at a slow pace

Currently facing a challenge with our sticky navigation. Noticing a flickering issue on the second navigation (sticky nav) when users scroll down slowly. The problem seems to be specific to Chrome and Edge, as it doesn't occur on Firefox, IE11, and S ...

Guide to building a JavaScript array and storing data from a separate array into the newly created array in JavaScript

Can you help me create a JavaScript array and save another array of data to be part of the newly created array in JavaScript? I attempted it using the code below. Code: var vvv=this.new_products.length-this.quote.lines.length; let mmm={}; if(v ...

The Art of Checkbox Design

Seeking help in replacing the default check mark on a checkbox with an image. Here is the code snippet I am currently using: <html> <head> <style> .bl { background:-webkit-gradient(linear, left top, left bottom, color-stop(0, #175899), c ...

Implementing a filter in React with data fetched from MongoDB

Hey there! I'm encountering an issue while using the code in Project.jsx and ProductList.jsx. Every time I run the code, it gives me this error message: Warning: Each child in a list should have a unique "key" prop. Check the render method of Product ...

A step-by-step guide on integrating HTML form input with an API object array

I'm looking to combine two code "snippets" but I'm not sure how to do it. One part of the code turns HTML form input into a JSON object. You can see the CodePen example here. What I want is when the "Add note" button is clicked, I want to grab ...

"Enhance the visual appeal of your Vue.js application by incorporating a stylish background image

Currently, I am utilizing Vue.js in a component where I need to set a background-image and wrap all content within it. My progress so far is outlined below: <script> export default { name: "AppHero", data(){ return{ image: { bac ...

Encounter a critical issue while making a JSON request using Kendo UI

I am facing an issue at my workplace where I need to integrate Angular.js with ASP.NET MVC. Currently, I am trying to build a simple application that features a Kendo UI grid on the front page. In my App.js file, I am fetching data from the Data Controller ...

Codeceptjs does not have the capability to scroll or swipe down without being linked to a specific element

I'm facing an issue with scrolling/swiping down in an Android application while using codeceptjs. The method I'm currently using only works on the visible element, but I need to scroll down to the bottom of the page or a specific element without ...