Challenges arising from AJAX, JavaScript, and ASP.Net MVC integration

Hello, everyone!

  • I am developing a website using Asp.Net MVC 2.
  • I have implemented a TimeController and TimeView along with a CountDownHelper to render time on the TimeView page.
  • Additionally, I have JavaScript that updates the current time which is used in the CountDownHelper.

I need to make an AJAX call from this JavaScript to fetch the current server time. Can someone guide me on how to achieve this? I need to get it done within the next few hours!

Below you can find the JavaScript code as well as my attempt to call AJAX. I have tried various ways to write GetServerTime.html but none of them seem to work. (((


//countDown.js  
function calcage(secs, num1, num2) 
{
    s = ((Math.floor(secs / num1)) % num2).toString();
    if (LeadingZero && s.length < 2)
        s = "0" + s;
    return "<b>" + s + "</b>";
}

function CountBack(secs) 
{
    if (secs < 0) 
    {
        location.reload(true);
        document.getElementById("cntdwn").innerHTML = FinishMessage;
        return;
    }

    //difference between received time and current client time
    diff = new Date(new Date() - clientTime);
    targetD = new Date(TargetDate);
    serverD = new Date(serverDate);
    currentServerDate = new Date(serverD.getTime() + diff.getTime());

    leftD = new Date(targetD.getTime() - currentServerDate.getTime());

    secs = leftD.getTime() / 1000;

    DisplayStr = DisplayFormat.replace(/%%D%%/g, calcage(secs, 86400, 100000));
    DisplayStr = DisplayStr.replace(/%%H%%/g, calcage(secs, 3600, 24));
    DisplayStr = DisplayStr.replace(/%%M%%/g, calcage(secs, 60, 60));
    DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs, 1, 60));

    document.getElementById("cntdwn").innerHTML = DisplayStr;
    if (CountActive)
        setTimeout("CountBack(" + (secs + CountStepper) + ")", SetTimeOutPeriod);
}

function putspan(backcolor, forecolor) 
{
    document.write("<span id='cntdwn' style='background-color:" + backcolor +
                "; color:" + forecolor + "'></span>");
}

if (typeof (BackColor) == "undefined")
    BackColor = "white";
if (typeof (ForeColor) == "undefined")
    ForeColor = "black";
if (typeof (TargetDate) == "undefined")
    TargetDate = "12/31/2020 5:00 AM";
if (typeof (serverDate) == "undefined")
    serverDate = "12/31/2020 5:00 AM";
if (typeof (DisplayFormat) == "undefined")
    DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
if (typeof (CountActive) == "undefined")
    CountActive = true;
if (typeof (FinishMessage) == "undefined")
    FinishMessage = "";
if (typeof (CountStepper) != "number")
    CountStepper = -1;
if (typeof (LeadingZero) == "undefined")
    LeadingZero = true;


CountStepper = Math.ceil(CountStepper);
if (CountStepper == 0)
    CountActive = false;
var SetTimeOutPeriod = (Math.abs(CountStepper) - 1) * 1000 + 990;
putspan(BackColor, ForeColor);
var dthen = new Date(TargetDate);
var dtServ = new Date(serverDate);
var dnow = new Date();
if (CountStepper > 0)
    ddiff = new Date(dnow - dthen);
else
    ddiff = new Date(dthen - dtServ);

gsecs = Math.floor(ddiff.valueOf() / 1000);
CountBack(gsecs);

alert("Start");
alert(serverDate);

//AJAX CALL ???? 
//How to call async JavaScript?
//Which must be GetServerTime.html

$.get('Views/GetServerTime.html', function(data) {
    serverDate = data;
    clientTime = new Date();    
});

alert(serverDate);

Answer №1

Typically, direct access to views is not recommended, as the view is often stored in an .ASPX file.

Therefore,

$.get('Views/GetServerTime.html',...

Can be changed to

$.get('/GetServerTime/',...

This pertains to the Views/GetServerTime/Index.aspx view and the getserverTimeController.cs controller with a default Action of Index.

It seems there may be more issues at play here?

Edit

Additionally, it might be better to utilize JSON for this task. You can employ the System.Web.Mvc.JsonResult to automatically send your result as JSON, which jQuery can then process and convert into javascript objects.

        $.get('/GetServerTime/', 
                        function (data)
                        {
                                if (data.HasError == false)
                                {
                                    $("#resultDiv").html(data.ServerTime);
                                }
                        }, "json");

Your MVC Action could resemble the following...

public JsonResult Index(string id)
{
    JsonResult res = new JsonResult();          
    res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

    res.Data = new { ServerTime = DateTime.Now(), HasError = false };

    return res;
}

The code above is a rough example since I don't have a compiler available.

Answer №2

First and foremost, I have reservations about using "GetServerTime.html" to obtain the current time. Are you certain that is the correct page name you want to use? It may require specific Routing configuration to handle that URL pattern, as mentioned by Kervin below.

Additionally, the "function(data)" method within an ajax call serves as the callback function that executes when the ajax request completes.

When creating a page to return server date/time information, it's important to determine the format in which it will be retrieved: XML or JSON. Subsequently, the controller should be set up accordingly.

public class DateController : Controller {
    public ActionResult CurrentDate()
    {
       var returnJson = new 
          {
              currentDate = DateTime.Now.ToString()
          }

       return Json(returnJson, JsonRequestBehavior.AllowGet);
    }
}

The .get function to retrieve this data would then appear as follows:

$.get('/Date' function(data) {
    theDate = data.currentDate;
});

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

Exploring the possibilities of repetition in puppeteer

I'm looking to extract certain elements and receive updates every 15 minutes, however I'm unsure how to create a loop for this situation: const totalCases = await page.$eval('.maincounter-number span', element => element.innerHTML); ...

Tips for implementing a Jquery .keyup function on elements that are dynamically loaded via Ajax requests

On a specific page, I have elements that are loaded through ajax after user interaction. The issue I'm facing is that Jquery doesn't seem to recognize the newly loaded elements in order to work with the function refresh_current_items. This is m ...

What is the best way to loop through a group of WebElements, and only log the results that contain a specific substring?

In my test case, I'm utilizing Mocha to handle the scenario. The test appears to be passing successfully, however, no logs are being printed... it('Is 'Mooooooo!!!! I2MaC0W' a Substring in Results?', function() { this.timeout(50 ...

Troubleshooting: Issues with Contenteditable div functionality in Angular 2

When HTML text stored on the server is bound to a contenteditable div, it is not processed or rendered as expected. Instead, it is displayed in its raw form. For example, the following HTML text from the server is shown as plain text rather than rendered ...

Implement a "please wait" JavaScript modal on the ASPX DetailView insert button

Trying to utilize the insert functionality of an aspx DetailsView, I am looking to display a javascript modal popup window while a new record is being processed and added to the database. Despite my efforts to trigger the popup using DetailsView_ItemComman ...

Highlighted keyword: Unusual mouse movements

I am utilizing the Summernote plugin from Summernote to craft an aesthetically pleasing textarea, and adding the Mark.js plugin from Mark.js to highlight a specified keyword (such as foo) within that textarea. This is the HTML code I have: <div id="te ...

Using AngularJS to extract values from deeply nested JSON structures

I'm currently navigating through a nested JSON object and I'm facing challenges in accessing the sub items within it. Below is a snippet of the JSON file I'm working with. It has successfully passed the JSONLint test, so it should be in pro ...

Selecting elements with jQuery allows you to manipulate the

Encountering issues with jQuery selectors. This is how my HTML looks: <form method="" action=""> <p id="question_1"> <h1 id="question">1. A Question</h1> <div id="choices"> ...

Resize all types of content using a "zooming" container

Is there a way to create a magnifying effect without duplicating content and still keep the underlying elements clickable? Check out this jsfiddle example I am looking for a solution to scale the underlying div within the magnifying zoom without cloning ...

After repeated attempts to initialize and destroy, Froala encounters issues when loading a textarea via Ajax

Whenever an EDIT button is clicked to update some Blog Data, it triggers an Ajax call that brings up a textarea for Froala and initiates the initialization process. This sequence works smoothly initially, but after a few cycles of edit/submit (1, 2, or 3 o ...

Troubleshooting Problem with Custom Class Buttons in Angular Material

Recently, I've been working on creating a custom class for angular material buttons. However, I encountered an issue where the button fades out or turns white when I click on it and then navigate away from the browser window (minimize it or activate a ...

Mastering the Integration of React in Node.js

I've been eager to experiment with Server Side Rendering in React, however, my code isn't functioning as expected. It seems like I might be overlooking something crucial. Being new to React, it's challenging to pinpoint the issue. https:// ...

Unable to identify modified identifier

After changing the id of a button, I am unable to detect the new id using .on("click"). Although console.log() does acknowledge the change, the on() function fails to detect it. Here is the HTML code: <form id="formName" action="" method="post"> ...

What is the best way to extract the href value or URL from a JavaScript function and then utilize it for redirection

I need to redirect to a specific hostname from the request by adding "https://" in front of it. <a target="_blank" href="javascript:createDynamicPubUrl();" > Here is the function that generates the URL by combining the hostname with the protocol (h ...

Achieve the buoyancy effect in threejs to make an object float on water

I successfully created a water effect using THREE.WATER and incorporated a few gltf objects into the scene. Currently, I am aiming to make these added objects float on the water just like a boat would. Below is the code snippet: var scene, camera, rend ...

"Enhancing User Authentication with Firebase Email Verification in React Native

Does Firebase have a feature that allows me to verify if an email confirmation has already been sent to a user? I am able to check validation, but I need to determine whether the verification email has already been sent in order to decide if it needs to be ...

Two DataTables on a Single Page - Odd Initialization in the Second One

My page contains two dataTable elements and I've created a method as shown below: function ToDataTable() { $(".dataTable").css("width", "100%"); $(".dataTable").each(function () { var $that = $(this); /* Start of custom ...

JavaScript-powered Chrome Extension designed for modifying CSS styling

Like many others, I've embarked on creating a Chrome Extension to modify the CSS of a specific webpage. Despite reading through various threads, my approach is a bit more complex than what has been discussed. The page I want to style features a sele ...

Material-UI's style is taking precedence over other styles that have been defined

Introduction Last week, I posted a similar query which touched on the same issue. However, as the solution seems to be different this time around, I am revisiting it in a new thread. Check out the updated version of the CodeSanbox Example that reflects t ...

The attempt to call an Ajax POST was unsuccessful

I am currently working on setting up a web api that utilizes mongoDB. Here is my model public class Entity { [BsonId] public int Id { get; set; } public string Name { get; set; } public string Gender { get; set; } ...