Shawn Shawn - 2 months ago 5
Ajax Question

json parsing error syntax error unexpected end of input

I got the following piece of code

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);
}
});
}


Notice that I hard coded the data value. The data get pushed into the database fine. However, I keep getting the error "parsing error syntax error unexpected end of input". I am sure my data is in correct JSON syntax. When I checked with on Network of Chrome inspector the saveProduct request showed the data is correct.

{ "Name": "AA" }


This POST request did not have response. So I am clueless as to where the parse error was coming from. I tried using FireFox browser. the same thing happened.

Can anyone give some idea as to what is wrong?

Thanks,

P.S.
Here is the controller code

namespace MvcApplJSON.Controllers
{
public class KnockoutController : Controller
{
//
// GET: /Knockout/

public ActionResult Index()
{
return View();
}

[HttpGet]
public JsonResult GetProductList()
{
var model = new List<Product>();
try
{
using (var db = new KOEntities())
{
var product = from p in db.Products orderby p.Name select p;
model = product.ToList();
}
}
catch (Exception ex)
{ throw ex; }
return Json(model, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public void SaveProduct (Product product)
{
using (var db = new KOEntities())
{
db.Products.Add(new Product { Name = product.Name, DateCreated = DateTime.Now });
db.SaveChanges();
}
}
}
}

Answer

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 should absolutely never be hardcoding your JSON as strings as you did. 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 casesusually you don't need to be setting the dataType property when making AJAX request to an ASP.NET MVC controller action. The reason for that 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).

Ohhhh, and one more thing that I just noticed that made my eyes bleed:

async: false,

Seriously? Please, NEVER EVER NEVER set this attribute to false. I am seeing people doing this over and over and over and over again. It's outrageous. Guys, if you set this attribute to false you are no longer doing AJAX. You are blocking/freezing the client browser during the entire execution of the request killing all the benefits that AJAX gives you. Just make a normal request in this case. Don't bother with javascript. If you want to do AJAX, then stop thinking in terms of procedural and sequential programming. Start thinking in terms of asynchronous events and callbacks.

Comments