0

How can I get data from the controller with ajax.

Method in my Controller

 public ActionResult StartPage()
    {
        var result = CommonService.GetCurrentDateTime();
        ViewBag.DateAndTimeFromDataBase = result ;
        return View();
    }

and my Ajax

$(document).ready(function() {
    setInterval('getServerDateTime()', 0, 1000);
});

function getServerDateTime() { 
    $.ajax({
        type: 'GET',
        cache: false,
        url: "/Login/StartPage",
        complete: function (req, textStatus) {
            var dateString = req.getResponseHeader('Date'); 
            if (dateString.indexOf('GMT') === -1) {
                dateString += ' GMT';
            }
            var date = new Date(dateString);
            $('#time-span').text(dateString);
        }
    });
};

Here I get the date time from the server. And I wanted to take the value of the time date from the controller. And display the difference therebetween. I am new to this. I can’t get the result of that in the controller.

<div>
    <span id="time-span" class="date-time"></span>
</div>
2

1 Answer 1

1

Considering that this is an AJAX request you are likely better off returning the data as a JSON payload. You can do that by modifying your code like so:

public JsonResult StartPage()
{
    var date = CommonService.GetCurrentDateTime();
    return Json(new { date });
}

this will return a payload to the client that looks something like this:

{
    "date": "<the value of GetCurrentDateTime() as a String>"
}

This can then be easily accessed via your JavaScript code like so:

$.ajax({
    type: 'GET',
    cache: false,
    url: "/Login/StartPage",
    complete: function (response) {
        var dateString = response.date;
        if ( !dateString ) {
            console.error('A001: date not returned from server');
        }

        if (dateString.indexOf('GMT') === -1) {
            dateString += ' GMT';
        }
        var date = new Date(dateString);
        $('#time-span').text(dateString);
    }
});

You should note that .NET has a funky way of serializing timestamps that may not work for JS, you may want to format the date serverside to something more understandable for JavaScript (see then options for DateTime.ToString())

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.