Search code examples
javascriptphpajaxgetjson

How can I pass multiple data from PHP to jQuery/AJAX?


I have a main select list of courses which drives various things on a page. When a course is selected another select list will be repopulated with the start date of that course up to 6 months in advance. Also, I have a table on the page with the students name and phone number, when a course is selected, the table will be repopulated with all the students enrolled onto that course. My problem is I will be getting various different things from PHP via JSON i.e. the students and the starting date. How can I therefore pass more than one thing to jQuery? What if the course select list affected not just 2 things but 3, 5 or even 10? How would we handle that with PHP and jQuery?

foreach($m as $meta)
{
        $metaCourse = $this->getCourseInfo($meta['parent_course']);

        //populate the select list with the name of each course
        $metaSelectList .= '<option id="select'.$count.'" value="'.$metaCourse['id'].'">'.$metaCourse['fullname'].'</option>';
        $count++;

        //get only the first course's dates
        if($count3 == 1)
        {
                $startDate =  intval( $course->getStartDate(50) );
                $endDate =  strtotime('+6 month', $startDate);

                //populates the select list with the starting date of the course up to the next six months
                for($date = $startDate; $date <= $endDate ; $date = strtotime('+1 day', $date))
                {
                        $dateSelectList .= '<option id="select'.$count2.'" value="'.$date.'">'.date('D d F Y', $date).'</option>';
                        $count2++;
                }
                $count3++;
                $students = $s->getStudents($metaCourse['id']);
                $content = $this->createStudentTable($students);

        }
}

This is my handler for the AJAX...FOR NOW (I haven't implemented the students table yet as I'm still trying to figure out how to pass multiple pieces of data to jQuery). Basically each time a course is selected, PHP creates a new select list with the appropriate dates and then passes it to jQuery. I'm not sure if I should do this in JavaScript or in PHP.

if (isset($_GET['pid']) && (isset($_GET['ajax']) && $_GET['ajax'] == "true"))//this is for lesson select list
{
        $pid = intval( $_GET['pid'] );
        $c = new CourseCreator();
        $startDate =  intval( $c->getStartDate($pid) );
        $endDate =  strtotime('+6 month', $startDate);
        $dateSelectList = '<select name="dateSelect" id="dateSelect">';

        //populates the select list with the starting date of the course up to the next six months
        for($date = $startDate; $date <= $endDate ; $date = strtotime('+1 day', $date))
        {
                $dateSelectList .= '<option id="select'.$count2.'" value="'.$date.'">'.date('D d F Y', $date).'</option>';
                $count2++;
        }

        $dateSelectList .= '</select>';

        echo json_encode($dateSelectList);
        exit;
}

My jQuery handler:

$('#metaSelect').live('change', function()
{
    $.getJSON('?ajax=true&pid='+$('#metaSelect').val(), function(data)
    {           
        alert(data);
        $('#dateSelectDiv').html(data);
    }); 

});  

Solution

  • You can easily pass ALOT of data from PHP to your HTML via JSON (which you seem to of put in basic already)

    However to expand on what you have - heres a quick example

    <?php
       $arrayOfStuff = array("theKey" => "theEntry", 123 => "Bob Dow", 56 => "Charlie Bronw", 20 => 'Monkey!', "theMyID" => $_POST['myID']);
       echo json_encode($arrayOfStuff);
    ?>
    

    On your HTML side.

    <script> 
       $.post("/theurl/", {type: "fetchArrayOfStuff", myID: 24}, function(success) {
           //your success object will look like this
           /*
              {
                 theKey: 'theEntry',
                 123: 'Bob Dow',
                 56:  'Charlie Bronw',
                 20:  'Monkey!',
                 theMyID: 24
              }
           so you can easily access any of the data.
                      alert(success.theKey);
                      alert(success[123]);
                      alert(success[56]);
                      alert(success[20]);
                      alert(success.theMyID);
    
           */
    
           //we can iterate through the success JSON!           
           for(var x in success) { 
               alert(x + "::" + success[x]);
           };
       }, "json");
    </script>
    

    In the long run - your MUCH better of letting the backend do the backend stuff, and the front end doing the front-end stuff.

    What this means is, try keep the HTML generation as far away as possible from the back-end, so instead of constantly passing

        for($date = $startDate; $date <= $endDate ; $date = strtotime('+1 day', $date))
        {
                $dateSelectList .= '<option id="select'.$count2.'" value="'.$date.'">'.date('D d F Y', $date).'</option>';
                $count2++;
        }
    

    You could perhaps

        $date = $startDate;
        $myJson = array()
        while($date <= $endDate) {
            $myJson[] = array("date" => $date, "formattedDate" => date('D d F Y', $date));
            $date += 86400; //86400 is the value of 1 day.
        }
        echo json_encode($myJson);
    

    And you can just do a simple iteration on your HTML code.

    <script> 
       $.get("/", {ajax: true, pid: $('#metaSelect').val()}, function(success) {
    
    
           //we can iterate through the success JSON!           
           var _dom = $('#dateSelectDiv').html(''); //just to clear it out.
    
           for(var x in success) { 
              _dom.append("<option value='"+success[x].date+"'>"+success[x].formattedDate+"</option>");
           };
       }, "json");
     </script>
    

    So as you can see - you can pass alot of data using JSON

    Maybe look at some of the documentation to - http://api.jquery.com/jQuery.get/ , http://api.jquery.com/jQuery.post/ - might give you more ideas.

    Best of luck to you