Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Having trouble getting a data array in the correct format for Cakephp in Javascript. I'm making a scheduling calendar using Fullcalendar and I've gotten the events loaded into an array.

The external events are users dragged onto the calendar from another div and they transfer their name and userId. Next, the calendar is initialized and when a user is dropped onto it, the user is displayed on the calendar and added to the arrayOfEvents. This is the variable we're working with.

$(document).ready(function() { 
    /* initialize the external events -----------------------------------------------------------------*/
    $('#external-events div.external-event').each(function() {
        // create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
        // it doesn't need to have a start or end
        var eventObject = {
            title: $.trim($(this).text()), // use the element's text as the event title
            userId: this.id
        };
        // store the Event Object in the DOM element so we can get to it later
        $(this).data('eventObject', eventObject);
        // make the event draggable using jQuery UI
        $(this).draggable({
            zIndex: 999,
            revert: true, // will cause the event to go back to its
            revertDuration: 0  //  original position after the drag
        });
    });
    /* initialize the calendar-----------------------------------------------------------------*/   
    $('#calendar').fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'agendaWeek,agendaDay'
        },
        defaultView: 'agendaWeek',
        editable: true,
        events: [
            <?php foreach ($users as $user) { foreach ($user['Event'] as $event): ?>
            {
                start: '<?php echo $event['start_date']; ?>',
                end: '<?php echo $event['end_date']; ?>',
                title: '<?php echo $event['title']; ?>',
                allDay: false,
                color: '#077169'
            },
            <?php endforeach; } ?>
        ],
        droppable: true, // this allows things to be dropped onto the calendar !!!
        drop: function(date, allDay) { // this function is called when something is dropped
            // retrieve the dropped element's stored Event Object
            var originalEventObject = $(this).data('eventObject');
            // we need to copy it, so that multiple events don't have a reference to the same object
            var copiedEventObject = $.extend({}, originalEventObject);
            // assign it the date that was reported
            copiedEventObject.start = date;
            copiedEventObject.end = (date.getTime() + 3600000) / 1000; // default shift length is 1 hour
            copiedEventObject.userId = originalEventObject.userId;
            copiedEventObject.allDay = false;
            // render the event on the calendar
            // the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
            $('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
            // Push events into array
            arrayOfEvents.push(copiedEventObject); 
            console.log(arrayOfEvents);
        }
    });
});  // End document ready
var arrayOfEvents = [];
var data = {};

function updateSchedule() { // Function clicked on in link to send arrayOfEvents to controller to add to database
    // You can get all events out of the array here
    for (var i = 0; i < arrayOfEvents.length; i++) {
        var event = arrayOfEvents[i];
        data += "Event" + i
                + "&user_id=" + event.userId
                + "&start_date=" + event.start
                + "&end_date=" + event.end
                + "&title=" + event.title;
    }
    // Make your ajax post here
    $.ajax({
        type: "POST",
        url: "<?php echo $this->webroot; ?>events/add",
        data: data,
        success: function(response) {
            alert('done!');
        },
        fail: function(response) {
            alert("error");
        }
    });
}

The updateSchedule function is tied to an onClick event and is submitting to the view, but not in the correct format. I need the array to look like this:

Array
(
    [Event] => Array
    (
        [0] => Array
        (
            [user_id] => 'value'
            [start_date] => 'value'
            [end_date] => 'value'
            [title] => 'value'
        ),
        [1] => Array
        (
            [user_id] => 'value'
            [start_date] => 'value'
            [end_date] => 'value'
            [title] => 'value'
        )
   )
)

Currently it looks like:

array(
    'Event' => 'Event0',
    'user_id' => '4',
    'start_date' => 'Tue Apr 30 2013 11:30:00 GMT-0400 (Eastern Daylight Time)',
    'end_date' => 'Tue Apr 30 2013 12:30:00 GMT-0400 (Eastern Daylight Time)',
    'title' => 'value'
)

I'm a bit lost at how to change this to my desired format.

share|improve this question
    
what your current array looks like is not a valid array format for javascript. There is no way to parse that with javascript (if that's the actual format) because it will throw a syntax error. –  ryan Apr 29 '13 at 15:32
    
Is this supposed to submit the data in JSON format? It looks like it's just posting a query string. Your updateSchedule() function is added to the data string which isn't defined in the function. –  nullability Apr 29 '13 at 15:53
    
@nullability Currently the controller doesn't do anything but respond with a debug for the data. I was hoping to just submit all the data pre-configured for the Data format required by CakePHP. How would I submit it in JSON format so CakePHP would recognize it? –  Chris Apr 29 '13 at 16:30

1 Answer 1

up vote 1 down vote accepted

It looks like you would need to represent the structure in Javascript is with combination of objects and arrays, and then output it to JSON. Your data variable should be constructed as an object like this:

var data = {};
for (var i = 0; i < arrayOfEvents.length; i++) {
    var event = arrayOfEvents[i],
        eventId = "Event" + i,
        eventData = {};
    if (!data[eventId]) data[eventId] = [];

    eventData['user_id'] = event.userId;
    eventData['start_date'] = event.start;
    eventData['end_date'] = event.end;
    eventData['title'] = event.title;

    data[eventId].push(eventData);
}

Then the $.ajax call can handle converting it to json if you set dataType: "json":

$.ajax({
    type: "POST",
    url: "<?php echo $this->webroot; ?>events/add",
    data: data,
    dataType: "json",
    success: function(response) {
        alert('done!');
    },
    fail: function(response) {
        alert("error");
    }
 });

The controller would then have to decode the JSON string and convert it to your desired PHP array. See this question to learn how to set that up: How do I handle json data sent as an HTTP Post to a cakephp app?

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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