whispersan
whispersan

Reputation: 1039

Codeigniter, jQuery and Ajax - Preventing Page Refresh on Displaying New Database Content Dynamically

I'm trying to achieve something relatively straightforward - allow users to make comments on a view page, update the database and display the new content dynamically on the page without the whole page refreshing.

My efforts so far have been unsuccessful - there may be several issues with what I'm doing!

On the view page I have tried this (to send 2 variables to a CI controller function):

<script type="text/javascript">
function ajax(id, user_id) {
jQuery('#dynamicdiv').load('/controller/function/' + id + '/' + user_id);
}
</script>

<div id='dynamicdiv'>
</div>

I have a textarea to collect the user comment, in the controller function should I be able to call this as post data in order to write it to the database? If so, I would still need to send two other variables ($id and $user_id) to the ajax function.

<?php $atts = array (
  'class' => "alignright button",
  'onClick' => "ajax('$id,$user_id')",
  ); ?>
<?php echo anchor(current_url(), 'Post my Comment', $atts); ?>

and in the controller, which involves a different function (view) than the page I want the user to stay on:

$data = $this->model->database_query($id, $user_id);

echo $data; // from reading other posts it seems I would process the data within this function, to have it displayed on the page the user is viewing?

Any help appreciated!

Upvotes: 1

Views: 1768

Answers (2)

Shibbir Ahmed
Shibbir Ahmed

Reputation: 1350

you can make the ajax request as follows:

function ajax(id, user_id) {
    $.ajax({
        url: base_url + controller_name + '/' + action_name,
        type: 'GET',
        data: { id: id, user_id: user_id },
        dataType: 'json',
        success: function (data) {
            // append the returned result to your #dynamicdiv
        }
    });
}

and in the controller:

$id = $this->input->get('id');
$user_id = $this->input->get('user_id');

$data = $this->model->database_query($id, $user_id);
echo json_encode($data);

Hope this helps

Upvotes: 0

Shomz
Shomz

Reputation: 37711

Don't forget to block you default anchor behaviour (for example by adding return false; to your onclick parameter).

<?php $atts = array (
'class' => "alignright button",
'onClick' => "ajax('$id,$user_id'); return false;",
); ?>

Upvotes: 1

Related Questions