OnwardsAndUpwards
OnwardsAndUpwards

Reputation: 67

How can I resolve this WCF / AJAX issue? (400 Bad Request error accessing database)

I'm pretty novice with AJAX and JavaScript so please bear with me. I want to use an AJAX call to send a new user object to a WCF C# method which then goes and creates the user in a SQL server db, and then for the C# to send back a validation object to the AJAX call, (containing a message that either the user has been successfully created, or it hasn't).

This is my AJAX code:

$("#createUserCallButton").click(function () {
       var reply = $.ajax({
            url: "http://localhost/userservice/user.svc/createuser",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            type: "POST",
            data: JSON.stringify({
                "username": "ThisIsMyUsername",
                "password": "ThisIsMyPassword"
            }),

            success: function (data) {
                console.log('success');
                console.log(reply.responseText);
            },
            error: function (error) {
                console.log('failure');
                console.log(error);
            },

        });
    });

This is my C# code:

public class User
{
    [DataMember]
    public string username { get; set; }

    [DataMember]
    public string password { get; set; }
}



[OperationContract]
[WebInvoke(Method = "*", UriTemplate = "/createuser",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare)]
Validation Create_User(User json);



 public Validation Create_User(User user)
 {
        Validation validation = new Validation { PassesValidation = true, Reason = ("") };

        dataAccessor.CreateOne_User(user);

        return validation;

 }

Now when I comment out this line...

        dataAccessor.CreateOne_User(user);

It returns the Validation object to the Console window and reports success. But when this line is present, (and the code is going off to create the user), the AJAX call returns failure with this error:

Failed to load resource: the server responded with a status of 400 (Bad Request)

However, even when it reports failure the user is successfully created in the database, so I don't think the issue is with the database part of it.

I think this comes down to a gap in my understanding of AJAX. I have looked into this at length and watched countless tutorial videos and I'm still struggling. If some kind person out there can come up with a solution to this problem I will be really grateful.

Thanks!

Upvotes: 1

Views: 68

Answers (1)

Bhaktuu
Bhaktuu

Reputation: 89

As it returns Validation Object when below line is commented, I suspect there should be an error while executing the below statement.May be you can add try catch block or logs to determine where is the code exactly breaking.

'dataAccessor.CreateOne_User(user);'.

Upvotes: 1

Related Questions