Robert Scoloni Robert Scoloni - 6 months ago 26
Javascript Question

How to define an element with a a sql row id usng JSON encoded data

I'm using jQuery AJAX to process form data, the PHP side of it should delete two files on the server and then the SQL row in the database (for the id that was sent to it). The element containing the SQL row should then change color, move up, delete and the next SQL rows move into its place. The animation stuff occurs in the beforeSend and success functions of the ajax callback.

This script is not working, when user clicks button, the page url changes to that of the php script but the item and files do not get deleted either on the server or in the database. Nor does any of the animation occur.

This is my first time using jQuery ajax, I think there is a problem with how I define the element during the call back. Any help would be great:

js

$("document").ready(function(){
$(".delform").submit(function(){
data = $(this).serialize() + "&" + $.param(data);
if (confirm("Are you sure you want to delete this listing?")) {
$.ajax({
type: "POST",
dataType: "json",
url: "delete_list.php",
data: data,
beforeSend: function() {
$( "#" + data["idc"] ).animate({'backgroundColor':'#fb6c6c'},600);
},
success: function() {
$( "#" + data["idc"] ).slideUp(600,function() {
$( "#" + data["idc"] ).remove();
});
}
});
return false;
}
});
});


php

if (isset($_POST["id"]))
{
$idc = $_POST["id"];

if (isset($_POST["ad_link"]) && !empty($_POST["ad_link"]))
{
$ad_linkd=$_POST["ad_link"];
unlink($ad_linkd);
}

if (isset($_POST["listing_img"]) && !empty($_POST["listing_img"]))
{
$listing_imgd=$_POST["listing_img"];
unlink($listing_imgd);
}

try {
require('../dbcon2.php');
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "DELETE FROM listings WHERE id = $idc";
$conn->exec($sql);

}
catch (PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
echo json_encode($idc);
}


html

<div id="record-<?php echo $id; ?>">
*bunch of stuff*
<form method="post" class="delform">
<input name="id" type="hidden" id="id" value="<?php echo $id; ?>" />
<input name="ad_link" type="hidden" id="ad_link" value="<?php echo $ad_link; ?>" />
<input name="listing_img" type="hidden" id="listing_img" value="<?php echo $listing_img; ?>" />
<button type="submit">Delete</button>
</form>
</div>

Answer

You should fix your php code like this

try {
    require('../dbcon2.php');
    // It's better, if you will going to use MySQL DB, use the class designed to connect with it.
    $conn = mysqli_connect("Servername", "usernameDB", "PasswordDB", "NameDB");
    $sql = "DELETE FROM listings WHERE id = $idc";
    mysqli_query($conn, $sql);
    // you have to create a asociative array for a better control
    $data = array("success" => true, "idc" => $idc);
    // and you have to encode the data and also exit the code.
    exit(json_encode($data));
} catch (Exception $e) {
    // you have to create a asociative array for a better control
    $data = array("success" => false, "sentence" => $sql, "error" => $e.getMessage());
    // and you have to encode the data and also exit the code.
    exit(json_encode($data));
}

Now in you JS code Ajax change to this.

$.ajax({
    type: "POST",
    dataType: "json",
    url: "delete_list.php",
    data: data,
    beforeSend: function()  {
        $( "#" + data["idc"] ).animate({'backgroundColor':'#fb6c6c'},600);      
    },
    success: function(response) {
        // the variable response is the data returned from 'delete_list.php' the JSON
        // now validate if the data returned run well
        if (response.success) {
            $( "#" + response.idc ).slideUp(600,function() {
                $( "#" + response.idc ).remove();
            });
        } else {
            console.log("An error has ocurred: sentence: " + response.sentence + "error: " + response.error);
        }
    },
    // add a handler to error cases.
    error: function() {
        alert("An Error has ocurred contacting with the server. Sorry");
    }
});