Home > front end >  Uncaught TypeError: Cannot convert undefined or null to object error when using fullCalendar
Uncaught TypeError: Cannot convert undefined or null to object error when using fullCalendar

Time:04-19

I'm trying to create a FullCalendar in laravel project and get this error :

Uncaught TypeError: Cannot convert undefined or null to object
    at entries (<anonymous>)
    at e (jquery.min.js:4:7727)
    at Ab (jquery.min.js:4:7608)
    at Ab (jquery.min.js:4:7631)
    at Ab (jquery.min.js:4:7631)
    at Function.r.param (jquery.min.js:4:7918)
    at Function.ajax (jquery.min.js:4:12227)
    at Et.e.constructor.select (MyReservations:121:27)
    at constructor.publiclyTrigger (fullcalendar.min.js:9:16482)
    at Et.e.constructor.publiclyTrigger (fullcalendar.min.js:8:30673)

Here is My blade

MyReservations.blade.php

<!DOCTYPE html>
<html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>My Reservations</title>
    <meta name="csrf-token" content="{{ csrf_token() }}" />
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.js"></script>
    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
</head>
<body>




<!-- Modal -->
<div  style="text-transform: capitalize" id="ResModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div >
        <div >
            <div >
                <h5  id="exampleModalLabel">Add New Reservation</h5>
                <button type="button"  data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <div >
                <!-- Room -->
                <select  aria-label="Default select example" name="room_id" id="room_id" >
                    <option selected>Select Room</option>
                    @foreach($room as $items)
                        <option value="{{$items->id}}">{{$items->id}}</option>
                    @endforeach

                </select>
                <br>
                <!--  Title -->


                <div >
                    <span > Title : </span>
                    <input  aria-label="Title" name="title" id="title"></input>

                </div>
                <br>
                <!-- Objectif -->
                <div >
                    <span >Objectif :</span>
                    <textarea  aria-label="Objectif" name="objectif" id="objectif"></textarea>
                </div>
             




            </div>
            <div >
                <button type="button"  data-bs-dismiss="modal">Close</button>
                <button type="button" id="submit" >Save changes</button>
            </div>
        </div>
    </div>
</div>

<div >
    <div >
        <div >
            <h3 >My Reservations</h3>
            <div >

                <div id="calendar">

                </div>

            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG 2QOK9T ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>


    <script>

        $(document).ready(function() {

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            var reservation = @json($events);
           $('#calendar').fullCalendar({
                editable:true,
                header:{
                    left:'prev,next today',
                    center:'title',
                    right:'month, agendaWeek, agendaDay'
                },
                events: reservation,
                selectable:true,
                selectHelper:true,
                select: function(start, end, allDay)
                {
                    $('#ResModal').modal('toggle');
                    $('#submit').click(function () {
                        var title =$('#title').val;
                        var start = moment(start).format('YYYY-MM-DD');
                        var end = moment(end).format('YYYY-MM-DD');
                        var objectif =$('#objectif').val;
                        var room_id =$('#room_id').val;


                    });

                        $.ajax({
                            url:"{{route('MyReservations.store')}}",
                            type:"POST",
                            data:{title, start, end, room_id, objectif},
                            success:function(response)
                            {
                               // MyReservations.fullCalendar('refetchEvents');
                               // alert("Added Successfully");
                                console.log(response)

                         },

                        })

                },

            });
        });

    </script>
</body>
</html>

This is my controller

MyController

 public function  index(){

        $events=array();
        $reservations = reservation::all();
        foreach ($reservations as $reservation){
            $events[] = [
                'title' =>$reservation->title,
                'start' =>$reservation->start,
                'end' =>$reservation->end,

//
//                'objectif' =>$reservation->objectif,
//                'room_id' =>$reservation->room_id,
//                'user_id' =>$reservation->user_id,
//                'stat' =>$reservation->stat,


            ];
        }
         $room=room::all();
        return view('/MyReservations', ['events'=>$events],compact('room'));
    }




    public function store(Request $request)
    {
        $request->validate([
            'title' =>'required|string',
            'objectif' =>'required|string',
            'room_id' =>'required',



        ]);
        $reservation =reservation::create ([
            'objectif' => $request->objectif,
            'start' => $request->start,
            'end' => $request->end,
            'stat' => $request->stat,
            'user_id' => Auth::user()->id,
            'room_id' => $request->room_id,
        ]);
        return response()->json($reservation);

    }

i'm a beginner and i was follwing a tutorial when I click on a square of the calendar, it shows the bootstrap model (till here everything is fine) once I click on ' save changes' i get this problem I think the problem starts at $.ajax, and the store function in MyController

i don't really know where is the problem i was watching a tutorial and i did exactly the same

Note : My model continues $fillable And i Have three tables ( users , reservations and rooms )

CodePudding user response:

I think basically the issue is that the $.ajax({ command needs to be inside the $('#submit').click(function () { ... }) area. Otherwise it'll run the AJAX command as soon as the selection is made without waiting for the user to enter anything or submit the form.

So that means the variables declared inside that click area, which the AJAX is trying to rely on, won't exist yet, and that would explain the error about "undefined" variables.

It should look like this instead:

select: function(start, end, allDay)
{
  $('#ResModal').modal('toggle');  
  $('#submit').off("click");

  $('#submit').on("click", function () {
    var title = $('#title').val;
    var start = moment(start).format('YYYY-MM-DD');
    var end = moment(end).format('YYYY-MM-DD');
    var objectif = $('#objectif').val;
    var room_id = $('#room_id').val;

    $.ajax({
      url:"{{route('MyReservations.store')}}",
      type:"POST",
      data:{title, start, end, room_id, objectif},
      success:function(response)
      {
        // MyReservations.fullCalendar('refetchEvents');
        // alert("Added Successfully");
        console.log(response)
      },
    })
  });
}

Note that I also modified the "click" handler slightly and added an .off call just before it. That's so that if you then select another area afterwards, and then another one, it doesn't add more and more "click" handlers without removing the previous ones - because if you didn't remove them, then when the modal is submitted it will run all the added handlers (one for each time there's a selection) and re-submit the earlier event data to the server, resulting in duplicate data being stored.

CodePudding user response:

Your code calendar code looks fine but you are doing a mistake in laravel syntax, you are returning two arrays using array and compact both methods. That's why the second variable is not passing correctly.

Solution

return view('/MyReservations', compact('events' ,'room'));

Hope this will solve your issue.

  • Related