0

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?

4 Answers 4

8

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...

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

2 Comments

Great answer @gnarf. If I hadn't tested first I would have beat you to the answer ;) +1
@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/
0

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

Comments

0

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.

Comments

0

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

Comments

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.