1

I am working in codeigniter, and using foreach loop in a div to display content of the database here is my code

<?php foreach($values as $row): ?>
<div class="col-xs-6 col-md-3" id="<?php echo $row->album_id ?>">
<?php echo $row->album_name; ?>
</div>
<?php endforeach; ?>

my question is how can I update the value of "$values" using ajax, and how can I refresh the content of this div.

2
  • you would need to write some client side code that sends an ajax request to the server and some server side code that responds with the data you require Commented Mar 25, 2014 at 17:02
  • I know how to write ajax, I want to know how to fetch data in a PHP variable Commented Mar 25, 2014 at 17:04

2 Answers 2

1

Step1: On PHP side add an action for requesting the values:

<?php
$myValues = array(); // maybe from database?
header('Content-type: application/json');
echo json_encode($myValues);
?>

This is your controller action for sending JSON data to the client side.

Step2: On client-side: (a) add jQuery and then (b) do a ajax call to fetch the data from your action above, like so:

$.getJSON( "index.php?getValueAction", function( data ) {
   alert(data);

   // to access the individual properties you would do
   alert(data.property); 

   // use jquery selectors to target the element, where you want the content
   $("#myDiv").append(...);
   // you should create a proper html element before inserting it :)
}

The first argument of the getJson() call depends on your Codeigniter routing configuration. Some have /index/forum/show, others have index.php?controller=forum&action=show. Insert the URL style you use, to make the request to CI.

The this answer does the iteration on client-side JS and prepares a dom-element for insertion, right.

-- An alternative would be to keep the PHP part like you have it and send the whole HTML part over on an AJAX request. That's not very nice, but works. Then it's a basic Ajax Get request to the controller/action providing the HTML fragment.

$.get( "URL", function( data ) {
   $("#myDiv").html( data );
});
Sign up to request clarification or add additional context in comments.

1 Comment

np. You're welcome. I've added an alternative way of solving the problem.
0

You can also use jquery DataTables with server side processing (using Ajax). There are some great examples on the data tables site.

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.