简体   繁体   中英

my done button somehow went to a blank page and delete won't work unless I refresh -ajax

I am playing around with a todo list I learned online. Trying to add ajax into it. Works well when I try to add an item. When an item is added there's a button says 'Mark as done' so I can click on it and then there will be a 'Delete' button which is used to delete the item from the list and database.

Adding with ajax works fine but after adding, if I click on 'Mark as done' button, the page goes to the url of done-ajax.php?as=done&item=110 where 110 is just the id of the item in database. I have to go back to the index page. And when I go back to index page the item will be marked done already because the 'Mark as done' worked but somehow would go to the url instead of staying in the index page.

This is one of the problems found that I have no idea where to look for the result.

Another problem is if I add the item and refresh the page then clicked 'Mark as done' it wouldn't go to the url instead the ajax works and a 'delete' button would show up but some how the delete button wouldn't work. I have to refresh the page in order for the 'delete' button to work with ajax. I checked the attributes and looked around the codes but couldn't seem to find where is causing the problem.

my index codes are as below

<div class="list">
<h1 class="header">ET's To do lists.</h1>

<?php if(!empty($items)): ?>
<ul class="items">
    <?php foreach($items as $item): ?>
    <li>
                    <span class="item<?php echo $item['done'] ? ' done' : '' ?>">
                        <?php echo $item['todoText']; ?>
                    </span>
        <?php if($item['done']): ?>
        <a href="delete-ajax.php?as=delete&item=<?php echo $item['id']; ?>" class="delete-button">Delete Task</a>
        <?php endif; ?>
        <?php if(!$item['done']): ?>
        <a href="done-ajax.php?as=done&item=<?php echo $item['id']; ?>" class="done-button">Mark as done</a>
        <?php endif; ?>
    </li>
    <?php endforeach; ?>
</ul>
<?php else: ?>
<p class="empty">You haven't added any items yet.</p>
<ul class="items"></ul>
<?php endif ?>

<form class="item-add" action="add.php" method="post">
    <input type="text" name="todoText" placeholder="Type a new item here." class="input" autocomplete="off" required>
    <input type="submit" value="Add" class="submit">
</form>
</div>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="js/ajax.js"></script>

my ajax.js file

$(document).ready(function() {

//Action when submit is clicked
$(".submit").click(function(e){
var todoText = $("input[name='todoText']").val();
e.preventDefault();

//Ajax for adding todoText
$.ajax({
method: "POST",
url: "add-ajax.php",
data: {todoText: todoText},
dataType: "json"
})
.done(function(data){
$('p.empty').empty();
$('input.input').val('');
$('ul.items').append('<li>'+todoText+' '+
    '<a href="done-ajax.php?as=done&item=' + data.id +
                '" class="done-button">Mark as Done</a></li>');
})
});

//Action when done button is clicked
$(".done-button").click(function(e){
e.preventDefault();

//making sure only work with the current element
var $clicked = $(this);

//get the href attribute value and parse it to get the item # which is the item's id
var attrValue = $clicked.attr('href');
var parseAttrValue = attrValue.split('&');
var parseItem = parseAttrValue[1].split('=');
var item = parseItem[1];

//Ajax for Mark as Done Button
$.ajax({
method: "GET",
data:{as: 'done', item: item},
url: "done-ajax.php"
})
.done(function(){
$clicked.prev().addClass('done');
$clicked.removeClass('done-button').empty();
$clicked.addClass('delete-button').text('Delete Task');
$clicked.removeAttr('href');
$clicked.attr('href','delete-ajax.php?as=delete&item='+item);
});
});

//Action when delete button is clicked
$(".delete-button").click(function(e){
e.preventDefault();

//making sure only work with the current element
var $clicked = $(this);

//get the href attribute value and parse it to get the item # which is the item's id
var attrValue = $clicked.attr('href');
var parseAttrValue = attrValue.split('&');
var parseItem = parseAttrValue[1].split('=');
var item = parseItem[1];

//Ajax for Mark as Done Button
$.ajax({
method: "GET",
data:{as: 'delete', item: item},
url: "delete-ajax.php"
})
.done(function(){
$clicked.closest('li').remove();
$clicked.remove();
});
});
});

my done-ajax.php file


<?php

require_once 'app/init.php';

if (isset($_GET['as'], $_GET['item']))
{
    $as = $_GET['as'];
    $item = $_GET['item'];

    switch ($as) {
        case 'done':
            $doneQuery = $db->prepare("
UPDATE phptodolist_items
SET done = 1
WHERE id = :item
AND user = :user
");
break;
}
}


my delete.php file

<?php

require_once 'app/init.php';

if (isset($_GET['as'], $_GET['item']))
{
    $as = $_GET['as'];
    $item = $_GET['item'];

    switch ($as) {
        case 'delete':

            $doneQuery = $db->prepare("
DELETE FROM phptodolist_items
WHERE id = :item
AND user = :user
");
break;
}
}

(By the way, thanks to few that helped out with the ajax earlier) Thanks a lot to everyone in advance :D

You are binding your event handlers when the page opens / the DOM is ready, on $(document).ready() . Then you add new items using ajax but the links in these items will not have your event handlers bound to them.

You can use event delegation to make sure that the events are also automatically bound to newly added items.

You can do that changing:

$(".delete-button").click(function(e){
e.preventDefault();
...

to something like:

$(".list").on('click', '.delete-button', function(e){
  e.preventDefault();
  ...

where the $(".list") can be any element that contains the newly added elements and that is on the page when this code executes.

This applies to all event handlers that you want to bind to elements that are not yet on the page when the DOM is ready.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM