0

I am trying to catch data from Ajax in Laravel controller to save it. But I keep getting error as seen image below. What am I doing wrong here?

Laravel Controller@ajaxstore

public function ajaxstore(Request $request)
{

    //Event::create($request->all());
    //return (gettype($name));
    $data = $request->all();
    //$newdata =array_keys($data);
    $data= json_decode($data,true);
    $event = New Event;        
    $event->name = $data['name'];
    $event->description = $data['description'];
    $event->start = $data['start'];
    $event->end = $data['end'];
    $event->color = $data['color'];
    $event->save();
}

My jquery

$('#calendar').fullCalendar({
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    events: '/admin/event-list/' + roomId.val(),
    //events: JSON.parse(json_events),
    defaultView: 'agendaWeek',
    editable: true,
    selectable: true,
    timezone: 'local',
    select: function(start, end, jsEvent, view) {
        endtime = end.format('LLLL');
        starttime = start.format('LLLL');
        room_id = roomId.val();
        var mywhen = starttime + ' - ' + endtime;
        startTime.val(start);
        endTime.val(end);
        $('#dayClick #when').text(mywhen);
        $("#dayClick").modal("show");
        $('#submitButton').on('click', function(event){
            console.log("clicked");
            if(createEvent.valid()){
                // We don't want this to act as a link so cancel the link action
                if(doSubmit(start, end))
                {

                    $("#dayClick").modal('hide');
                    // remove previous entry
                    $("#createEvent").each(function(){
                        this.reset();
                    });
                    console.log($('#apptStartTime').val());
                    console.log($('#apptEndTime').val());
                    // enter to the calender
                    $("#calendar").fullCalendar('renderEvent',
                        {
                            title: $('#createEvent #event-name').val(),
                            start: new Date($('#apptStartTime').val()),
                            end: new Date($('#apptEndTime').val()),
                        },
                        true);
                    console.log("after renderEvent");

                }
                else
                {
                    console.log("failed");
                };
            }
            event.preventDefault();
        });

        //return eventData;
    },
    eventClick: function(event, jsEvent, view) {
        $('#modalTitle').html(event.name);
        $('#modalBody').html(event.description);
        $('#eventUrl').attr({'href':'event/'+event.id,'target':'_self'});
        $('#fullCalModal').modal("show");
    }
});

function doSubmit(start, end){
    console.log("inside dosubmit");
    eventData.name = eventName.val();
    eventData.description = description.val();
    eventData.capacity = capacity.val();
    eventData.room_id = roomId.val();
    startDate =  moment(start.format("YYYY-MM-DD HH:mm:ss"));
    eventData.start = startDate;
    endDate =  moment(end.format("YYYY-MM-DD HH:mm:ss"));
    eventData.end = endDate;
    eventData.color = color.val();
    console.log("inputdata: " + JSON.stringify(eventData));
    $.ajax({
        type: 'POST',
        url:'/admin/event-ajaxstore',
        //url: '/admin/event-ajaxstore',
        data: JSON.stringify(eventData),
        success: function(response){
            //event.id = response.eventid;
            console.log("returned : " + typeof(response));
            /* $('#calendar').fullCalendar('updateEvent',event); */ 
            /* //json_events = response; */
            /* console.log("data: " + data); */
            return true;
        }
    });


}

enter image description here

When I run this in the contoller;

    $data = $request->all();
    return (json_decode($data));

I get the following error.

local.ERROR: ErrorException: json_decode() expects parameter 1 to be string, array given in /Users/sokada/Code/backpack-aktiv/app/Http/Controllers/Admin/EventController.php:39

1
  • I spent hours trying to get Laravel JSON POST testing, and my controller, and a front-end that used stringify. I eventually gave up and changed the front-end to not send stringify and all my problems were solved. Commented Apr 4, 2020 at 7:15

1 Answer 1

2

Your issue is that $request->all() already returns an array. So you dont need the json_decode()

$data = $request->all();
$data= json_decode($data,true);  // remove this, you don't need it here

Do keep in mind though that $request->all() is going to return ALL variables. which may or may not be what you expect

If it were me, I would send my data like this:

data: JSON.stringify({eventData:eventData}),

Then I would access it in my controller like this:

$data = $request->input('eventData');

Sign up to request clarification or add additional context in comments.

3 Comments

This gives an error, "Call to a member function input() on array".
@shin can you show the full new code? $request shown in your code above is definitely a std class object and not an array, seems somehow in your new code, you have cast $request to an array or overwritten the variable
Are you sure you didnt mistakenly type $request->all()->input(), that would cause that error

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.