Silagy
Silagy

Reputation: 3083

Getting 500 error when sending Ajax request

I have read every post here about it and didn't find the answer to fix it.

I have an action in this controller:

public class AccountController : Controller
{
    [HttpPost]
    public JsonResult CheckUsername(string i_username)
    {
        var MembershipProvider = new OtakimMembershipProvider();

        return Json(MembershipProvider.CheckUsername(i_username));
    }
}

This is the code in the View:

$.ajax({
    type: "POST",
    url: '@Url.Action("CheckUsername", "Account")',
    contentType: "application/json; charset=utf-8",
    data: { 'i_username': 'silagy' },
    dataType: "json",
    success: function (data) {
        alert(data);
    },
    error: function () {

    }
});

Now I keep getting this error:

POST http://localhost:61035/Account/CheckUsername 500 (Internal Server Error) 

According to posts here, I am using this to generate the URL:

url: '@Url.Action("CheckUsername", "Account")', 

Restitution - EDIT


OK, after digging in in debug mode i found the problem.

The error was: "Invalid JSON primitive: i_username."

and based on this post "Invalid JSON primitive" in Ajax processing

i changed my code to this:

var data = { "i_username": "silagy" };

            $.ajax({
                url: '@Url.Action("CheckUsername", "account")',
                type: 'POST',
                data: JSON.stringify(data),
                datatype: "json",
                contentType: "application/json; charset=utf-8",
                error: function (xhr) {
                    alert('Error: ' + xhr.statusText);
                },
                success: function (result) {
                    alert(result);
                }
            });

Upvotes: 2

Views: 5054

Answers (1)

Viktor Bahtev
Viktor Bahtev

Reputation: 4908

You should json stringify your data if you use contentType = application/json.

Try following code:

Variant 1:

$.ajax({
    type: "POST",
    url: '@Url.Action("CheckUsername", "Account")',
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({ 'i_username': 'silagy' }),
    // ... 
});

Or change contentType to application/x-www-form-urlencoded; charset=UTF-8. (actually this is the default option for jQuery ajax contentType so just removing application/json will solve the problem)

Variant 2:

$.ajax({
    type: "POST",
    url: '@Url.Action("CheckUsername", "Account")',
    contentType: "application/x-www-form-urlencoded; charset=UTF-8",
    data: { 'i_username': 'silagy' },
    // ... 
});

Upvotes: 3

Related Questions