Matt Thrower Matt Thrower - 1 month ago 5
Ajax Question

Combining Ajax posts with MVC controllers and redirects

I'm trying to get my server-side code to play nicely with some page templates we got from a design agency. All is good except that I'm struggling to implement the correct behaviour with the results of the form submission.

What should happen is, if the form submits successfully, some JQuery is triggered to animate into a success message. If not, the user should be redirected to an error page.

Here's the form submit script:

$.ajax({
type: 'POST',
data: JSON.stringify(userObject),
url: submitFormUrl,
contentType: 'application/json; charset=utf-8',
cache: 'false',
dataType: 'json',
success: function (data) {
if(data.Success){
console.log('success');
$('.thanks-msg').fadeIn(1000);
$('#market-message').hide();
}else{
console.log('Error');
}
}
});


And here's the controller action that it posts to:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Register(User userObject)
{
bool userExists;
try
{
if (ModelState.IsValid)
{
userExists = InsertUser(userObject); //calls a sproc
}
else
{
return CollectValidationErrors(); // collects all validation errors into a string
}
}
catch(Exception ex)
{
ViewBag.ErrorMessage = "Sorry! There has been an error " + ex.Message;
return Json(new { result = "Redirect", url = Url.Action("Error", "Home") });
}

if(userExists)
{
ViewBag.ErrorMessage = "This user already exists";
return Json(new { result = "Redirect", url = Url.Action("Error", "Home") });
}

return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}


What happens is that the form submission is received and the code inside executed successfully. But if an error state is returned, there's no redirect.

What am I doing wrong?

SeM SeM
Answer

Try to use error property of ajax call:

$.ajax({
    type: 'POST',
    data: JSON.stringify(userObject),
    url: submitFormUrl,
    contentType: 'application/json; charset=utf-8',
    cache: 'false',
    dataType: 'json',
    error: function (XMLHttpRequest, textStatus, errorThrown) {
         //Do Something
    },
    success: function (data) {
        if(data.Success){
            console.log('success');
            $('.thanks-msg').fadeIn(1000);
            $('#market-message').hide();
        }else{
            console.log('Error');
        }
    }
});
Comments