json parsing error syntax error unexpected end of input
Don't Return Empty Json
In My Case I was returning Empty Json
String in .Net Core Web API
Project.
So I Changed My Code
From
return Ok();
To
return Ok("Done");
It seems you have to return some string or object.
Hope this helps.
I can't say for sure what the problem is. Could be some bad character, could be the spaces you have left at the beginning and at the end, no idea.
Anyway, you shouldn't hardcode your JSON as strings as you have done. Instead the proper way to send JSON data to the server is to use a JSON serializer:
data: JSON.stringify({ name : "AA" }),
Now on the server also make sure that you have the proper view model expecting to receive this input:
public class UserViewModel
{
public string Name { get; set; }
}
and the corresponding action:
[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
...
}
Now there's one more thing. You have specified dataType: 'json'
. This means that you expect that the server will return a JSON result. The controller action must return JSON. If your controller action returns a view this could explain the error you are getting. It's when jQuery attempts to parse the response from the server:
[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
...
return Json(new { Foo = "bar" });
}
This being said, in most cases, usually you don't need to set the dataType
property when making AJAX request to an ASP.NET MVC controller action. The reason for this is because when you return some specific ActionResult
(such as a ViewResult
or a JsonResult
), the framework will automatically set the correct Content-Type
response HTTP header. jQuery will then use this header to parse the response and feed it as parameter to the success callback already parsed.
I suspect that the problem you are having here is that your server didn't return valid JSON. It either returned some ViewResult or a PartialViewResult, or you tried to manually craft some broken JSON in your controller action (which obviously you should never be doing but using the JsonResult instead).
One more thing that I just noticed:
async: false,
Please, avoid setting this attribute to false. If you set this attribute to false
you are are freezing the client browser during the entire execution of the request. You could just make a normal request in this case. If you want to use AJAX, start thinking in terms of asynchronous events and callbacks.
For me the issue was due to single quotes for the name/value pair... data: "{'Name':'AA'}"
Once I changed it to double quotes for the name/value pair it works fine... data: '{"Name":"AA"}' or like this... data: "{\"Name\":\"AA\"}"
I was using a Node http
request and listening for the data
event. This event only puts the data into a buffer temporarily, and so a complete JSON is not available. To fix, each data
event must be appended to a variable. Might help someone (http://nodejs.org/api/http.html).