tags:

views:

132

answers:

4

I have the following piece of jQuery code:

function saveSchedule()
{
    var events = [];

         $('ul#schedule-list').children().each(function() {
             events.push($(this).attr('value'));
         });

         jQuery.each(events, function()
         {
             alert(this);
         });


         $.post("schedule_service.php?action=save_schedule", 
         { events: events, studentid:  $('#student').val() }, 
         function(data) { 
             alert(data);
         }, 'json');   
     }

Which gets all the 'values' from a list on my page, and puts them into the events array.

Then, below I pass in that array plus a studentid into the data section of my $.post call.

However, when I receive this array on my PHP side, it seems to be a singular value:

<?php

    include_once('JSON.php');
    $json = new Services_JSON();


    if ($_GET['action'] == 'save_schedule')
    {
        $event_list = $_POST['events'];

        echo $json->encode($event_list);
        exit;
    }
?>

(note: I'm using an older version of PHP, hence the JSON.php library.)

Now, all this ever returns is "14", which is the last event in the events array.

Post:
alt text

Response:
alt text

How am I handling passing the array in my $.post wrong?

A: 

You can pass the array elements as a string comprising of all the elements concatenated by a character. Then you can split the array in your php code and extract the values there.

Use join() to join the elements of an array.

join(separator);

separator:

Specifies a string to separate each element of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma.

Use explode() on the PHP side to turn the join()ed string back together.

rahul
A: 

Why not use JSON? Pass the JavaScript array as a JSON object and parse it in PHP.

Traveling Tech Guy
+7  A: 

It may seem silly, but try this:

$.post("schedule_service.php?action=save_schedule", 
         { 'events[]': events, studentid:  $('#student').val() }, 
         function(data) { 
             alert(data);
         }, 'json');

PHP will parse the key name events[] into an actual array inside php automatically...

gnarf
Wow, that worked. I wasn't expecting that. Thanks gnarf.
Mithrax
Great answer @gnarf. If I hadn't tested first I would have beat you to the answer ;) +1
Doug Neiner
@dcneiner - I was 99% sure it would work, since thats what you use for `<select multiple='multiple' name='stuff[]'>` - but since you tested it, *s/should/will/*
gnarf
A: 

Believe it or not, just use 'events[]': events in your $.post request instead of events: events (without the brackets).

Doug Neiner