Mike Wood Mike Wood - 7 months ago 10
Javascript Question

Return multiple duplicate Keys in PHP to json AJAX response

Pretty comfortable with PHP but fighting with jQuery.
I have a bootstrap modal that is used for editing a project and I'm using AJAX to populate the fields when an edit button is clicked. This works great but a project can be in multiple departments (checkboxes in the modal)

This is how I'm populating the modal:

$.ajax({
url: 'project_tasks.php?task=select_project&pjct_id=' + id,
method: 'GET',
dataType: 'json'
}).success(function(response) {
// Populate the form fields with the data returned from server
$('#edit_project')
.find('[name="project_id"]').val(response.project_id).end()
.find('[name="project_title"]').val(response.project_title).end()
.find('[name="project_bgcolor"]').val(response.project_bgcolor).end()
.find('[name="project_desc"]').val(response.project_desc).end()
.find(':checkbox[name^="department"]').each(function () {
if($(this).val() == response.dpmt_id) {
console.log("depart: " + response.dpmt_id);
$(this).prop('checked', true);
}
});
});


And the PHP is (not escaping yet but will do):

$pjct_id = $_GET['pjct_id'];
$pjct = Projects::find_by_id($pjct_id);

$dpmts = Projects_departments::find_all_by_pjct_id($pjct_id);
foreach ($dpmts as $dpmt) {
$response_array['dpmt'] = $dpmt->department_id;
}
$response_array['project_id'] .= $pjct->id;
$response_array['project_title'] .= $pjct->project_title;
$response_array['project_bgcolor'] .= $pjct->project_bgcolor;
$response_array['project_desc'] .= $pjct->project_desc;
echo json_encode($response_array);


Obviously I know that 'dpmt' is being overwritten each time so I only get the json
dpmt : 1
rather than each departments ID but I would like to achieve something like
dpmt: 1, dpmt: 2, dpmt: 3
and then loop through that to tick the checkbox.

Hopefully I've explained myself well enough (The wife is rushing me out)
Thanks in advance.

Answer

The PHP: return an array of ids instead of an integer/string.

...
foreach ($dpmts as $dpmt) {
    $response_array['dpmt'][] = $dpmt->department_id;
}
...

The Javascript: use a combined selector, so you don't have to loop every checkbox. Use the loop only on the dpmt_ids returned by the PHP.

$('#edit_project')
    .find('[name="project_id"]').val(response.project_id).end()
    .find('[name="project_title"]').val(response.project_title).end()
    .find('[name="project_bgcolor"]').val(response.project_bgcolor).end()
    .find('[name="project_desc"]').val(response.project_desc).end()
;
for (i=0; i< response.dpmt_id.length; ++i) {
     $('#edit_project').find(':checkbox[name="department[]"][value="'+response.dpmt_id[i]+'"]').prop('checked',true);
}