1

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!

2 Answers 2

1

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;",
); ?>
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.