FllnAngl
FllnAngl

Reputation: 576

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in JSON format

I'm trying to get data from my database using AJAX and put that data in my jQuery FullCalendar. though when trying to get the data I get an error.

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [(JSON object)]

when I console.log(doc) I get a correct JSON object which I validated using JSON Formatter & Validator

I made a question yesterday about a different error but the same script so HERE is some additional information to see what I have tried and how I got to this point.

This is the output of the console.log(obj):

[  
{  
  "id":1,
  "title":"K. Keesen",
  "desc":"zelf ziek gemeld",
  "start":"2-2-2018 13:00:00",
  "end":"5-2-2018 13:00:00",
  "user":15,
  "melding":1
  },
  {  
  "id":3,
  "title":"K. Keesen",
  "desc":null,
  "start":"2-2-2018 13:00:00",
  "end":"5-2-2019 13:00:00",
  "user":15,
  "melding":1
  },
  {  
  "id":5,
  "title":"K. Keesen",
  "desc":null,
  "start":"14-2-2018 08:30:00",
  "end":"",
  "user":15,
  "melding":1
  },
  {  
  "id":6,
  "title":"K. Keesen",
  "desc":"srgsrgrgdrgdrgd",
  "start":"7-2-2018 08:30:00",
  "end":"",
  "user":38,
  "melding":13
  },
  {  
  "id":7,
  "title":"T. test",
  "desc":null,
  "start":"14-2-2018 08:30:00",
  "end":"21-2-2018 17:00:00",
  "user":63,
  "melding":10
  },
  {  
  "id":8,
  "title":"K. Keesen",
  "desc":null,
  "start":"16-2-2018 08:30:00",
  "end":"23-2-2018 17:00:00",
  "user":28,
  "melding":14
  },
  {  
  "id":9,
  "title":"K. Keesen",
  "desc":null,
  "start":"14-2-2018 08:30:00",
  "end":"",
  "user":33,
  "melding":12
  },
  {  
  "id":10,
  "title":"K. Keesen",
  "desc":"fvghbj",
  "start":"22-2-2018 08:30:00",
  "end":"",
  "user":15,
  "melding":11
  },
  {  
  "id":11,
  "title":"K. Keesen",
  "desc":null,
  "start":"15-2-2018 08:30:00",
  "end":"22-2-2018 17:00:00",
  "user":15,
  "melding":1
  },
  {  
  "id":12,
  "title":"K. Keesen",
  "desc":null,
  "start":"23-2-2018 08:30:00",
  "end":"",
  "user":15,
  "melding":1
  },
  {  
  "id":13,
  "title":"K. Keesen",
  "desc":"Test take #25",
  "start":"7-2-2018 08:30:00",
  "end":"23-2-2018 17:00:00",
  "user":15,
  "melding":1
  },
  {  
  "id":14,
  "title":"K. Keesen",
  "desc":null,
  "start":"8-2-2018 08:30:00",
  "end":"",
  "user":15,
  "melding":1
  }
]

I'm not very good at AJAX so I bet there are mistakes that I can't see, this is my script:

<script>
    $(document).ready(function () {

        GenerateCalendar();

        function GenerateCalendar() {
            $("#calendar").fullCalendar({
                theme: true,
                header: {
                    left: "prev,next today",
                    center: "title",
                    right: "month,agendaWeek,agendaDay"
                },

                defaultView: 'month',
                selectable: true,
                selectHelper: true,
                editable: true,
                eventLimit: true,
                events: function (start, end, callback) {
                    $.ajax({
                        type: "POST",    //WebMethods will not allow GET
                        url: '@Url.Action("List/medewerker_melding")',   //url of a webmethod - example below
                        data: "",  //completely take out 'data:' line if you don't want to pass to webmethod - Important to also change webmethod to not accept any parameters
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (doc) {
                            var events = [];   //javascript event object created here
                            var obj = JSON.parse(doc);  //.net returns json wrapped in "doc"
                            console.log(obj); //Shows a correct JSON format in the console
                            //jQuery.parse.JSON(obj); //This gives an error: Cannot read property 'JSON' of undefined
                            $.each(doc, function (index, obj) {
                                events.push({
                                    title: obj.title,
                                    start: obj.start,
                                    end: obj.end
                                });
                            });
                            callback(events);

                            $('#calendar').fullCalendar('renderEvent', events, true);
                        }
                    });
                },

                select: function (start, end) {
                    var start = moment(start).format();
                    var end = moment(end).format();
                    $('#startDate').val(start);
                    $('#endDate').val(end);
                    $('#eventModal').modal();
                    if ($('#eventModal')) {
                        $(".meldingForm").submit(function () {
                        });
                    }
                    $('#calendar').fullCalendar('unselect');
                },
            });
        }
    });
</script>

Here's the controller that it sends the request to:

    [HttpPost, ActionName("List")]
    [WebMethod(EnableSession = true)]
    public ActionResult List()
    {
        temphrmEntities db = new temphrmEntities();
        List<medewerker_melding> eventList = db.medewerker_melding.ToList();

        // Select events and return datetime as sortable XML Schema style.
        var events = from ev in eventList
                     select new
                     {
                         id = ev.ID,
                         title = ev.medewerker.voorvoegsel + ". " + ev.medewerker.achternaam,
                         desc = ev.Omschrijving,
                         start = ev.datum_van.ToString(),
                         end = ev.datum_tot.ToString(),
                         user = ev.medewerkerID,
                         melding = ev.meldingID
                     };

        // Serialize to JSON string.
        JavaScriptSerializer jss = new JavaScriptSerializer();
        String json = jss.Serialize(events);
        Debug.WriteLine("Json:"+json);
        return Json(json, JsonRequestBehavior.AllowGet);

    }

and for those who would like to try and reproduce the issue, here's my HTML and some additional script:

<div class="modal fade" id="eventModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title" id="exampleModalLabel">Creëer agenda item</h3>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <span id="verplicht">Velden met <i class="fa fa-exclamation-triangle" aria-hidden="true"></i> bent u verplicht in te vullen</span>
        <form class="meldingForm" role="form" action="@Url.Action("Create", "medewerker_melding")" method="post">
            @Html.AntiForgeryToken()
            <div class="modal-body">
                <p><label for="werknemer">Werknemer:</label>@Html.DropDownList("medewerkerID", null, htmlAttributes: new { @class = "form-control ddL" })</p>
                <p><label for="titel">Titel:</label>@Html.DropDownList("meldingID", null, htmlAttributes: new { @class = "form-control ddL" })</p>
                <p><label for="start"><i class="fa fa-exclamation-triangle triangle" aria-hidden="true"></i>Start:</label><input name="startDate" id="startDate" type="date" class="form-control" onmousedown='return false;' readonly required /><input name="start" id="start" class="form-control time" required /></p>
                <p><label for="end">Eind:</label><input name="endDate" type="date" class="form-control" /><input name="end" id="end" class="form-control time" /></p>
                <p><label for="Omschrijving">Omschrijving:</label><textarea type="text" name="Omschrijving" id="Omschrijving" class="Omschrijving form-control" placeholder="Omschrijving" maxlength="200"></textarea></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-primary">Save changes</button>
            </div>
        </form>
    </div>
</div>

 $(document).ready(function () {
            //zorgt ervoor dat de KendoTimePicker de juiste opties weergeeft.
            $('#start').kendoTimePicker({
                format: "HH:mm",
                min: "8:00",
                max: "17:30",
                value: "8:30",
                interval: 15
            });

            $('#end').kendoTimePicker({
                format: "HH:mm",
                min: "8:00",
                max: "17:30",
                value: "17:00",
                interval: 15
            });
        })

EDIT

I changed a line in my ajax to make an object out of the doc string, I accidently left that in there. now the output is this:

JSFIDDLE (it wouldnt go in a code block for some reason)

Thanks!

Edit for the possible duplication The reason this isn't a duplicate to that question is because I simply had mistakes in my code that caused these errors. and my controller was already parsing an object.

so it wasn't the problem that my doc was not an object; because it was.

Upvotes: 1

Views: 1695

Answers (2)

FllnAngl
FllnAngl

Reputation: 576

Thanks to @Evk's help we discovered that I was missing an argument in

events: function(start, end, callback)

It should have been

events: function(start, end, timezone, callback)

also var obj = JSON.parse(doc); is now var obj = doc; since that caused it to try and make an object out of an object

and finally in my controller the script below was causing double serialization.

// Serialize to JSON string.
    JavaScriptSerializer jss = new JavaScriptSerializer();
    String json = jss.Serialize(events);
    Debug.WriteLine("Json:"+json);
    return Json(json, JsonRequestBehavior.AllowGet);

removing the serialize and changing it to return Json(events, JsonRequestBehavior.AllowGet); fixed the errros.

since Evk hasn't posted an answer, I have.

Thanks Evk!

Upvotes: 1

Saveen
Saveen

Reputation: 712

In Operator can be only applied with object. Not with string or primitive type.

Upvotes: 0

Related Questions