Search code examples
phpjqueryarraysajaxcodeigniter

How can I send an array to Codeigniter with jQuery AJAX


I have an array of marks of students :

<span>Teacher Name : </span> <input id="teacher" type="text">
<span>Course Name : </span> <input id="course" type="text">
<table id="students_list">
    <tr>
        <td><span>George</span></td>
        <td><input class="mark-field" type="text" id="1105"/></td>
    </tr>
    <tr>
        <td><span>Danny</span></td>
        <td><input class="mark-field" type="text" id="1351"/></td>
    </tr>
    <tr>
        <td><span>Linda</span></td>
        <td><input class="mark-field" type="text" id="3486"/></td>
    </tr>
    <tr>
        <td><span>Mario</span></td>
        <td><input class="mark-field" type="text" id="9032"/></td>
    </tr>
    …
</table>
<button id="save_marks">SAVE</button>

I use this method to create an array with JQUERY and send it to server :

$(document).on('click', '#save_marks', function () {
    var dataArray = [];
    var i = 1;
    $('.mark-field').each(function () {
        dataArray[i] = {
            'teacher' : $('#teacher').val(),
            'course' : $('#course').val(),
            'mark' : $(this).val(),
            'id' : $(this).attr('id')
        };
        i++;
    });
    dataArray[0] = i;
    $.ajax({
        url: 'save-marks',
        data: {dataset: dataArray},
        type: 'post',
        success: function (res) {
            alert(res);
        }
    });
});

and use this way to change it to PHP (CodeIgniter) array and save it on database :

public function save_marks() {
    $arrayLength = $this->input->post('data')[0];
    for ($i = 1; $i < $arrayLength; $i++) {
        $arr[] = array(
            'TEACHERS' => $this->input->post('dataset')[$i]['teacher'],
            'COURSES' => $this->input->post('dataset')[$i]['course'],
            'MARKS' => $this->input->post('dataset')[$i]['mark'],
            'ID' => $this->input->post('dataset')[$i]['id']
        );
    }
    $this->db->insert_batch('marks_table', $arr);
    die($this->db->affected_rows() . ' marks were saved.');
}

Now my questions :

  • Is there another way to calculate array length on the server side?

  • Is it a good way to build an array both on the server side and on the client side?

    and if no

  • Is there another way to create and send them to the server?

Thanks.


Solution

  • 1. Is there another way to calculate array length on the server side?

    Yes, by using sizeof($array), you can get the array length of the array.

    2. Is it a good way to build an array both on the server side and on the client side?

    Using name="mark-field[]" you can send the mark list without manually construct it in your javascript, also by using sizeof($array) you can get array size in the server side without sending the size from your javascript.

    3. Is there another way to create and send them to the server?

    Personally, I would do something like this:

    <form id = "form_data" method="post">
    <span>Teacher Name : </span> <input id="teacher" name="teacher" type="text">
    <span>Course Name : </span> <input id="course" name="course" type="text">
    <table id="students_list">
        <tr>
            <td><span>George</span></td>
            <td>
                <input name="mark[]" type="text" id="1105"/>
                <input name="mark_id[]" type="hidden" value="1105"/>
            </td>
        </tr>
        <tr>
            <td><span>Danny</span></td>
            <td>
                <input name="mark[]" type="text" id="1351"/>
                <input name="mark_id[]" type="hidden" value="1351"/>
            </td>
        </tr>
        <tr>
            <td><span>Linda</span></td>
            <td>
                <input name="mark[]" type="text" id="3486"/>
                <input name="mark_id[]" type="hidden" value="3486"/>
            </td>
        </tr>
    </table>
    <button id="save_marks">SAVE</button>
    </form>
    

    and the javascript part

    $(document).on('submit', '#form_data', function (event) {
        event.preventDefault();
        var data = new FormData(this);
        $.ajax({
            //fill url with your controller name
            url:"<?php echo base_url(); ?>controllername/save_marks",
            method:"POST",
            data: data,
            async: false,
            processData: false,
            contentType: false,
            cache:false,
            dataType:"json",
            success:function(returndata)
            {
                //do something with your returned data
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.log(xhr.status);
                console.log(thrownError);
            }
        });
    });
    

    and in your controller:

    public function save_marks() {
        $teacher= $this->input->post('teacher',true);
        $course= $this->input->post('course',true);
        //mark & mark_id is an array
        $mark= $this->input->post('mark',true);
        $mark_id= $this->input->post('mark_id',true);
        
        $arr = array();
        foreach($mark_id as $key => $row)
        {
            $arr[] = array(
                'TEACHERS' => $teacher,
                'COURSES' => $course,
                'MARKS' => $mark[$key],
                'ID' => $row
            );
        }
        
        $this->db->insert_batch('marks_table', $arr);
        //die($this->db->affected_rows() . ' marks were saved.');
        
        echo json_encode($arr);
    }
    

    By sending formdata, you wont need to manually construct the array, however since you need to send the mark_id to the controller, you need to add 1 more field to send the mark_id