如何使用PHP AJAX Javascript验证某个值是否重复或某个输入字段是否未填充



这是一个简单的REST API,用于在数据库中列出、创建和删除产品。我在验证/检查某些值是否重复或某些输入字段是否未填充时遇到问题。我曾尝试在php文件中使用rowCount来处理重复项,但我认为一定有更好的方法,但我在找到如何做到这一点时遇到了问题。

这是邮局。php

$query_check = 'SELECT * FROM skandi WHERE sku = :sku'; 
$stmt_check = $this->conn->prepare($query_check);
$stmt_check->bindParam(':sku', $this->sku);
$stmt_check->execute();
if ($stmt_check->rowCount() > 0) {
echo 'product name already exists!';
} else {
$query = 'INSERT INTO ' . $this->table . '
SET             

sku = :sku,
name = :name,
price = :price,
productType = :productType,
size = :size,
weight = :weight,
height = :height,
length = :length,
width = :width';
$stmt = $this->conn->prepare($query);

$this->sku;
$this->name; 
$this->price; 
$this->productType; 
$this->size;
$this->weight;
$this->height;
$this->length;
$this->width;
$stmt->bindParam(':sku', $this->sku);
$stmt->bindParam(':name', $this->name);
$stmt->bindParam(':price', $this->price);
$stmt->bindParam(':productType', $this->productType);
$stmt->bindParam(':size', $this->size);
$stmt->bindParam(':weight', $this->weight);
$stmt->bindParam(':height', $this->height);
$stmt->bindParam(':length', $this->length);
$stmt->bindParam(':width', $this->width);
if($stmt->execute()) {
return true;
} else {
ini_set('display_errors',1);
return false;
}
}

这是张贴的ajaxcall

$(document).ready(function () {
$("#saveBtn").click(function (e) {
e.preventDefault();
//serialize form data
var url = $("form").serialize();
//function to turn url to an object
function getUrlVars(url) {
var hash;
var myJson = {};
var hashes = url.slice(url.indexOf("?") + 1).split("&");
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split("=");
myJson[hash[0]] = hash[1];
}
return JSON.stringify(myJson);
}

//pass serialized data to function
var test = getUrlVars(url);
//post with ajax
$.ajax({
type: "POST",
url: "/api/post/create.php",
data: test,
ContentType: "application/json",
success: function () {
alert("successfully posted");
},
error: function () {

console.log("Could not be posted");
},
});

});});

您不应该检查重复项。在相关列上设置唯一约束,然后尝试插入。捕捉重复的错误(如果有的话(,并根据需要进行处理。

您可以使用PHP中的isset((函数检查某些输入字段是否未填充:例如:

if (isset($_POST['sku']) {
//exists
}

当要检查产品是否已经存在时,您必须检查它是否存在于数据库中,所以您必须进行查询。

最新更新