Home > Enterprise >  Javascript processes 200 response before server sends the 200
Javascript processes 200 response before server sends the 200

Time:09-27

I have a timing problem with an ASP.NET core 5 system I'm working on. My page shows a DataTable with id='outsideDataTable', and when an item is selected a modal bootstrap dialog is shown. The submit button invokes method submitModal() which does this:

$.ajax({
    type: 'POST',
    url: '/api/Submit',
    dataType: 'json',
    statusCode: {
        200: SubmitDone()
    },
    error: 'SubmitError',
    data: $('#ModalForm').serialize()
});

The /api/Submit function calls the server's Submit function which does an update to the database. None of the C# code uses async coding. The database interface is NPoco. At the end of the update the function calls Ok() which I believe returns the status 200 to the ajax call.

    [HttpPost("api/[action]")]
    public IActionResult Submit(
        int recordId,
        ... other formdata ...)
    {
        if (recordId == 0)
        {
            var sr = new Record() { ... fill with form data ... };                    
            db.Insert(sr);
        }
        else
        {
            var sr = db.Single("select * from Records where recordId=@0", recordId);
            if (sr == null)
                return BadRequest($"Couldn't find record with ID={recordId}");
            ... update sr with form data ...
            db.Update(sr);
        }
        return Ok();
    }

The OK() function returns status of 200 back to the client, which should now execute the js SubmitDone() function.

function SubmitDone() {
    $('#ModalDlg').modal('hide');
    $('#outsideDataTable').DataTable().draw();
}

The problem is that when the outsideDataTable is redrawn from within the SubmitDone function, it will retrieve the data, which does not yet include the changes put into the database by the submit action routine. Why is that? In my opinion the database should have done its thing by the time the status 200 is returned to the ajax call, ergo when the redraw happens the database should have the new data.

As a matter of fact, in fiddler I see that the list load from the redraw happens before the ajax to the submit function.

I have not isolated this into working code I can share, but can do so if needed - unless someone knows what I'm doing wrong.

CodePudding user response:

When you assign the SubmitDone function to the statusCode.200 callback you shouldn't use parentheses because this is making the function execute immediately. Instead, it should be like this:

$.ajax({
    type: 'POST',
    url: '/api/Submit',
    dataType: 'json',
    statusCode: {
        200: SubmitDone
    },
    error: 'SubmitError',
    data: $('#ModalForm').serialize()
});
  • Related