76

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();
            }
        }
    }
}
5
  • 2
    " { \"Name\" : \"AA\" } " -> " { 'Name' : 'AA' } " there is a difference between " and ' inside a json object
    – HellBaby
    Dec 29, 2013 at 16:33
  • 2
    Yes, and your second example produces invalid JSON. Single quotes are not valid JSON! Dec 29, 2013 at 16:35
  • @DarinDimitrov this works also from what I saw(you can try it on jsonviewer.stack.hu), but you can't send a string as an object(if you don't have that object with the string name avaible). So in the end: you're right
    – HellBaby
    Dec 29, 2013 at 16:41
  • Does this error come up on the client side or on the server side?
    – Breedly
    Mar 14, 2015 at 14:44
  • You just lost Internet connection. That's all.
    – rob
    Aug 11, 2018 at 0:47

10 Answers 10

86

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.

11
  • 1
    Hi, Darin, thanks for the quick response. I tried to paste your code into mine replacing what I had. But I got exactly the same error. I can see the data is pushed into the data base. I can select to verify that. I am using MS ASP.NET MVC4 with knockout.js. Can figure out which part is complaining about this error.
    – Shawn
    Dec 29, 2013 at 16:51
  • 1
    Maybe the error's inside your loadJsonData function that you are calling inside the success callback and has nothing to do with the AJAX request itself? Where/when exactly are you seeing this error? Use the Network tab of FireBug or Chrome developer toolbar to inspect the AJAX request and see if the server returns JSON response. What's the exact response from the server? Your success callback doesn't take any arguments. Why is that? Does your SaveProduct controller action return a JsonResult? I suspect that you declared it as void. Please read my entire answer more carefully. Dec 29, 2013 at 16:52
  • 1
    Alright, but you didn't answer my other questions in the previous comment. I will repeat them: What's the exact response from the server? Your success callback doesn't take any arguments. Why is that? Does your SaveProduct controller action return a JsonResult? I suspect that you declared it as void. Dec 29, 2013 at 17:02
  • 2
    Dude, are you even reading my answer??? One of the things I have stressed upon is that your controller action should return a JsonResult. There's no such thing as a controller action that returns void. You have specified dataType: 'json' so return JSON. That's it. As far as what parameter this controller action should take, well, from the JSON you are sending ({"Name":"AA"}) it should be a class that has a Name property of type string. All this is already shown in my answer. READ IT MORE CAREFULLY. I have provided you with everything necessary to resolve this problem in my answer Dec 29, 2013 at 17:35
  • 1
    So yeah, modify your action signature to look like this: [HttpPost] public ActionResult SaveProduct (Product product) { ... return Json(new { success = true }); }. Or get rid of this dataType: 'json' attribute from your AJAX request if you don't want to return JSON. In this case you could return simply status code 201 (Created with empty response body): return new HttpStatusCodeResult(201);. Dec 29, 2013 at 17:40
7

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).

4

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.

1
  • 1
    Thanks, let me to: 'return Request.CreateResponse(HttpStatusCode.OK, "Done");'
    – Rafe Smith
    Feb 8, 2021 at 18:28
2

May be it will be useful.

The method parameter name should be the same like it has JSON

It will work fine

C#

public ActionResult GetMTypes(int id)

JS

 var params = { id: modelId  };
                 var url = '@Url.Action("GetMTypes", "MaintenanceTypes")';
                 $.ajax({
                     type: "POST",
                     url: url,
                     contentType: "application/json; charset=utf-8",
                     dataType: "json",
                     data: JSON.stringify(params),

It will NOT work fine

C#

public ActionResult GetMTypes(int modelId)

JS

 var params = { id: modelId  };
                 var url = '@Url.Action("GetMTypes", "MaintenanceTypes")';
                 $.ajax({
                     type: "POST",
                     url: url,
                     contentType: "application/json; charset=utf-8",
                     dataType: "json",
                     data: JSON.stringify(params),
1

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\"}"

0
1

Unexpected end of input means that the parser has ended prematurely. For example, it might be expecting "abcd...wxyz" but only sees "abcd...wxy.

This can be a typo error somewhere, or it could be a problem you get when encodings are mixed across different parts of the application.

One example: consider you are receiving data from a native app using chrome.runtime.sendNativeMessage:

chrome.runtime.sendNativeMessage('appname', {toJSON:()=>{return msg}}, (data)=>{
    console.log(data);
});

Now before your callback is called, the browser would attempt to parse the message using JSON.parse which can give you "unexpected end of input" errors if the supplied byte length does not match the data.

0

I did this in Node JS and it solved this problem:

var data = JSON.parse(Buffer.concat(arr).toString());
0

spoiler: possible Server Side Problem

Here is what i've found, my code expected the responce from my server, when the server returned just 200 code, it wasnt enough herefrom json parser thrown the error error unexpected end of input

fetch(url, {
        method: 'POST',
        body: JSON.stringify(json),
        headers: {
          'Content-Type': 'application/json'
        }
      })
        .then(res => res.json()) // here is my code waites the responce from the server
        .then((res) => {
          toastr.success('Created Type is sent successfully');
        })
        .catch(err => {
          console.log('Type send failed', err);
          toastr.warning('Type send failed');
        })
0

I've had the same error parsing a string containing \n into JSON. The solution was to use string.replace('\n','\\n')

0

This error occurs on an empty JSON file reading.

To avoid this error in NodeJS I'm checking the file's size:

const { size } = fs.statSync(JSON_FILE);
const content = size ? JSON.parse(fs.readFileSync(JSON_FILE)) : DEFAULT_VALUE;

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.