OK, so CodeIgniter is a PHP framework - which means it works server-side. (I know, there's an ajax library in there, but I don't use that.) We have to understand the difference between server-side and client-side. Your javascript is client-side. I usually develop everything without javascript to begin with in codeigniter, then go back and add the javascript bits. This helps me to ensure that the system works for those that don't have javascript turned on, or can't execute javascript for whatever reason. (BTW, this is called progressive enhancement).
So, first, let's take care of the non-javascript version:
You just need to give your red/green button a url when clicked that points to the controller method that will update the database record and redirect you back to the page that you were previously on (which has the red/green buttons).
/controller/method.html is our controller method that will save to the database and redirect back to this page. -->
<a href="/controller/method.html" class="red my-button">Check</a>
Now, let's take care of the js version:
in your view, you just need to hijack the click, send the ajax request, and change the red/green button based on the result from the controller method. So, what we do is keep the link from redirecting the page to the href attribute (e.prevendDefault()). Then, we get the value of the href and make an ajax call to that controller method. The method will determine if this is an ajax request and save to the database, then echo back a "success" message. On success, we can update the visual component on the client side.
$('.my-button').live('click', function(e) {
e.preventDefault();
$.ajax({
// $(this).attr('href') gets the value of the links href attribute
// which is "/controller/method.html" in this case
url: $(this).attr('href'),
success: function(data) {
// update your button with whatever html to write the new button
$('.my-button').replaceWith('<a href="/controller/method.html" class="red my-button">Check</a>');
}
});
});
Your controller method just checks if it is an ajax request or not. If so, just returns success, if not redirects the page.
function my_controller_method()
{
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
$_SERVER['HTTP_X_REQUESTED_WITH']=="XMLHttpRequest") {
// update your database
echo "success";
}else{
// redirect back to page
redirect($_SERVER[‘HTTP_REFERER’]);
}
}