In my cakephp application I am trying to create a commenting functionality. So I use an ajax request to get the comments and then clone an html template and append it to the page:
//load comments
$(document).ready(function(){
$.ajax({
type: 'POST',
url: '/app/tasks/getComments',
datatype: 'json',
beforeSend: function (xhr) { // Add this line
xhr.setRequestHeader('X-CSRF-Token', $('[name="_csrfToken"]').val());
},
data: {
task_id : "<?php echo $task->id; ?>"
},
success: function( data )
{
for (var i=0; i < data.length; i++)
{
//Clone the template
var item = $(template).clone();
document.cookie = 'photos['+i+']='+data[i].user.photo;
document.cookie = 'names['+i+']='+data[i].user.username;
//Find the element
$(item).find('#comment_photo').html('<?php if(isset($_COOKIE["photos[$num]"])) {echo $this->Html->image($_COOKIE["photos[$num]"], ["class" => "avatar avatar-online", "alt" => $currentUser->username]); } ?>');
$(item).find('#comment_username').html('<?php if(isset($_COOKIE["names[$num]"])) { echo $_COOKIE["names[$num]"]; }?>');
$(item).find('#comment_time').html(moment(data[i].created_date, 'DD-MM-YYYY hh:mm:ss').format('MMMM Do YYYY, h:mm:ss a'));
$(item).find('#comment_text').html(data[i].comment);
$(item).find('#comment_id').html(data[i].id);
//Append to the source
$('#target').append(item);
}
}
});
});
In order to access the returned results in php I store them in cookie arrays (photos[]
, names[]
). How I can set and update the value of $num
in order to iterate the arrays in every html code append? Is it possible to achieve what I want with this approach? Or I need a complete new one?