Question

I have an API controller that returns a HttpStatusCodeResult 200 if it worked and 500 if they weren't able to register. The problem is .done and .fail will both be called no matter what status code is returned. However the information is posted or not posted correctly. Here is my post function. Any ideas what could be causing this would be greatly appreciated?

function register() {
    $.post("../api/Register",
                {
                    'Email': $("#rEmail").val(),
                    'Password': $("#rPassword").val()
                })
    .done((function () {
        alert("Thank you for registering!");
    })())
    .fail((function () {
        alert("Email already exists");
    })());

}

Edit: The problem is that it was reloading the page when jquery.unobtrusive is supposed to prevent that from happening. The fix or workaround was changing it to a button and not a form.

Was it helpful?

Solution

Instead of passing the anonymous functions you were invoking it as a IIFE by adding () at the end of the function

function register() {
    $.post("../api/Register", {
        'Email': $("#rEmail").val(),
            'Password': $("#rPassword").val()
    }).done(function () {
        alert("Thank you for registering!");
    }).fail(function () {
        alert("Email already exists");
    });

}

OTHER TIPS

The problem is you're immediately executing the functions that are getting passed to done and fail. That's causing these functions to be executed right then and there.

So just pass the function itself by changing this

.done((function () {
    alert("Thank you for registering!");
})())

to this

.done(function () {
    alert("Thank you for registering!");
})

You really shouldn't be sending an http status of 500 on an expected registration failure such as "email already exists" condition... this should be handled by a parameter that denotes success / failure as part of a 200 response.

You can handle unexpected internal server errors (status 500) using success or error callbacks like so:

$.ajax({
    url : "../api/Register",
    type : "post",
    data : {"Email" : "you@example.com", "Password" : "pw"},
    dataType : "json",
    success : function(response){
        // handle http 200 responses
        if(response.registrationApproved){
            alert("Thank you for registering!");
        }else{
            alert("email exists");
        }
    },
    error : function(){
        // handle 500 or 404 responses
        alert("server call failed");
    },
    complete : function(){
        // if needed..  this will be called on both success and error http responses
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top