I have a ajax form in which I would like to call two different javascript functions, one for success and one for failure. In both of these calls, I pass data back from the server to the javascript. Please note the following:
I have this in my view
@using (Ajax.BeginForm("MyAction", null,
new AjaxOptions
{
HttpMethod = "POST", // HttpPost
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "myDiv",
OnSuccess = "callSuccess(data.msg)",
OnFailure = "callFailure(data.msg)",
}, new { @class = "form-inline" }))
{
... // my content
}
My controller has the following logic when return the post.
public ActionResult MyAction(string myString)
{
...
// If error occurred
return Json(new { success = false, msg= "Fail" });
...
// If no errors
return Json(new { success = true, msg= "Success" });
}
No matter what is returned, OnSuccess
is the only one that gets called. What is the proper way to call OnFailure
?
Consider Using HTTP Status Codes
You could consider returning the appropriate HTTP status code that corresponds with the type of error you want to trigger (i.e. Unauthorized, Bad Request, etc.) by returning an
HttpStatusCodeResult
object :Handling This Client-Side
If you didn't want to do this, you could consider defining a single result event (i.e.
OnSuccess = "call(data);
) and then within that event, check yoursuccess
property to determine what to do :Yes it will always call OnSuccess. But you can check your success Property inside onSuccess function.
Otherwise you have to send error status as Rion Williams mention
With the help from Rion Williams post, I was able to call both functions. More importantly, I figured out how to access and display the desired message upon success/failure:
My controller
My view: