Tikeb
Tikeb

Reputation: 1068

parseJSON Uncaught SyntaxError: Unexpected token u

This problem has been driving me slightly nuts for more than a few hours now. I've read so many posts and articles now that I have a vague understanding of the problem but not the cause. I realise the problem is that when I submit something like JSON.parse on an object that's undefined. I cannot figure out why that is though. I'm sure it's very simple and I'm sure I'll feel a tool once it's pointed out, but for now I don't mind feeling a bit silly if it sorts the problem.

The problem is that when I submit the form using the below methods I get the following error:

Uncaught SyntaxError: Unexpected token u js:1
i.extend.parseJSON js:1
c js:1
u js:1
n.extend.showLabel js:1
n.extend.defaultShowErrors js:1
n.extend.showErrors js:1
n.extend.form js:1
n.extend.valid js:1
(anonymous function)
i.event.dispatch js:1
y.handle

Also when I move the cursor from field to field I get this error:

Uncaught SyntaxError: Unexpected token u js:1
i.extend.parseJSON js:1
c js:1
u js:1
n.extend.showLabel js:1
n.extend.defaultShowErrors js:1
n.extend.showErrors js:1
n.extend.element js:1
n.extend.defaults.onfocusout js:1
r js:1
(anonymous function) js:1
i.event.dispatch js:1
y.handle js:1
i.event.trigger js:1
i.event.simulate js:1
f

This obviously prevents me from submitting the form to the controller to be processed. The error seems to be from the jquery library (line 498) when it tries to: return n.JSON.parse(t); (t is undefined). I'm using jquery 1.9.1, bootstrap 2.2.2 and jqValidate/1.9.0.unobtrusive.js. The form is in a bootstrap modal and looks as follows:

@model AModelTestApp.Models.UserModel

<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    <h3>User</h3>
</div>

<div class="modal-body">

    @{
        var ajaxOptions = new AjaxOptions
            {
                HttpMethod = "POST",
                OnComplete = "Complete"
            };
    }

    @using (Ajax.BeginForm("EditUser", "Home", ajaxOptions, new { id = "userform" }))
    {
        <div class="row-fluid">
            <div class="span12">
                @Html.ValidationSummary("Ooops..", new { id = "validateuser", @class = "alert alert-error" })
            </div>
        </div>

        <div class="row-fluid">
            <div class="span6">
                @Html.LabelFor(m => m.Id)
                @Html.TextBoxFor(m => m.Id)

                @Html.LabelFor(m => m.Username)
                @Html.TextBoxFor(m => m.Username)

                @Html.LabelFor(m => m.FirstName)
                @Html.TextBoxFor(m => m.FirstName)

                @Html.LabelFor(m => m.LastName)
                @Html.TextBoxFor(m => m.LastName)
            </div>
            <div class="span6">
                @Html.LabelFor(m => m.Email)
                @Html.TextBoxFor(m => m.Email)

                @Html.LabelFor(m => m.UserTypeId)
                @Html.TextBoxFor(m => m.UserTypeId)

                @Html.LabelFor(m => m.Created)
                @Html.TextBoxFor(m => m.Created)

                @Html.LabelFor(m => m.Active)
                @Html.CheckBoxFor(m => m.Active)
            </div>
        </div>
        <div class="row-fluid">
            <div class="span1 offset10">
                <a id="btnclear" class="btn" href="#">Clear</a>
            </div>
        </div>
    }

</div>

<div class="modal-footer">
    <a class="btn" data-dismiss="modal" href="#">Close</a>
    <a id="btnsubmit" class="btn btn-info" href="#">Submit</a>
</div>

<script type="text/javascript">
    $.validator.unobtrusive.parse($('#userform'));

    $('#btnclear').click(function() {
        $('input').val('');
        $(':checkbox').prop('checked', false);
        return false;
    });

    $('#btnsubmit').click(function () {

        $('#userform').validate();
        if ($('#userform').valid()) {
            $('#userform').submit();
        } else {
            alert("Something went wrong with the validation")
        }

    });

    function Complete(result) {
        alert("Woooo - " + result);
    }
</script>

The modal is loaded as follows:

<div class="row-fluid">
    <div class="span12">
        <button id="btnclick" class="btn btn-large btn-block btn-primary">Click Me</button>
    </div>
</div>

<div id="mainmodal" class="modal hide fade"></div>

<script type="text/javascript">
    $('#btnclick').click(function () {
        $.ajax({
            url: '@Url.Action("GetUser", "Home")',
            type: 'GET',
            success: function (result) {
                //awss.modal.popup(result);
                $('#mainmodal').html(result);
                $('#mainmodal').modal('show');
            }
        });
        return;
    });
</script>

From this controller:

    public ActionResult GetUser()
    {
        var user = new UserModel
            {
                Id = 1,
                Username = "sbody",
                FirstName = "Some",
                LastName = "Body",
                Email = "[email protected]",
                UserTypeId = 6,
                Created = new DateTime(2013, 1, 1),
                Active = true
            };
        return PartialView("EditUser", user);
    }

Both ClientValidationEnabled and UnobtrusiveJavaScriptEnabled are enabled in the web.config. I'm hoping it's just a case of me looking at the same problem for too long and can't see the obvious. Any help greatly appreciated. Thanks :)

Upvotes: 10

Views: 11212

Answers (4)

Fordy
Fordy

Reputation: 780

As mentioned in the comments, jquery 1.9 has incompatibility issue with jquery unobtrusive validation. You can quickly check if you have this issue by putting the below code in the browser console window:

JSON.parse(undefined)

If you get

Uncaught SyntaxError: Unexpected token u in JSON at position 0

... then you have the issue. To fix this add the migrate library to your page, underneath jquery:

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.4.1.js"></script>

The errors should go away and be replace with console warnings.This version is for debugging, so if you want the warnings to go away altogether, then point to the migrate library .min file instead:

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.4.1.min.js"></script>

More can be found out about migrating code to jquery 1.9+ with jquery-migrate on GitHub.

Upvotes: 1

Justine Jose
Justine Jose

Reputation: 140

Just add Following Code The issue is happened because of unavailable a span to show error message

 $('input[name],select[name]').each(function ()
{

    if ($(this).attr('name') != '')
    {

        if ($(this).closest('div').find('span[data-valmsg-for=' + $(this).attr('name') + ']').length == 0)
        {
            $(this).closest('div').append('<span class="field-validation-valid error_msg" data-valmsg-for="' + $(this).attr('name') + '" data-valmsg-replace="true"></span>');
        }
    }
})

Upvotes: 1

Steven
Steven

Reputation: 1280

Not sure if this is applicable in this case or not, but I have found sporadic issues like this with unobtrusive validation.

You have a ValidationSummary element in there, so this may not be applicable.. but the times I see it have been when I didn't include a Validation Message element.

It's been a while since I stumbled upon this, but from what I recall, I even needed to add the message for seemingly-innocuous stuff like check-boxes. It seems like the JSON that was being parsed may have been expected to contain the element that was supposed to hold the validation message, and if that was undefined, then it failed the parse once it reached that 'u'.

So, for your code, maybe try something like this:

<div class="row-fluid">
    <div class="span6">
        @Html.LabelFor(m => m.Id)
        @Html.TextBoxFor(m => m.Id)
        @Html.ValidationMessageFor(m => m.Id)

        @Html.LabelFor(m => m.Username)
        @Html.TextBoxFor(m => m.Username)
        @Html.ValidationMessageFor(m => m.Username)

        @Html.LabelFor(m => m.FirstName)
        @Html.TextBoxFor(m => m.FirstName)
        @Html.ValidationMessageFor(m => m.FirstName)

        @Html.LabelFor(m => m.LastName)
        @Html.TextBoxFor(m => m.LastName)
        @Html.ValidationMessageFor(m => m.LastName)
    </div>
    <div class="span6">
        @Html.LabelFor(m => m.Email)
        @Html.TextBoxFor(m => m.Email)
        @Html.ValidationMessageFor(m => m.Email)

        @Html.LabelFor(m => m.UserTypeId)
        @Html.TextBoxFor(m => m.UserTypeId)
        @Html.ValidationMessageFor(m => m.UserTypeId)

        @Html.LabelFor(m => m.Created)
        @Html.TextBoxFor(m => m.Created)
        @Html.ValidationMessageFor(m => m.Created)

        @Html.LabelFor(m => m.Active)
        @Html.CheckBoxFor(m => m.Active)
        @Html.ValidationMessageFor(m => m.Active)

    </div>
</div>

Upvotes: 1

V2Solutions - MS Team
V2Solutions - MS Team

Reputation: 1127

Can you Try the following

'$.parseJSON(result)' 

use parsejson in your ajax success function.

Upvotes: 1

Related Questions