'Pass data from database to AJAX in Codeigniter 3
public function test()
{
$this->load->model('m_comment');
$comment = $this->input->post('comment');
$insert=[
'id_user' => '1092093',
'isi_komentar' => $comment
];
$data['komentar'] = $this->m_comment->getdata('komentar');
$komentar = json_encode($data);
echo $komentar;
$komentar = $this->db->get('komentar')->result();
echo json_encode($komentar);
}
above is the function to get data from ajax and insert it to the database at the bottom section im trying to get data from database and pass it to ajax, it worked perfectly
<body>
<h1>Article</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Accusantium maxime voluptates molestias. Repellendus eum incidunt sed, quae necessitatibus similique eveniet inventore accusantium repudiandae dolorum odio maxime reiciendis debitis aut nobis.</p>
<textarea name="komentar" id="komentar" cols="30" rows="10"></textarea>
<input type="submit" name="submitComment" id="submitComment" value="Submit">
<br>
<p>Comments</p>
<div class="comments"></div>
<br>
<!-- <?php foreach ($komentar as $k):?>
<div id="commenWrapper"><?= '<b>'.$k['id_user'].'</b>' .' '. ':'.' ' .$k['isi_komentar'];?></div>
<?php endforeach;?> -->
<div id="commentWrap"></div>
<script>
$('#submitComment').on('click', function () {
var commentContent = $('#komentar').val();
$.ajax({
method: 'POST',
url: '<?= base_url()."main/test"?>',
data: { comment : commentContent},
success: function (data) {
alert(data);
}
});
});
</script>
here is my ajax code, it worked and it worked perfectly
but somehow when i try to access a spesific data in ajax it return a '[', like it was reading a string
code look like this
<script>
$('#submitComment').on('click', function () {
var commentContent = $('#komentar').val();
$.ajax({
method: 'POST',
url: '<?= base_url()."main/test"?>',
data: { comment : commentContent},
success: function (data) {
console.log(data[0]);
}
});
});
</script>
and the result
logging a spesific index from the array?
if i try to access spesific data with an index
like this
console.log(data[0].id_user);
the return in console is 'undefined'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
