Hi guys, so i have a table populated by event details from database and i use a checkbox to select which event to be deleted:

echo 
"<tr>
    <td><input type='checkbox' name='check[]' class='check' value='$id'>$name</a></td><td>$formatDate</td>
</tr>";

my delete function:

<?php
if(isset($_SESSION['sess_user_id']))
{
    if(isset($_POST['del_event']) && isset($_POST['check']))
    {
        require "connection.php";
        $userid = $_SESSION['sess_user_id'];
        foreach($_POST['check'] as $del_id)
        {
            $del_id = (int)$del_id;
            $sqlqueer = "DELETE FROM event WHERE event_id IN ($del_id) AND euser_id IN ($userid)";
            $deletion = $dbh->query($sqlqueer);
            if($deletion)
            {
                echo "<script type='text/javascript'>window.location.href='event.php';</script>";
            }
        }
    }
}
?>

and it works fine. I wanna know how to call that delete function after a confirm dialog, something like this?

<script type="text/javascript">
$(".del_single_event").live("click", function(){
    var r = confirm("Are you sure ?");
    if(r)
    {
        $.ajax({
            type: 'GET',
            url: 'DelEvent.php',
            data: //how do i get the data?
            success: function(data){
                alert("Deleted!");
            }
        )};
    }
});
</script>

but how do i get the data?

TIA!

You can send the data using a query string:
url: 'DelEvent.php?var1='+var1+'&var2='+ var2;
and so on

Member Avatar for diafol

First thing - don't use a loop to run multiple queries - use a loop or an array function to build the sql and then run a single query.

Second - never use GET to send info that will insert/update or delete data - always use POST. GET is the preferred method for retrieving info (e.g. SELECT statments). You are using POST in your PHP, so GET method in your js wouldn't work anyway.

Third - do not use mysql_* functions - they have been deprecated for some time. Change over to PDO or mysqli.

Fourth - I believe that '.on' is the most recent way to run a jquery '.live' event. I'm no jQ guru, so I may be wrong on that.

okay i've changed it to a prepared statement. yes .on is the newest but im using n old js version. will upgrade it later on.

Member Avatar for diafol

Ok, so does it work now or do you need further help?

im still trying to figure out how to get the data. as tapananand suggested -> url: 'DelEvent.php?var1='+var1+'&var2='+ var2;

so im figuring that out.

im still stuck. i dont get it. is there a tutorial of some kind that could explain things step by step. I know API docs explain but their examples are fixed data and stuff and i have no clue how to modify it.

i did:

$(document).ready(function(){
    $("#del_event").live("click", function(){
        var events = $("input[name=event_id]").val();
        alert(events);<= SCRIPT AFTER THIS LINE IF NOT COMMENTED OUT  
        NOTHING WORKS, IF AFTER THIS LINE COMMENTED OUT ALERT POPS WITH 
        EVENT ID
        var confirmation = confirm("Are you sure ?");
        if(confirmation == true)
        {
            $.ajax
            ({
                type = "post",
                url = "EMS/DelEvent.php",
                data = events,
                success: function(){
                    alert("event deleted!");
                }
            });
            return false;
        }
    });
});

not sure if i did it right.

Member Avatar for diafol

You don't say if it works or not

right sorry. no it does not work. the whole code that i posted does not even read. unless i comment out the part after var confirmation ....., the alert will pop up but when i leave the code as it is without commenting out any part of the script it isn't read. im definitely doing something wrong.

Did you try like this?

$(document).ready(function(){
    $("#del_event").live("click", function(){
        var events = $("input[name=event_id]").val();
        alert(events);

        if(confirm("Are you sure ?"))
        {
            $.ajax
            ({
                type = "post",
                url = "EMS/DelEvent.php",
                data = events,
                success: function(){
                    alert("event deleted!");
                }
            });
            return false;
        }
    });
});

i just did and it is still the same

unless i comment out the part after if(confirm)..., the alert will pop up but when i leave the code as it is without commenting out any part of the script it isn't read.

maybe something in the page is messing it up.

i got this to show the confirm dialog:

$(document).ready(function(){
   $("#del_event").live("click", function(){
        var events = $("input[name=event_id]").val();
        if(confirm("Are you sure ?"))
        {
            $.ajax
            ({
                 type : "post",
                 url : "EMS/DelEvent.php",
                 data : events,
                 success: function(){
                   alert("event deleted!");
                 }
            });
            return false;
        }
    });
});

it doesn't delete but it does alert("event deleted!"). probably my DelEvent.php which i did like this:

<?php

$id = $_POST['events'];

require "connection.php";

$sqlqueer = $dbh->prepare("DELETE FROM event WHERE event_id = ?");
$sqlqueer->bindParam(1, $id, PDO::PARAM_INT);
$sqlqueer->execute();
?>

is that wrong?

problem : data :events,

should be: data : {events : events}

but it is deleting the wrong event.

this is what im trying to delete:

<input type='hidden' name='event_id' value='$id'>
<input type='checkbox' name='check[]' class='check' value='$id'>&nbsp;
<a href= '#' id='e_n' value='$id' name='e_n'>$name</a></td>

something like:

|Event Name |
|checkbox event_name |

Member Avatar for diafol

There seems to be a lot of stuff here that you probably don't need. Here's an example of a simple ajax delete routine:

<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
</head>
<style>
    table{
        border-collapse:collapse;   
    }
    tr th, tr td{
        border: black solid 1px; padding: 4px;  
    }
    tr:last-child td{
        text-align: right;  
    }
</style>
<body>

<form>
<div id="deleteMsg"></div>

<table id="gigs">
    <thead>
        <tr>
            <th>Check</th>
            <th>Date &amp; Time</th>
            <th>Artist</th>
            <th>Venue</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><input type="checkbox" value="7" /></td>
            <td>Sun 16/11/14 1900</td>
            <td>Volbeat</td>
            <td>Manchester Academy, Manchester, GB</td>
        </tr>

        <tr>
            <td><input type="checkbox" value="16" /></td>
            <td>Sun 16/11/14 1900</td>
            <td>The Temperance Movement</td>
            <td>O2 Academy, Bristol, GB</td>
        </tr>

        <tr>
            <td><input type="checkbox" value="27" /></td>
            <td>Tue 28/10/14 1900</td>
            <td>Black Stone Cherry</td>
            <td>Motopoint Arena Cardiff, Cardiff, GB</td>
        </tr>

        <tr>
            <td><input type="checkbox" value="143" /></td>
            <td>Mon 1/12/14 1930</td>
            <td>Slash</td>
            <td>LG Arena, Birmingham, GB</td>
        </tr>

        <tr>
            <td><input type="checkbox" value="12"  /></td>
            <td>Tue 26/08/14 2000</td>
            <td>Airbourne</td>
            <td>Wedgewood Rooms, Portsmouth, GB</td>
        </tr>


        <tr><td colspan="4"><input id="btnDelete" value="Delete Selected Events" type="submit" /></td></tr>
    </tbody>
</table>

</form>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
    $("#btnDelete").click(function(e){

        e.preventDefault();
        var checks = [];

        $( "input[type=checkbox]:checked" ).each( function()
        {
            checks.push( $(this).val() );
        });

        if( checks.length )
        {
            if(confirm("Do you really want to delete?"))
            {
                deleteRecords( checks );
            }
        }

    });

    function deleteRecords( checks )
    {
        var delrecords = checks;
        var del = $.post("delete.php",{toDelete: delrecords}, function(data)
        {
            //alert( "Raw: " + data.raw + "\nFiltered: " + data.filtered + "\nDeleted: " + data.deleted + "\nConfimation:" + data.confirmed );
            if(data.confirmed)
            {
                $( "input[type=checkbox]:checked" ).each( function()
                {
                    if(jQuery.inArray( parseInt($(this).val()), data.confirmed ))
                    {
                        $(this).closest('tr').remove(); 
                    }
                }); 
            }
        }, 
        "json");
    }

</script>
</body>
</html>

The php:

<?php
    session_start();
    //===Hard coded for now
    $_SESSION['id'] = '1';
    $_SESSION['rights'] = 256;
    //==end hard code

    $rawNum = 0;
    $cleanNum = 0;
    $deleted = 0;
    $confirmedArray = NULL;

    if(isset($_SESSION['id']) && isset($_SESSION['rights']) && isset($_POST['toDelete']) && $_SESSION['rights'] == 256) 
    {
        $raw = (array) $_POST['toDelete'];

        $clean = array_filter($raw, "intval");
        $rawNum = count($raw);
        $cleanNum = count($clean);

        $dsn = 'mysql:dbname=daniweb;host=localhost';
        $user = 'root';
        $password = 'ygwterfawr';

        $dbh = new PDO($dsn, $user, $password);

        $items = implode(",", array_fill(0, $cleanNum, '?'));

        $stmt = $dbh->prepare("SELECT count(id) AS cnt FROM events WHERE id IN ($items)");
        $stmt->execute($clean);
        $cnt = $stmt->fetchColumn();
        if($cnt == $cleanNum)
        {
            $stmt = $dbh->prepare("DELETE FROM events WHERE id IN ($items)");
            $stmt->execute($clean);
            $deleted = $stmt->rowCount();
            $confirmedArray = $clean;
        }
    }
    echo json_encode(array("raw"=>$rawNum, "filtered"=>$cleanNum, "deleted"=>$deleted, "confirmed"=>$confirmedArray));

?>

This isn't meant to be production code - just a few ideas.

Member Avatar for diafol

The html table should be created dynamically from the db of course. Her's some sample data:

CREATE TABLE `events` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `venue` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `date` datetime DEFAULT NULL,
  `artist` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=147 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

insert  into `events`(`id`,`venue`,`date`,`artist`) values (7,'Manchester Academy, Manchester, GB','2014-11-16 17:00:00','Volbeat'),(12,'Wedgewood Rooms, Portsmouth, GB','2014-08-26 20:00:00','Airbourne'),(16,'O2 Academy, Bristol, GB','2014-11-16 17:00:00','The Temperance Movement'),(27,'Motopoint Arena Cardiff, Cardiff, GB','2014-10-28 19:00:00','Black Stone Cherry'),(143,'LG Arena, Birmingham, GB','2014-12-01 19:30:00','Slash');
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.