Sike12
Sike12

Reputation: 1262

Ajax call failing to get the return message from web api service

I am making a simple ajax call to the web api service that serves an authentication routine. My problem is the ajax call can make a request to the service but errors out once the service returns a boolean value.

WHAT I WANT:

All i want to do is check if the returned boolean is true or false. If true i want to redirect the user to another page. Could somebody please help me out on this?

JQUERY CODE:

<script type="text/javascript">
$(document).ready(function () {
    $('#submitButton').click(function () {   
        var name = $(userNameTextBox).val);          
        var pass = $(passwordTextBox).val();
        if (name.length == 0 || pass.length == 0) {
            alert("Please enter your credentials");
        }
        else {
             $.ajax({
                url: "http://localhost:50503/api/Authentication/Authenticate",
                data: { userName: name, passWord: pass },
                cache: false,
                type: 'GET',
                dataType: 'json',
                success: function (msg) {

                    alert(msg);
                },
                error: function (msg) {
                    alert("Error Message: "+msg);
                }                  
            });

        }//end of else
    });
});
</script>

Here is my webapi service

public class AuthenticationController : ApiController
{
    [HttpGet]
    [Route("api/Authentication/Authenticate")]
    public bool Authenticate(string userName,string passWord)
    {
        if (userName.ToLower().Equals("username") && passWord.ToLower().Equals("password"))
        {
            return true;
        }
        else
        {
            return false;
        }            
    }
}

Upvotes: 0

Views: 3014

Answers (3)

Lucas Ponzo
Lucas Ponzo

Reputation: 104

Try to use (worked for me, check responseJSON.Message of first parameter object):

$.post(url, jsonData).
done(function (data) {}).
fail(function (xhr, status, err) {
   alert("Error " + err + ". " + xhr.responseJSON.Message);
});

Upvotes: 1

aknuds1
aknuds1

Reputation: 67997

If all else fails, put a debugger breakpoint (e.g., via the debugger directive in your error callback to $.ajax and run your code in the browser's debugger (i.e. Chrome dev tools). Then, after the breakpoint is hit, you should be able to determine (by walking the stack) why the error callback is invoked.

My Test

I've tried to reproduce your case, and for me it doesn't fail. I've defined a test controller in the following way:

using System.Web.Http;

namespace Test
{
    public class TestController : ApiController
    {
        [HttpGet]
        public bool Authenticate(string username, string password)
        {
            return username == "user" && password == "pass";
        }
    }
}

And I make an AJAX call to it from JavaScript like so:

$.ajax({url: 'http://localhost:59900/api/test', type: 'get', dataType: 'json', cache: false, data: { userName: 'user', passWord: 'pass' }}).done(function () {console.log("Success", arguments);}).fail(function () { console.log("Error", arguments); });

The AJAX call invokes the success callback (done) with true as its result, so no issues at all.

Parser Error

It appears that jQuery can't parse the JSON sent from Web API (true). To return valid JSON, return an object of the following type from your controller:

public class Result
{
    public bool Result { get;set; }
}

This should result in the following JSON being sent to your client:

{ "Result": true }

Updated controller:

namespace Test
{
    public class TestController : ApiController
    {
        [HttpGet]
        public Result Authenticate(string username, string password)
        {
            return new Result { Result = username == "user" && password == "pass" };
        }
    }
}

Upvotes: 1

MamaWalter
MamaWalter

Reputation: 2113

You can try replace your ajax call by this maybe, remove the dataType:

var request = $.ajax({
    url: "http://localhost:50503/api/Authentication/Authenticate",
    cache: false,
    type: 'POST',
    data: { userName: userName, passWord: passWord }
});
request.done(function (msg) {
   //check the boolean and redirect user to another page.
   if(msg) window.location.href = "http://nextpage.com";
});

i also change the method to POST. More appropriate in your case.

Upvotes: 1

Related Questions