gpt4 book ai didi

javascript - 如何修改 PHP/Jquery/Ajax 脚本以拥有多个表单字段

转载 作者:行者123 更新时间:2023-11-29 13:18:51 38 4
gpt4 key购买 nike

我有一个 php/Ajax/Jquery 脚本,它将表单字段插入 MySQL 并更新页面,而无需在您点击提交时刷新。我希望脚本提交四个表单字段,而不是仅一个。

我已经用 3 个附加字段更新了数据库表 add_delete_record:balance、account_numbermonthly,以及已经存在的内容字段那里。

下面的代码可能有点过头了,因为我只需要修改几行,但我认为这可以回答所有问题。

这是 php 和 html 页面:

<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>

这是它发布到的 php:

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

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

//sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH
$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 is successfully inserted, respond to ajax request
$my_id = mysql_insert_id(); //Get ID of last inserted record 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);

}else{
//output error

//header('HTTP/1.1 500 '.mysql_error());
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 record was unsuccessful, output error
header('HTTP/1.1 500 Could not delete record!');
exit();
}
mysql_close($connecDB);

}else{

//Output error
header('HTTP/1.1 500 Error occurred, Could not process request!');
exit();
}
?>

这是 JQuery

$(document).ready(function() {
//##### Add record when Add Record Button is clicked #########
$("#FormSubmit").click(function (e) {

e.preventDefault();

if($("#contentText").val()==="") //simple validation
{
alert("Please enter some text!");
return false;
}

var myData = "content_txt="+ $("#contentText").val(); //post variables

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, //post variables
success:function(response){
$("#responds").append(response);
$("#contentText").val(''); //empty text field after successful submission
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError); //throw any errors
}
});
});

//##### Delete record when delete Button is clicked #########
$("body").on("click", "#responds .del_button", function(e) {
e.preventDefault();
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, //post 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);
}
});
});
});

这不是我的脚本,所以我想我还应该提供一个链接来注明其作者: http://www.sanwebe.com/2012/04/ajax-add-delete-sql-records-jquery-php

最佳答案

我不是 php 专家,但这应该可以帮助您完成:

首先更改主页上的表单区域:

<div class="form_style">
<textarea name="content_txt" id="contentText" cols="45" rows="5"></textarea><br/>
<input type="text" id="balance" /><br/>
<input type="text" id="acctNum" /><br/>
<input type="text" id="monthly" /><br/>
<button id="FormSubmit">Add record</button>
</div>

那么你的 myData 看起来像这样:

var myData = {
content_txt: $("#contentText").val(),
balance: $("#balance").val(),
acctNum: $("#acctNum").val(),
monthly: $("#monthly").val()
};

以及稍后的ajax响应:

$("#contentText").val(''); //empty text field after successful submission
$("#balance").val('');
$("#acctNum").val('');
$("#monthly").val('');

最后是 PHP:

//sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH
$content = filter_var($_POST['content_txt'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$balance = filter_var($_POST['balance'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$account = filter_var($_POST['acctNum'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$monthly = filter_var($_POST['monthly'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);


$qry= "INSERT INTO add_delete_record(content,balance,account,monthly) VALUES('".$content."','".$balance."','".$account."','".$monthly."')";


// Insert sanitize string in record
if(mysql_query("INSERT INTO add_delete_record(content,balance,account,monthly) VALUES('".$content."','".$balance."','".$account."','".$monthly."')"))
{
//Record is successfully inserted, respond to ajax request
$my_id = mysql_insert_id(); //Get ID of last inserted record 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 $content.'</li>';
mysql_close($connecDB);

}else{
//output error

//header('HTTP/1.1 500 '.mysql_error());
header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
exit();
}

关于javascript - 如何修改 PHP/Jquery/Ajax 脚本以拥有多个表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21123567/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com