Unexpected end of JSON Input
The problem of the unexpected end of JSON input
In this blog, we will solve the JSON error that occurs at an unexpected end of JSON input. To get an idea of this problem we will try to solve the issue in the following code as shown below:
function pushJsonData(productName) { $.ajax({ url: "/knockout/SaveProduct", type: "POST", contentType: "application/json", dataType: "json", data: " { \"Name\" : \"AA\" } ", async: false, success: function () { loadJsonData(); }, error: function (jqXHR, textStatus, errorThrown) { alert(textStatus + " in pushJsonData: " + errorThrown + " " + jqXHR); } }); }
The error that appears in the following code is shown below:
Solution
One of the major solutions is that the server must have the proper view model to receive the input. An example of the same is given below:
public class UserViewModel
{
public string Name { get; set; }
}
DataType: “json” has been provided by one. This indicates that a JSON result can be anticipated from the server. The controller operation must produce a JSON response. Users might understand the problem if user controller action returns a view. It occurs when jQuery tries to parse the server’s response:
[
]
public ActionResult SaveProduct(UserViewModel model)
{
...
return Json(new { Foo = "bar" });
}
Thus, when sending an AJAX request to an ASP.NET MVC controller action, you typically don’t need to set the dataType field. This is because the framework will automatically set the relevant Content-Type response HTTP header when you return a certain ActionResult (such a ViewResult or a JsonResult). The response will then be parsed by jQuery using this header, and it will then be fed as a parameter to the parsed success callback.
Also Read: How do you get a timestamp in JavaScript?