AJAX POST request with JSON data appears successful but database records aren't being inserted

I’m having trouble with my web application. When I try to save data to the database using an AJAX call, everything seems to work fine but no records actually get saved.

Here’s my frontend JavaScript code:

var employee = {};
employee.FullName = $("#inputName").val();
employee.Years = $("#inputAge").val();
employee.ContactEmail = $("#inputEmail").val();

$.ajax({
    method: "POST",
    url: "Main.aspx/SaveEmployee",
    data: "{'employeeData':'" + JSON.stringify(employee) + "'}",
    success: function (result) {
        $("#messageSuccess").text("Record saved!");
        $("#messageSuccess").show();
    },
    error: function (result) {
        alert(result.responseJSON);
    }
});

This connects to my server-side method:

[WebMethod]
public static void SaveEmployee(string employeeData)
{
    JavaScriptSerializer parser = new JavaScriptSerializer();
    Employee emp = parser.Deserialize<Employee>(employeeData);
    DataMethods.SaveEmployee(emp);
}

Which calls this method in DataMethods.cs:

[WebMethod]
public static void SaveEmployee(Employee emp)
{
    EmployeeManager manager = new EmployeeManager();
    manager.SaveEmployee(emp);
}

And finally the database operation:

public void SaveEmployee(Employee emp)
{
    if (string.IsNullOrWhiteSpace(emp.FullName))
    {
        throw new Exception("Name is required");
    }
    if (string.IsNullOrWhiteSpace(emp.ContactEmail))
    {
        throw new Exception("Email is required");
    }

    using (companyEntities context = new companyEntities())
    {
        context.employee.Add(emp);
        context.SaveChanges();
    }
}

The success callback fires and no errors show up in the browser console, but when I check the database there’s nothing there. This same logic works perfectly in my desktop application. Any ideas what might be going wrong?

that’s a strange issue! Have you checked if the server method is really getting called? Maybe adding some logs or breakpoints in your SaveEmployee function could help. sometimes ajax might think it worked, but there could be hidden errors on the server side.

I’ve hit this exact problem before. EF gets confused when you deserialize JSON directly into an Employee object - it thinks you’re trying to update an existing entity instead of creating a new one. Don’t deserialize straight to Employee. Instead, create a fresh Employee instance and manually copy the properties: emp.FullName = deserializedEmp.FullName, etc. Also double-check that your Employee class perfectly matches your database entity. Mismatched property names or types will make EF think it saved successfully when it actually didn’t.

you’re missing the contentType in your ajax call. add contentType: "application/json; charset=utf-8" to the request. without it, the server won’t parse your json data properly even tho everything else looks right.