在PHP MySql中使用Ajax/Jquery内联编辑删除

在PHP MySql中使用Ajax/Jquery内联编辑删除,php,jquery,mysql,ajax,json,Php,Jquery,Mysql,Ajax,Json,这对我来说是新的。我不知道如何从jquery开始。我正在尝试使用Ajax进行内联编辑。我在某处找到了这个代码。但我没能做到。在config.php中,我配置了所有数据库连接,在response.php中,我使用php设置了sql查询。在数据库中,我有两列id和content index.php <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

这对我来说是新的。我不知道如何从jquery开始。我正在尝试使用Ajax进行内联编辑。我在某处找到了这个代码。但我没能做到。在
config.php
中,我配置了所有数据库连接,在
response.php
中,我使用php设置了sql查询。在数据库中,我有两列
id
content

index.php

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Add/Delete a Record with jQuery Fade In/Fade Out</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {

//##### send add record Ajax request to response.php #########
$("#FormSubmit").click(function (e) {
        e.preventDefault();
        if($("#contentText").val()==='')
        {
            alert("Please enter some text!");
            return false;
        }
        var myData = 'content_txt='+ $("#contentText").val(); //build a   post data structure
        jQuery.ajax({
        type: "POST", // HTTP method POST or GET
        url: "response.php", //Where to make Ajax calls
        dataType:"text", // Data type, HTML, json etc.
        data:myData, //Form variables
        success:function(response){
            $("#responds").append(response);
            $("#contentText").val(''); //empty text field on successful
        },
        error:function (xhr, ajaxOptions, thrownError){
            alert(thrownError);
        }
        });
});

//##### Send delete Ajax request to response.php #########
$("body").on("click", "#responds .del_button", function(e) {
     e.returnValue = false;
     var clickedID = this.id.split('-'); //Split string (Split works as PHP explode)
     var DbNumberID = clickedID[1]; //and get number from array
     var myData = 'recordToDelete='+ DbNumberID; //build a post data structure

        jQuery.ajax({
        type: "POST", // HTTP method POST or GET
        url: "response.php", //Where to make Ajax calls
        dataType:"text", // Data type, HTML, json etc.
        data:myData, //Form variables
        success:function(response){
            //on success, hide  element user wants to delete.
            $('#item_'+DbNumberID).fadeOut("slow");
        },
        error:function (xhr, ajaxOptions, thrownError){
            //On error, we alert user
            alert(thrownError);
        }
        });
});

});
</script>

<link href="css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="content_wrapper">
<ul id="responds">
<?php
//include db configuration file
include_once("config.php");

//MySQL query
$Result = mysql_query("SELECT id,content FROM add_delete_record");


//get all records from add_delete_record table
while($row = mysql_fetch_array($Result))
{
  echo '<li id="item_'.$row["id"].'">';
  echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$row["id"].'">';
  echo '<img src="images/icon_del.gif" border="0" />';
  echo '</a></div>';
  echo $row["content"].'</li>';
}

//close db connection
mysql_close($connecDB);
?>
</ul>
<div class="form_style">
<textarea name="content_txt" id="contentText" cols="45" rows="5"></textarea>
<button id="FormSubmit">Add record</button>
</div>
</div>

</body>
</html>
<?php
//include db configuration file
include_once("config.php");

if(isset($_POST["content_txt"]) && strlen($_POST["content_txt"])>0) 
{   //check $_POST["content_txt"] is not empty

//sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH Strip tags, encode special characters.
$contentToSave = filter_var($_POST["content_txt"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); 

// Insert sanitize string in record
if(mysql_query("INSERT INTO add_delete_record(content) VALUES('".$contentToSave."')"))
{
     //Record was successfully inserted, respond result back to index page
      $my_id = mysql_insert_id(); //Get ID of last inserted row from MySQL
      echo '<li id="item_'.$my_id.'">';
      echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$my_id.'">';
      echo '<img src="images/icon_del.gif" border="0" />';
      echo '</a></div>';
      echo $contentToSave.'</li>';
      mysql_close($connecDB); //close db connection

}else{

    //header('HTTP/1.1 500 '.mysql_error()); //display sql errors.. must not output sql errors in live mode.
    header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
    exit();
}

}
elseif(isset($_POST["recordToDelete"]) && strlen($_POST["recordToDelete"])>0 && is_numeric($_POST["recordToDelete"]))
{   //do we have a delete request? $_POST["recordToDelete"]

//sanitize post value, PHP filter FILTER_SANITIZE_NUMBER_INT removes all characters except digits, plus and minus sign.
$idToDelete = filter_var($_POST["recordToDelete"],FILTER_SANITIZE_NUMBER_INT); 

//try deleting record using the record ID we received from POST
if(!mysql_query("DELETE FROM add_delete_record WHERE id=".$idToDelete))
{    
    //If mysql delete query was unsuccessful, output error 
    header('HTTP/1.1 500 Could not delete record!');
    exit();
}
mysql_close($connecDB); //close db connection
}
else
{
//Output error
header('HTTP/1.1 500 Error occurred, Could not process request!');
exit();
}
?>

Ajax使用jQuery淡入/淡出添加/删除记录
$(文档).ready(函数(){
//#####将添加记录Ajax请求发送到response.php#########
$(“#表单提交”)。单击(函数(e){
e、 预防默认值();
if($(“#contentText”).val()='')
{
警报(“请输入一些文本!”);
返回false;
}
var myData='content_txt='+$(“#contentText”).val();//构建post数据结构
jQuery.ajax({
键入:“POST”,//HTTP方法POST或GET
url:“response.php”,//在哪里进行Ajax调用
数据类型:“text”,//数据类型、HTML、json等。
data:myData,//表单变量
成功:功能(响应){
$(“#响应”)。追加(响应);
$(“#contentText”).val(“”);//成功时为空文本字段
},
错误:函数(xhr、ajaxOptions、thrownError){
警报(thrownError);
}
});
});
//#####将删除Ajax请求发送到response.php#########
$(“正文”)。在(“单击”按钮上,“响应.del_按钮”,功能(e){
e、 returnValue=false;
var clickedID=this.id.split('-');//split string(split与PHP分解一样工作)
var dbnumberrid=单击edid[1];//并从数组中获取数字
var myData='recordToDelete='+DbNumberID;//构建post数据结构
jQuery.ajax({
键入:“POST”,//HTTP方法POST或GET
url:“response.php”,//在哪里进行Ajax调用
数据类型:“text”,//数据类型、HTML、json等。
data:myData,//表单变量
成功:功能(响应){
//成功后,隐藏用户要删除的元素。
$('#item_'+dbnumberrid).fadeOut(“慢”);
},
错误:函数(xhr、ajaxOptions、thrownError){
//出现错误时,我们会提醒用户
警报(thrownError);
}
});
});
});
添加记录
response.php

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Add/Delete a Record with jQuery Fade In/Fade Out</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {

//##### send add record Ajax request to response.php #########
$("#FormSubmit").click(function (e) {
        e.preventDefault();
        if($("#contentText").val()==='')
        {
            alert("Please enter some text!");
            return false;
        }
        var myData = 'content_txt='+ $("#contentText").val(); //build a   post data structure
        jQuery.ajax({
        type: "POST", // HTTP method POST or GET
        url: "response.php", //Where to make Ajax calls
        dataType:"text", // Data type, HTML, json etc.
        data:myData, //Form variables
        success:function(response){
            $("#responds").append(response);
            $("#contentText").val(''); //empty text field on successful
        },
        error:function (xhr, ajaxOptions, thrownError){
            alert(thrownError);
        }
        });
});

//##### Send delete Ajax request to response.php #########
$("body").on("click", "#responds .del_button", function(e) {
     e.returnValue = false;
     var clickedID = this.id.split('-'); //Split string (Split works as PHP explode)
     var DbNumberID = clickedID[1]; //and get number from array
     var myData = 'recordToDelete='+ DbNumberID; //build a post data structure

        jQuery.ajax({
        type: "POST", // HTTP method POST or GET
        url: "response.php", //Where to make Ajax calls
        dataType:"text", // Data type, HTML, json etc.
        data:myData, //Form variables
        success:function(response){
            //on success, hide  element user wants to delete.
            $('#item_'+DbNumberID).fadeOut("slow");
        },
        error:function (xhr, ajaxOptions, thrownError){
            //On error, we alert user
            alert(thrownError);
        }
        });
});

});
</script>

<link href="css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="content_wrapper">
<ul id="responds">
<?php
//include db configuration file
include_once("config.php");

//MySQL query
$Result = mysql_query("SELECT id,content FROM add_delete_record");


//get all records from add_delete_record table
while($row = mysql_fetch_array($Result))
{
  echo '<li id="item_'.$row["id"].'">';
  echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$row["id"].'">';
  echo '<img src="images/icon_del.gif" border="0" />';
  echo '</a></div>';
  echo $row["content"].'</li>';
}

//close db connection
mysql_close($connecDB);
?>
</ul>
<div class="form_style">
<textarea name="content_txt" id="contentText" cols="45" rows="5"></textarea>
<button id="FormSubmit">Add record</button>
</div>
</div>

</body>
</html>
<?php
//include db configuration file
include_once("config.php");

if(isset($_POST["content_txt"]) && strlen($_POST["content_txt"])>0) 
{   //check $_POST["content_txt"] is not empty

//sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH Strip tags, encode special characters.
$contentToSave = filter_var($_POST["content_txt"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); 

// Insert sanitize string in record
if(mysql_query("INSERT INTO add_delete_record(content) VALUES('".$contentToSave."')"))
{
     //Record was successfully inserted, respond result back to index page
      $my_id = mysql_insert_id(); //Get ID of last inserted row from MySQL
      echo '<li id="item_'.$my_id.'">';
      echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$my_id.'">';
      echo '<img src="images/icon_del.gif" border="0" />';
      echo '</a></div>';
      echo $contentToSave.'</li>';
      mysql_close($connecDB); //close db connection

}else{

    //header('HTTP/1.1 500 '.mysql_error()); //display sql errors.. must not output sql errors in live mode.
    header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
    exit();
}

}
elseif(isset($_POST["recordToDelete"]) && strlen($_POST["recordToDelete"])>0 && is_numeric($_POST["recordToDelete"]))
{   //do we have a delete request? $_POST["recordToDelete"]

//sanitize post value, PHP filter FILTER_SANITIZE_NUMBER_INT removes all characters except digits, plus and minus sign.
$idToDelete = filter_var($_POST["recordToDelete"],FILTER_SANITIZE_NUMBER_INT); 

//try deleting record using the record ID we received from POST
if(!mysql_query("DELETE FROM add_delete_record WHERE id=".$idToDelete))
{    
    //If mysql delete query was unsuccessful, output error 
    header('HTTP/1.1 500 Could not delete record!');
    exit();
}
mysql_close($connecDB); //close db connection
}
else
{
//Output error
header('HTTP/1.1 500 Error occurred, Could not process request!');
exit();
}
?>

谢谢和问候


瓦伊巴夫希望这个链接能帮助你
.

您的问题是什么?