Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript, how to start a server-side process and monitor its output until completion?

In my web application I'd like to be able to start a process with certain parameters on the web server, and continuously display output from the process in a text area until it completes. How can I accomplish this with Javascript? I'm using jQuery along with ASP.NET MVC 3.

like image 840
aknuds1 Avatar asked Feb 24 '23 03:02

aknuds1


1 Answers

You can do this with 2 action methods and a javascript timer

[HttpPost]
public JsonResult StartProcess()
{
    StartTheMachine();
    return new JsonResult() { Data = "Started" };
}

[HttpGet]
public JsonResult GetProcessUpdate()
{
    return new JsonResult() 
    {
        Data = GetUpdate(), 
        JsonRequestBehavior = JsonRequestBehavior.AllowGet 
    };
}

and in your view something like this:

$.post("<%=Url.Action("StartProcess") %>", function(data) {
    // do something with data "Started" and start timer
    setTimeout(GetUpdate, 5000);
});

function GetUpdate()
{
    $.get("<%=Url.Action("GetUpdate") %>", function(data) {
        if (data.Complete) // or some way to tell it has finished
        {
            // do something with other data returned
        }
        else
        {
            // call again if not finished
            setTimeout(GetUpdate, 5000);
        }
    });
}
like image 191
hunter Avatar answered Feb 25 '23 18:02

hunter