javascript – Delete any row in MySQL with button click-ThrowExceptions

Exception or error:

First, I will summary my demo for you: I have a form for me to type an api link and type of the chart I want to draw from my api link. After that, I will click the button to create chart and insert my input to MySQL database to show it on screen. Each chart have a button for me to delete it if I want.
Everything worked fine except delete funtion to delete my input from database. When I press delete button, it’s only delete in html, not delete in my database. Can you help me? Thank you!
Here is my code:
My input form:

<!--HTML Form input-->
		<div class = "login-block">
			<form id="form1" style="display: block" method="POST" action="chart_test.php">
			
				<!--Input link api-->
				<b>Link: </b><input type="text" id="link" name="apilink"><br>
				<br>
				
				<!--Chart Type-->
				<b>Chart Type:</b>
				<label class="custom-select">
					<select id="chartType" name="chartType">
						<option value="">Select</option>
						<option value="pie">Pie Chart</option>
						<option value="column">Column Chart</option>
						<option value="bar">Bar Chart</option>
					</select>
				</label>
				<br><br>
				
				<!--Button create chart-->
				<div class ="wrapper">
					<button type="submit" name="create" onClick="drawChart()">Create</button>
					<br><br>
				</div>
				
			</form>
		</div>

Insert input to database and show to screen:

<!--insert form data to mysql-->
    <?php

        $con = mysql_connect("localhost","root","123456");
        if (!$con)
        {
            die('Could not connect: ' . mysqli_error());
        }

        mysql_select_db("activiti_report");

        //check data when first load page to not showing notice error
        if ($_SERVER['REQUEST_METHOD'] == 'POST'){
            $apilink = $_POST["apilink"];
            $chartType = $_POST["chartType"];
        }

        if(isset($_POST['create'])) {
            $sql = "INSERT INTO chartinfo (link, typeChart) VALUES ('$apilink', '$chartType')";

            $result = mysql_query($sql);

            header("Location:chart_test.php");
            exit;
        }           
    ?>

Query database to show chart on screen and the button with script to delete:

<?php //query data from database
        $result = mysql_query("SELECT * FROM chartinfo");
    ?>

    <?php //while loop to read data from query result
        while($db_field = mysql_fetch_assoc($result)):          
    ?>

    <?php //unique chartId for not the same to show more chart  
            $idChart = 'chartContainer_' . uniqid();                            
    ?>

    <!--Show chart from database-->
    <br>
    <div class = "chart-block">
        <?php // 2 lines about chart infomation
            echo ("<b>API Link:</b>   "); print $db_field['link'] . "<BR>";
            echo ("<b>Chart Type:</b>   "); print $db_field['typeChart'] . "<BR>";
        ?>

        <!-- The <div> and <script> to show the chart -->
        <div id="<?=$idChart?>" style="height: 360px; width: 70%;"></div>

        <script>
        $(document).ready(function() {

            var dataPointsA = []
            var text = document.getElementById('chartType')
            var strChart = text.options[text.selectedIndex].value

            $.ajax({
                type: 'GET',
                url: "<?php echo $db_field['link']?>", //assign URL from query result field 
                dataType: 'json',
                success: function(field) {
                    for (var i = 0; i < field.length; i++) {
                        dataPointsA.push({
                        label: field[i].name,
                        y: field[i].value
                        });
                    }

            var chart = new CanvasJS.Chart("<?=$idChart?>", {
            title: {
                text: "Activiti Report"
            },

                data: [{
                    type: "<?php echo $db_field['typeChart']?>", //assign type of chart from query result field
                    name: "chart",
                    dataPoints: dataPointsA
                }]
            });

            chart.render();
                }
            });
        });
        </script>
        <br>

        <!--Button to delete the chart and row in database-->
        <button type="submit" name="delete" onClick="removeParent(this.parentNode)">Delete</button>

        <!--Script remove <div> contain the chart-->
        <script>
            function removeParent(parent) {
                parent.remove();
            }
        </script>   

        <!--Script delete form data from mysql-->
        <?php                                                                                           
            if(isset($_POST['delete'])) {
                $sql = "DELETE FROM chartinfo (link, typeChart) WHERE link ='" .$db_field['link']. "' AND typeChart = '" .$db_field['link']. "'";

                $result = mysql_query($sql);

                header("Location:chart_test.php");
                exit;
            }           
        ?>

I know I should use mysqli_* instead mysql_* but this is just a demo for me to understand PHP, I learned it only a few days. Sorry for a lot of code but I think I should show to you to understand what I am doing.
Thank you very much!

How to solve:

Your delete button trigger its action from the js code not the php code. It only remove from the view but will appear on reload. You can use ajax in your remove function or use a delete link instead of button

Answer:

<button type="submit" name="<?php echo chart id here?>" id="btn_del">Delete</button>

$("#btn_del).on("click", function(){
var btn_this = $(this);
var id= $(this).attr('name');
$.ajax({
type: 'GET',
url: "delete.php",
data: {id:id},
success: function(resp) {
    btn_this.parentNode.remove();            
}
});
});


<?php                                                                                           
            if(isset($_GET['id'])) {
                $sql = "DELETE FROM chartinfo WHERE link ='" .$_GET['id']. "';

                $result = mysql_query($sql);
            }           
        ?>

Answer:

<button type="submit" name="<?php echo chart id here?>" id="btn_del">Delete</button>
<script>
$("#btn_del).on("click", function(){
     var btn_this = $(this);
     var id= $(this).attr('name');
     $.ajax({
           type: 'GET',
           url: "delete.php?id="+id,
           success: function(resp) {
              btn_this.parentNode.remove();            
            }
     });
});

</script>

<?php                                                                                           
    if(isset($_GET['id'])) {
        $sql = "DELETE FROM chartinfo WHERE link ='" .$_GET['id']. "';
        $result = mysql_query($sql);
    }           
 ?>

Leave a Reply

Your email address will not be published. Required fields are marked *