javascript - 如何使用 JSON 编码数据定义具有 sql 行 id 的元素

标签 javascript php jquery ajax

我正在使用 jQuery AJAX 来处理表单数据,它的 PHP 端应该删除服务器上的两个文件,然后删除数据库中的 SQL 行(对于发送给它的 id)。然后,包含 SQL 行的元素应更改颜色、向上移动、删除,并且下一个 SQL 行将移至其位置。动画内容发生在 ajax 回调的 beforeSend 和 success 函数中。

此脚本不起作用,当用户单击按钮时,页面 URL 更改为 php 脚本的 URL,但项目和文件不会在服务器或数据库中删除。也没有发生任何动画。

这是我第一次使用jQuery ajax,我认为我在回调过程中定义元素的方式有问题。任何帮助都会很棒:

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>

最佳答案

你应该像这样修复你的 php 代码

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));
}

现在在你的 JS 代码 Ajax 中更改为这个。

$.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");
    }
});

关于javascript - 如何使用 JSON 编码数据定义具有 sql 行 id 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27000840/

相关文章:

javascript - JavaScript 可以引用当前文件夹之外的图像源吗?

javascript - 在 String/String 位置后插入 HTML

php - 为搜索词提供黄色背景色

javascript - 从 View 发送到 Web api Controller 时,数据始终为空

javascript - $ ('.button' ).on ("DOMSubtreeModified") 在 chrome/safari 中不起作用,但在 Firefox 中起作用

javascript - 异步 for 循环行为在 map 和 [].push 之间表现不同

javascript - 从 firebase 获取数据节点

php - PHP解析/语法错误;以及如何解决它们

PHP 连接到 4D 数据库

jquery - Flex Slider - 动画不工作