4

I have upgraded to jquery 1.10.2. I am using jquery migrate and I am having the warning message "jQuery.parseJSON requires a valid JSON string"

I have not understood how I can correct that. Can anyone help me out with the best solution of how I can remove the warning message

The javascript is as follows:

 function Search() {

        $.ajax({
            cache: false,
            contentType: "application/json; charset=utf-8",
            dataType: "html",
            url: "@Url.Action("Search")",
            data:  JSON.stringify({myModel: $("#DateFrom").val()}),
            success: function (data)
            {
                $("#NewDiv").html(data);
            },
            error: function (request, status, error)
            {
                  DisplayError(ParseErrorFromResponse(request.responseText, "Unknown error"), true);
            }
        });

 }

In the Controller:

 public PartialViewResult Search(myModel myModel)
    {
        return PartialView("SearchResult", myModel);
    }

ParseErrorFromResponse:

Function ParseErrorFromResponse(responseText, defaultError)
{
    var text = responseText.replace("<title>", "TitleStart");       
    var startIndex = text.indexOf("TitleStart");
    var endIndex = text.indexOf("TitleEnd");
    return (startIndex == -1 || endIndex == -1) ? defaultError : text.substring(startIndex + 10, endIndex);
}
learning
  • 11,415
  • 35
  • 87
  • 154

5 Answers5

3

You need to send your data as JSON.

Where you have data: $("#DateFrom").val(), replace it with data: JSON.stringify({$("#DateFrom").val()}).

EDIT: You may need to send it as JSON.stringify({(myModel: $("#DateFrom").val()}).

Saghir A. Khatri
  • 3,429
  • 6
  • 45
  • 76
Kyhil
  • 39
  • 2
0

The error may be related to "" or false values that used to convert to null in versions of jQuery prior to 1.9.0 per THIS PAGE

Here it the relevant excerpt including the suggested solution:

JQMIGRATE: jQuery.parseJSON requires a valid JSON string

Cause: Before jQuery 1.9.0, the $.parseJSON() method allowed some invalid JSON strings and returned null as a result without throwing an error. This put it at odds with the JSON.parse() method. The two methods are aligned as of 1.9.0 and values such as an empty string are properly not considered valid by $.parseJSON().

Solution: If you want to consider values such as "" or false successful and treat them as null, check for them before calling $.parseJSON(). Since falsy values such as an empty string were previously returned as a null without complaint, this code will suffice in most cases:

var json = $.parseJSON(jsonString || "null"); 

If your own code is not calling $.parseJSON() directly, it is probably using AJAX to retrieve a JSON value from a server that is returning an empty string in the content body rather than a valid JSON response such as null or {}. If it isn't possible to correct the invalid JSON in the server response, you can retrieve the response as text:

$.ajax({
    url: "...",
    dataType: "text",
    success: function( text ) {
        var json = text? $.parseJSON(text) : null;
        ...
    } 
});
PeterKA
  • 24,158
  • 5
  • 26
  • 48
  • Data is raw html. I can`t do var json = data? $.parseJSON(data) : null; – learning Jul 02 '14 at 08:56
  • @learning is the function `Search` the only part of your application that uses a JSON method? What is the output of `console.log( $.type( $("#DateFrom").val() ) )` and `console.log( $("#DateFrom").val() )`? – PeterKA Jul 02 '14 at 12:19
0

Remove content-type attribute and do like this:

function Search() {

        $.ajax({
            cache: false,
            url: "@Url.Action("Search","ControllerName")",
            dataType:"html",
            data:
            {
            myModel: $("#DateFrom").val()
            },
            success: function (data)
            {
                $("#NewDiv").html(data);
            },
            error: function (request, status, error)
            {
                  DisplayError(ParseErrorFromResponse(request.responseText, "Unknown error"), true);
            }
        });

 }

and in action:

 public PartialViewResult Search(string myModel)
    {
        return PartialView("SearchResult", myModel);
    }
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
0

I think it's because you're missing double quotes around key myModel in line

...
data:  JSON.stringify({myModel: $("#DateFrom").val()},
...

and not because of jquery version upgrade.try using

data:  JSON.stringify({"myModel": $("#DateFrom").val()},
skam
  • 357
  • 5
  • 18
0

Try like this.. You have to return Json as result from your Search().

 public JsonResult Search(myModel myModel)
 {
    return Json(result);
 }

and also in you Script, try like this..

$.ajax({
        type:"POST"
        cache: false,
        contentType: "application/json; charset=utf-8",
        url: "@Url.Action("Search","ControllerName")",
        dataType: "json",
        data:  JSON.stringify({"myModel": $("#DateFrom").val()}),
        success: function (data)
        {
            $("#NewDiv").html(data);
        }
    });

Also check $("#DateFrom").val() is having correct value and put an

alert(data)

in success and check the returned data.

I have updated the url.

Nemo
  • 310
  • 1
  • 3
  • 12