MChan
MChan

Reputation: 7172

JQuery web service authorization

My client has a web service API which I must connect to first with a payload of username and password to get SecurityToken, then use this SecurityToken as part of the header sent for all following API calls, so I was wondering how I can do this using JQuery $.ajax method. Any example is highly appreciated.

Here is what I've tried so far in authenticating but it is always returning error in response so I am not sure if it is correct:

$(document).ready(function(){  
    $.ajax
      ({
        type: "POST",
        url: "http://portal.domainname.com/auth",
        dataType: 'json',
        async: false,
        data: '{"Login : [email protected]", "Password : test"}',
        success: function (){
            alert('Success'); 
        },
        error: function(xhr, error){
            console.debug(xhr); console.debug(error);
        } 
    });

}); 

Problem with the above code is that it always return 200 OK status but token is never returned in response

Upvotes: 1

Views: 127

Answers (2)

Software Guy
Software Guy

Reputation: 3280

For me the JSON that you are sending is not valid json:

data: '{"Login : [email protected]", "Password : test"}',

it should be

data: '{"Login" : "[email protected]", "Password" : "test"}',

Upvotes: 1

Igor
Igor

Reputation: 33993

I think you want to send data as an object, rather than a string, since string implies it's a query string:

data: JSON.stringify({ Login: "[email protected]", Password : "test" }),

Also, if you are getting a 200, then it means the response was successful (and you should use the success callback), however all your logic is in the error callback instead. You probably want:

success: function(data) {
    // Do something with data
},

Upvotes: 1

Related Questions