2

This is my first time working with an Ajax Json post.

I have the following script code now:

<script type="text/javascript">
$(document).ready(function () {
    // If the button is clicked, redirect to a controller action, send the data, and show
    // a view with the changes. 
    $('#submitDiffs').click(function () {
        var requirementNumberData = "@Model.FirstOrDefault().Requirement.RequirementNumber";

        var data = [];
        $('table tr').children('td').children('#selected :checked').each(function (i, element) {
            var el = $(element);
            data[i] = el.parent().siblings(':eq(1)').html();
        });

        diffParameters = GetDifferenceParameters(data);
        var jsonData = JSON.stringify(diffParameters, null, 2);

        $.ajax({
            url: '/Requirements/Differences',
            type: 'POST',
            data: jsonData,
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            // callback handler that will be called on error 
            success: function (response) {
                alert("Ajax call made successfully!!!");
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status + '\n\r' + xhr.responseText);
                alert(thrownError);
            }     

        });
    });

    function GetDifferenceParameters(data) {
        var requirementNumber = "@Model.FirstOrDefault().Requirement.RequirementNumber";
        var oldRequirement = data[1];
        var newRequirement = data[0];

        return { 
            RequirementNumber: requirementNumber,
            OldRequirement: oldRequirement,
            NewRequirement: newRequirement
        };
    }
});

This code is posting to a MVC3 controller, code below:

[HttpPost]
public ActionResult Differences(RequirementDifferenceViewModel model)
{
    HtmlDiff diff = new HtmlDiff(model.OldRequirement, model.NewRequirement);
    model.ContentDifference = diff.Build();

    return View(model);
}

Here is the view model:

public class RequirementDifferenceViewModel
{
    public string RequirementNumber { get; set; }
    public string OldRequirement { get; set; }
    public string NewRequirement { get; set; }
    public string ContentDifference { get; set; }
}

If I omit the jSON.stringify the controller action does not get executed, and I get a 500 error. If I stringify, I get a 200 status, but yet a jSON parse error is returned to AJAX. In both cases, the exact jSON string is sent to the AJAX call.

Here is the jSON string that I copied out of Firebug:

{
  "RequirementNumber": "PFSNET-UC12-008",
  "OldRequirement": "\n                <p class=\"Bullet1\"><span style=\"font-size:10.0pt;font-family:Wingdings;\nfont-weight:normal\">r<span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp; </span></span><span lang=\"X-NONE\">[PFSNET-UC12-008] – Undo/redo will be supported for Expert\nAssistant. The details can be found in the use case for Undo/Redo.</span>&nbsp; </p> \n\n <p class=\"Bullet2\"><span style=\"font-family:Wingdings;font-weight:\nnormal\" lang=\"X-NONE\">§<span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp; </span></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T11:06\">A</ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T08:36\">n ‘Undo\nLast Action’ button will </ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T11:06\">also </ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T08:36\">be available</ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T11:05\"> for\nselect products</ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T08:36\">.&nbsp; See\nUC12-</ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-29T14:10\">229</ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T08:36\"> for\nadditional information.</ins></span></p> \n\n <p class=\"MsoNormal\">&nbsp;</p> \n\n\n            ",
  "NewRequirement": "\n                <p class=\"Bullet1\"><span style=\"font-size:10.0pt;font-family:Wingdings;\nfont-weight:normal\">r<span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp; </span></span><span lang=\"X-NONE\">[PFSNET-UC12-008] – Undo/redo will be supported for Expert\nAssistant. The details can be found in the use case for Undo/Redo.</span>&nbsp; </p> \n\n <p class=\"Bullet2\"><span style=\"font-family:Wingdings;font-weight:\nnormal\" lang=\"X-NONE\">§<span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp; </span></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T11:06\">A</ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T08:36\">n ‘Undo\nLast Action’ button will </ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T11:06\">also </ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T08:36\">be available</ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T11:05\"> </ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-06-20T12:34\">on </ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-06-20T12:42\">the\nAdvanced Expert Assistant screen.&nbsp; </ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T08:36\">See\nUC12-</ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-29T14:10\">229</ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T08:36\"> for\nadditional information.</ins></span></p> \n\n <p class=\"MsoNormal\">&nbsp;</p> \n\n\n            "
}

I put this string into a jSON validator website and it passed: [http://jsonformatter.curiousconcept.com/]

The exact parse error is: SyntaxError: JSON.parse: unexpected character

Any help would be appreciated!

EDIT 2:

It turns out that the parse error is the result of the AJAX success handler not being able to parse the response correctly. I am still trying to figure this part of it out.

As soon as the Success event is executed, code execution jumps right to the Error event.

2 Answers 2

1

If you run this in a browser, such as firefox or chrome (not ie), then you can inspect the network post and look at the headers. In there, you should be able to see exactly what information was being passed. More than likely you are getting some characters that you don't expect and that is causing the parse error.

1
  • I installed Firefox and it was a big help in debugging the script. I still have not determined the parse error, but your answer was very helpful. Jun 30, 2012 at 13:33
0

var requirementParameters = "{ oldRequirement: contentRecords[1], newRequirement: contentRecords[0] }"; is invalid json

You're probably looking for something like:

var requirementParameters = {
    oldRequirement: contentRecords[1],
    newRequirement: contentRecords[0]
};

This creates an anonymous object with your fields. The old code was just a string which you the JSON.stringify'd again.

1
  • I updated my question and fixed the way I was putting together the json string and it still does not work, but if I do not stringify the controller action does not get called. I am unsure why. Jun 30, 2012 at 15:08

Your Answer

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

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