Call PHP function at the click of a button

2

Good! I'm trying to call a PHP function at the click of a button. My solution so far:

<?php
    $result = getResult($mysqli,"SELECT * from todos WHERE sender = '$username' AND status = '$value' AND journal = '$journal' ORDER BY expiration_date");

    while($row = $result->fetch_array()){
        $receiver = $row['receiver'];
        $sender = $row['sender'];
        $title = $row['title'];
        $todo_text = $row['todo_text'];
        $status = $row['status'];
        $expiration_date = $row['expiration_date'];
        $todo_id = $row['todo_id'];
?> 

<div class="toDo"><b><?php echo $title; ?></b> 
    <ul class='date'>
        <li><img src="icons/date.png" style="width:60px;"></li>
        <li><?php echo "Due " . $expiration_date ?></li>
    </ul>
    <ul>
        <li><?php echo $todo_text; ?></li>
        <li><i><?php echo "assigned to ".$receiver." by ".$sender;?></i></li>
    </ul>

    <?php if($value == 'pending'){?>
    <?php
            if(isset($_POST['delete_x'])){ 
                $todo_id = $_POST['todo_id'];
                deleteToDo($mysqli,$todo_id,$journal);
                exit();
            }

            if(isset($_POST['markAsDone_x'])){ 
                $todo_id = $_POST['todo_id'];
                markToDoAsDone($mysqli,$todo_id,$journal);
                exit();
            }
    ?>
    <form method ="POST" action="">
        <input type="hidden" name="todo_id" value="<?php echo $todo_id ?>"/>
        <input type="image" name = "delete" src="icons/delete.png" style="width:20px"/>
        <input type="image" name = "markAsDone" src="icons/done.png" style="width:20px"/>
    </form>

    <?php } ?>

</div>
<hr> 
<?php 
    } 

This works. I'm running a while loop, so this code is being run multiple times. On my site, I have a page that lists different 'To Do's', and each has a 'Delete' button and a 'Mark as Done' button. However, when I click on one of these buttons, I have to refresh my page so that it gives me the To Do's listing. For example: I want to delete the third To Do from the list. I click on the 'Delete' button of the third To Do, but for some reason the page shows me the FIRST whole of the while loop. If you refresh the page, I already see the updated list without that same To Do. That is: the connection to the database is done successfully, but at the moment after clicking on the image should appear the already updated list of To Do's, but simply appears me the FIRST To Do's while. The action is successful, but the process is not smooth for the user! The page should be updated right after the Delete button!

I've still tried using a header ('location: MY PAGE') before the exits, but to no avail.

Listing before performing the 'Delete' action:

Whatappearsafterclickingonthe'Delete'iconofthethirdToDo: Any suggestion? Thanks:)

    
asked by anonymous 03.11.2016 / 13:48

1 answer

1

No Ajax

Following your template (the page refreshes when the button is clicked):

<?php
if(isset($_POST['delete_x'])) { 
    $todo_id = $_POST['todo_id'];
    deleteToDo($mysqli,$todo_id,$journal);
}

if(isset($_POST['markAsDone_x'])){ 
    $todo_id = $_POST['todo_id'];
    markToDoAsDone($mysqli,$todo_id,$journal);
}

$result = getResult($mysqli,"SELECT * from todos WHERE sender = '$username' AND status = '$value' AND journal = '$journal' ORDER BY expiration_date");

while ($row = $result->fetch_array()):
        $receiver = $row['receiver'];
        $sender = $row['sender'];
        $title = $row['title'];
        $todo_text = $row['todo_text'];
        $status = $row['status'];
        $expiration_date = $row['expiration_date'];
        $todo_id = $row['todo_id'];
?> 

<div class="toDo"><b><?php echo $title; ?></b> 
    <ul class='date'>
        <li><img src="icons/date.png" style="width:60px;"></li>
        <li><?php echo "Due " . $expiration_date ?></li>
    </ul>
    <ul>
        <li><?php echo $todo_text; ?></li>
        <li><i><?php echo "assigned to ".$receiver." by ".$sender;?></i></li>
    </ul>

    <?php if($value == 'pending'): ?>
    <form method ="POST" action="">
        <input type="hidden" name="todo_id" value="<?php echo $todo_id ?>"/>
        <input type="image" name = "delete" src="icons/delete.png" style="width:20px"/>
        <input type="image" name = "markAsDone" src="icons/done.png" style="width:20px"/>
    </form>
    <?php endif; ?>

</div>
<hr> 
<?php endwhile; ?>

I just moved markToDoAsDone and deleteToDo to top of code, before to perform the query again.

With Ajax

It would be interesting to use ajax, so the page would not need to update, but would involve javascript (in case I'm using jQuery).

The form would look like this:

<form>
    <input type="hidden" name="action" value="" />
    <input type="hidden" name="todo_id" value="<?php echo $todo_id; ?>" />
    <input type="image" name="delete" src="icons/delete.png" style="width:20px"/>
    <input type="image" name="markAsDone" src="icons/done.png" style="width:20px"/>
</form>

When the buttons were clicked:

$(document).on('click', '[name=delete], [name=markAsDone]', function(e) {
    // Capturamos o valor de name do botão.
    var actionValue = $(this).attr('name');

    // Atualizamos o valor do action.
    $(this).siblings('[name=action]').val(actionValue);

    // Enviamos o form.
    $(this).parent().submit();

    e.preventDefault();
});

// Quando o form for enviado.
$(document).on('submit', '.toDo form', function(e) {
    var form = $(this);

    $.ajax({
        url: 'url.php',
        method: 'POST',
        data: form.serialize(),
        dataType: 'json',
    }).done(function(r) {
        // resposta aqui.. exemplo:
        if (r.type == 'delete') {
            form.parents('div.toDo').fadeOut(300, function() {
                // Ele vai desaparecer em 300ms e depois
                // será removido.
                $(this).remove();
            });
        }
    });

    // Impedimos o envio padrão.
    e.preventDefault();
});

You could create a php file just to handle ajax calls (my preference), or use the same page yourself:

<?php
    if (isset($_POST['action'])) {
        $todo_id = $_POST['todo_id'];
        $resp = array(
            'type' => ''
        );

        switch ($_POST['action']) {
            case 'delete':
                $resp['type'] = 'delete';
                deleteToDo($mysqli, $todo_id, $journal);
            break;

            // Outros cases aqui...
        }

        echo json_encode($resp);
        die();
    }
?>

Note that jQuery.ajax has two other callbacks: fail and always . The callback fails, as the name says, will be called if an error occurs.

The callback always will always be called, with or without error. You can read more about api ajax here .

I've been doing the head code, I've reviewed it and I think it's going to work, it's just that now there's no way I can test it, and.

    
03.11.2016 / 15:56