mercredi 4 octobre 2017

Simple heartbeat implementation not working in MVC

I was recently suggested to try heartbeats to solve an issue in my project. Because I am new to javascript, I was trying to implement the second answer to this question before moving on, but even this does not seem to work, and I can't understand why. These are the three files involved:

HTML (Heart.cshtml)

@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Heart</title>
    <script type="text/javascript" src="~/Scripts/heartBeat.js"></script>
</head>

<body>
    <script type="text/javascript">
        LaunchHeartBeat(@Url.Action("KeepSessionAlive", "Auxiliary"));
    </script>
</body>
</html>

Javascript (heartBeat.js)

var keepSessionAliveUrl = null;
var isSuccess = false;

function LaunchHeartBeat(actionUrl) {
    keepSessionAliveUrl = actionUrl;
    checkToKeepSessionAlive();
}

function CheckToKeepSessionAlive() {
    setTimeout("KeepSessionAlive()", 2000);
}

function KeepSessionAlive() {
    $.ajax({
        type: "POST",
        url: keepSessionAliveUrl,
        success: function () { isSuccess = true; }
    });
    CheckToKeepSessionAlive();
}

Controller (AuxiliaryController.cs)

[HttpPost]
public JsonResult KeepSessionAlive()
{
    System.Diagnostics.Debug.WriteLine("This is a heart beat");
    return new JsonResult { Data = "success" };
}

Sorry for the (I believe) simple question. I would have asked in a comment, but I don't have enough reputation yet, so I did not know how else to do it.

Aucun commentaire:

Enregistrer un commentaire