I have a problem with my JQuery, Ajax, and PHP code.
I have a page containing all the post from a user.
Then in this page, I want to load the latest comment for that post by using Ajax.
However it doesn't show up anything.
Here is the PHP code where I called the JQuery function:
<? foreach($post_query as $post_row){ ?>
<li class="post_list">
<?php echo $post_row['text'];?>
<br/>
Latest Comment:
<br/>
<script type="text/javascript">
var post_id = $('#post_id_<?php echo $post_row['id'];?>').val();
document.write(post_id);//just to check that post_id value is not undefined
$(function(){
$.getJSON("<?php echo base_url();?>postC/latest_comment", {post_id: post_id},
function(res){
$("#result").prepend(res.text);
});
});
</script>
<? } ?>
And this is my PHP Code Igniter Controller that handle the request:
class postC extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('models_facade');
$this->load->Database();
$this->load->helper('url');
$this->load->helper('form');
$this->load->library('tank_auth');
$this->load->library('user_session_lib');
error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));
}
function latest_comment(){
$post_id = $this->checkValues($_GET['post_id']);
$latestcomment = $this->models_facade->getLatestCommentForPost($post_id);
return json_encode($latestcomment);
}
}
I have tested to call the function manually and display the latest comment without using ajax, and it worked. So this means that there is nothing wrong with the back end function in the modelthat retrieve the result from mysql.
I have also tried to do :
echo json_encode($latestcomment);
when trying to call the function manually, and I could see that the data was in JSON format.
So this means, that there is something wrong with the ajax call, that it did not get the data from the controller. I used GET for .getJSON, and POST for .post() and .ajax().
I have tried all versions of the jQuery Ajax call: .getJSON(), .post(), and .ajax() , and none of it worked. I am sure that the corresponding Jquery libraries have been loaded properly, since all my other ajax functions could work properly.
Does anyone has any clue where the errors could be? I have been debugging this for one full day, and got no result.
Thanks