I'm trying to do an AJAX (JQuery) call and the URL will periodically send responses back to the browser but I just want to know how to capture the responses.
html js:
$.ajax({
type: 'GET',
datatype: 'json',
url: Progess.ashx,
success: function (data) {
if (data.Working) {
$('#txt_test').val('Working on: ' + data.Current + '/' + data.Final);
}
else {
if (data.Success) {
alert('finished');
}
}
},
error: function () { alert('unable to call Progress.ashx and return valid JSON results'); }
});
My ASP.NET Handler:
public void ProcessRequest (HttpContext context) {
for (int i = 0; i < 20; i++)
{
ProgressRespond(true, "", context, 0, 19, i, true);
System.Threading.Thread.Sleep(1000);
}
ProgressRespond(true, "", context, 0, 19, 19, false);
}
public void ProgressRespond(bool success, string message, HttpContext context, int initial, int final, int current, bool working, object obj = null)
{
ProgressClass response = new ProgressClass();
response.Success = success;
response.Message = message;
response.Initial = initial;
response.Final = final;
response.Current = current;
response.Working = working;
response.Data = obj;
string jsonString = JsonConvert.SerializeObject(response, new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Local });
context.Response.ContentType = "application/json";
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
context.Response.Clear();
context.Response.Write(jsonString);
if (success)
context.Response.End();
else
context.Response.Flush();
}
private class ProgressClass
{
public int Initial { set; get; }
public int Final { set; get; }
public int Current { set; get; }
public bool Working { set; get; }
public bool Success { set; get; }
public string Message { set; get; }
public object Data { set; get; }
}
I'm hoping somewhere in the AJAX function I can capture each of the responses and utilize the data returned before the final response. The 'success' callback only seem to fire when it receives the Response.End() from the handler but nothing in between.
I'm basically trying to implement Comet using JQuery AJAX. Is that possible?
Thanks.