Search code examples
javascriptjqueryajaxasp.net5

Jquery Ajax fires error callback on first load of application


I have an odd one here. I am doing an ajax call back to my action method, its quite a simple call and I am always passing back a JSON object in the action method. However, when I have built my application and run it locally, the first time the ajax request is made, the error callback is executed. This callback is being fired before the request has returned anything, I can put a breakpoint in action method, the breakpoint is hit, I leave it as paused but error is fired. On the next ajax request, everything works fine, breakpoint is hit, nothing happens until I continue and then success is returned.

The error details when first selected are

xhr = Object {readyState: 0, responseJSON: undefined, status: 0, statusText: "error"}, ajaxOptions = "error", thrownerror = ""

My ajax call is as follows

jquery.ajax({
    url: "ReportSetting/SaveSetting",
    data: {
        reportSettings: this.ReportSettings
    },
    cache: false,
    type: "POST",
    dataType: "json",
    success: function(partialViewData) {
        alert("Settings saved");
        return true;
    },
    error: function(xhr, ajaxOptions, thrownError) {
        alert("ERROR SAVING SETTINGS");
        return false;
    }
});

Here is my action method

    [Authorize]
    [HttpPost]
    public IActionResult SaveSetting(int companyId, IList<ReportSetting> reportSettings)
    {
        _reportSettingsService.SaveSettings(companyId, reportSettings);

        return Json(reportSettings);
    }

And razor view of button

<a type="submit" class="btn btn-success" type="button" data-bind="click: SaveButtonClicked" asp-controller="ReportSetting" asp-action="Index">Save</a>

This occurs on Chrome. On IE no alert appears but the action method does run. I am running .net5. Any advice?

Thanks


Solution

  • Have fixed this now. My handler was returning true, so I think anchor tag was reloading as request was being fired so request getting in a muddle. I have now changed it to return false and in success handler I refresh the page