user3208486
user3208486

Reputation: 53

Invalid Character using json.parse

Using Asp.Net Core, after an ajax form submit I am returning an IActionResult from a Controller containing a Json result of my MVC Model object (Comment):

[HttpPost]
    public IActionResult AjCreate([FromForm] Comment comment)
    {
    // do whatever to save to the database
    //....
    // return a json object
        return Json(comment);
        //return Ok(comment);
    }

The script to submit the form and handle the response is as follows:

    $(function () {
        $('#submitButton').on('click', function (e) {
            e.preventDefault();
            var formData = $('#myForm').serialize();
            console.log('before ajax: ', formData);
            $.ajax({
                type: 'POST',
                url: 'AjCreate',
                dataType: 'json',
        contentType: 'application/x-www-form-urlencoded; charset=utf-8',
                data: formData,
                success: function (response) {
                    var comment = JSON.parse(response);     //<<<Invalid character error here
                    console.log('Success: ' + comment.commentText);
                },
                error: function (xhr, ajaxOptions, thrownError) {
                alert('error is:' + thrownError);
                }
            });

        });
    });

I am hoping to use JSON.parse to be able to access the 'properties' of the object returned, but the JSON.parse line causes an Invalid character error. The response body header shows the json response to be {"id":2,"commentText":"comment 2 text","commentDate":"2111-01-01T00:00:00","userName":"Will","parentCommentId":1}. I can get this if I use JSON.stringify instead, but how do I then access the object properties e.g. comment.id?

Can anyone suggest what I am doing wrong or a way around this? Ultimately, I want to add elements to the page based on the returned values.

Upvotes: 1

Views: 1577

Answers (1)

pishpish
pishpish

Reputation: 2614

From jQuery documentation, under dataType

"json": Evaluates the response as JSON and returns a JavaScript object.

You've already got an object, just use it:

success: function (response) {
  console.log('Success: ' + response.commentText);
},                      //  ^^^^^^^^

Upvotes: 3

Related Questions