JQuery + AJAX remove anchor not working
Hi I am using jQuery and Codeigniter. I am creating a simple to-do list that can add delete entries using ajax.
The problem is that whenever I click on my delete anchor, it doesn't delete the entry. Adding recording function works BTW.
Here's my code:
todo_view.php
<html>
<head>Todo List</head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function() {
var msg = $('#message').val();
$.post("<?= site_url('todo/add') ?>", {message: msg}, function() {
$('#content').load("<?= site_url('todo/view/ajax') ?>");
$('#message').val('');
});
});
$('a.delete').click(function() {
var id = $('input', this).val();
$.post("<?= site_url('todo/delete') ?>", {todoid: id}, function() {
$('#content').load("<?= site_url('todo/view/ajax') ?>");
});
});
});
</script>
<body>
<div id="form">
<input type="text" name="message" id="message" />
<input type="submit" name="submit" id="submit" value="Add todo" />
</div>
<div id="content">
<?php $this->load->view('message_list'); ?>
</div>
</body>
</html>
message_list.php
<ol>
<?php foreach ($todolist as $todo): ?>
<li>
<?php echo $todo->todo; ?>
<a href="#" class="delete"><input type="hidden" value="<?=$todo->todoid ?>" />delete</a></li>
<?php endforeach; ?>
</ol>
Why isn't it working?
a source to share
First of all, in order to keep track of headers and GET / POST values, you must start using Firebug (Firefox extension). Actually your life is simplified in terms of debugging ajax calls and responses.
Next (somewhat in line with what alimango mentioned) ... the most likely reason is that the message list is being loaded AFTER your main DOM page has already loaded. jQuery will not automatically bind the click event to elements added later. The click binding routine should be called AFTER the message list has been added to the DOM. Now this is not always possible ... since your list is fetched / modified dynamically.
One solution is to use the live () function , which has been introduced since jQuery 1.3 . It helps to bind a handler to an event (like click) for all current and future element . Can also bind custom events. For more information see http://docs.jquery.com/Events/live#typefn
The second solution is to use LiveQuery , a jQuery plugin that " harnesses the power of jQuery selectors by binding events or automatically activating callbacks for matched elements, even after the page has loaded and the DOM has been updated." You can get it from http://plugins.jquery.com/project/livequery
Cheers, Microscopic ^ earthling
a source to share