echo php 表单验证 ajax
echo php form validation with ajax
大家好,
我正在尝试使用 php 创建 CMS,但在执行下一步时遇到了问题:
我想删除、编辑或添加信息到我的页面,为此我使用了几个按钮和 AJAX 将表单加载到显示器 div。我让删除按钮完美地工作,但是当我尝试添加和编辑按钮时它不起作用,因为他们要求附加一些 html 文本,其中也包含 php 代码,所以没有PHP 解释器来阅读它。
我的做法:
<div class="displayHere col-xs-12"> </div>
为空。
- 我点击添加按钮,它会转到 ajax.php 并附加表单和表单验证。
- 我填写了表格并单击 add_document,表格验证 (php) 检查数据并在可能的情况下上传文档并设置一些输出变量。
如何获得此功能?可能是我处理的不好,希望大家分享经验。
例如,对于add函数,我想获得这个功能:
<div id="bodyDiv">
<!--HEADER-->
<header id="header" class=" row">
<?php
include 'includes/loadHeader.php';
echo '<nav class="col-xs-6 cms_nav">
<ul>
<li><input id="buttonAdd" type="submit" class="button buttonFuncitonality" name="AÑADIR" value="AÑADIR" /></li>
</ul>
</nav>';
?>
<div class="displayHere col-xs-12">
<?php
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$nameErr = $dateErr = $typeErr = $fileErr = "";
$name = $date = $type = $file = $matches = "";
$success = true;
if ($_SERVER["REQUEST_METHOD"] == "POST"){
// name, date, type, path
if (empty($_POST["name"])) {
$nameErr = "El nombre es necesario";
$success = FALSE;
}
else {
$name = test_input($_POST["name"]);
}
if (!empty($_POST["date"])) {
$date = test_input($_POST["date"]);
$time_pattern = "(([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]))?";
//Check the date format http://www.phpliveregex.com/ (0|[1-9]|0[1-9]|[1-2][0-9]|3[0-1])-(0[1-9]|1[0-2])-([0-9]{4})\s+([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])
if (preg_match("/^(0|[1-9]|0[1-9]|[1-2][0-9]|3[0-1])-(0[1-9]|1[0-2])-([0-9]{4})\s*".$time_pattern."/",$date,$matches)){
echo "<script>console.log('yeahh format 1');</script>";
echo "<script>console.log('yeahh format 1 ". $date. " ". str_replace("-","/",$matches['0']) ." yeahh format 1');</script>";
$date = str_replace("-","/",$matches['0']);
}
elseif (preg_match("/^(0|[1-9]|0[1-9]|[1-2][0-9]|3[0-1])\/(0[1-9]|1[0-2])\/([0-9]{4})\s*".$time_pattern."/",$date, $matches)){
}
else{
echo "<script>console.log('noooo ". $date. " " . $matches['0'] ." yeahh format 1');</script>";
$dateErr = "Formato de fecha incorrecto";
$success = FALSE;
}
//The formar mysql is expecting DATETIME '0000-00-00 00:00:00'
if(empty($dateErr)){
if( preg_match("/\s([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])/",$date)){
$date = DateTime::createFromFormat('j/m/Y H:i', $date);
$date = $date->format('d-m-Y H:i');
}
else{
$date = DateTime::createFromFormat('j/m/Y', $date);
$date = $date->format('d-m-Y');
}
echo "<script>console.log('date ".$date."');</script>";
}
}
if (empty($_POST["type"]) ) {
$typeErr = "El tipo de documento es necesario";
$success = FALSE;
}
else{
$type = test_input($_POST["type"]);
}
// Upload the file
if($success ){
if(empty($_FILES['documentPDF']['name'])){
$fileErr = "Debes añadir un documento pdf ";
}
else{
$target_dir = "shareholders_documents/".$type. "/";
$file_name = basename($_FILES["documentPDF"]["name"]);
$target_file = $target_dir . $file_name;
echo "<script>console.log('".$target_file."');</script>";
$fileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
//echo " vamos a ver que hay aqui " .$target_file;
// Check if pdf already exist
if (file_exists($target_file)) {
$fileErr = "Este documento ya existe.";
$success = false;
}
if ($_FILES["documentPDF"]["size"] > 500000) {
$fileErr = "El documento es demasiado largo";
$success = false;
}
// Allow certain file formats
if($fileType != "pdf" ) {
$fileErr = "El documento debe estar en formato pdf";
$success = false;
}
// Check if $uploadOk is set to 0 by an error
if ($success == true ) {
//echo "\nmove_uploaded_file(".$_FILES["documentPDF"]["tmp_name"].", ".$target_file.")" ;
if (!move_uploaded_file($_FILES["documentPDF"]["tmp_name"], $target_file)) {
$fileErr ="No se ha podido almacenar el documento ". basename( $_FILES["documentPDF"]["name"]);
$success = false;
}
}
}
}
}
$result="";
// Now we have to prepare the data for the sql operation
if( isset( $_POST["insert"] ) && $success ){
$name = test_input($_POST['name']);
$date = $date;
$type = test_input($_POST['type']);
$path = $file_name;
$id = $type ." ". $date . " " . $path ;
//Create $sql sentence
$sql = "INSERT INTO `shareholders_documents`(`id`, `name`, `date`, `type`, `path`) VALUES ('".$id."','".$name."',STR_TO_DATE('".$date."', '%d-%m-%Y %H:%i'),'".$type."','".$path."')";
$sqlResult = $conn->query($sql);
$message= "";
if($conn->error){
$message = $conn->error;
$success = false;
}
//Sending email
if ($success){
$result='<div class="alert alert-success margin-top-big">El documento se ha subido correctamente'.$name." ".$date." ".$type." ". $path. "\n" . $sql. '</div>';
}
else{
$result = '<div class="alert alert-danger margin-top-big">Algo ha fallado y el documento no se ha podido subir ' . $message . '</div>';
if(empty($fileErr)){ //If we cannot insert the document we must delete the file
unlink($target_file);
}
}
}
//Cleaning global array $_POST
$_POST = array();
$_FILE = array();
?>
<div id="insertForm" class="col-xs-12 shareholdersForm">
<h3>Insertar</h3>
<form method="POST" enctype="multipart/form-data">
<input class="col-xs-12 form-control <?php if( !empty($nameErr) ) {echo 'boxError alert-danger ' ;} ?> " value="<?php if( !$success ) {echo $name;}?>" type="text" name="name" placeholder="<?php if( !empty($nameErr) ) {echo $nameErr;}else{ echo 'nombre';}?>">
<input class="col-xs-12 form-control <?php if( !empty($dateErr) ) {echo 'boxError alert-danger ' ;} ?> " value="<?php if( !$success ) {echo $date;}?>" type="text" name="date" placeholder="<?php if( !empty($dateErr) ) {echo $dateErr;}else{ echo 'fecha (Ejemplo de formato: 31/10/2017 17:54)';}?>">
<select class="col-xs-12 form-control <?php if( !empty($typeErr) ) {echo 'boxError alert-danger ' ;} ?> " name="type">
<option value="hechosRelevantes">hecho relevantes</option>
<option value="informacionEmpresa">informacion empresa</option>
<option value="informacionFinanciera">informacion financiera</option>
</select>
<input class="col-xs-12" type="file" name="documentPDF" accept="application/pdf" >
<span class="error col-xs-12" style="float:left"> <?php if( !empty($fileErr) ) {echo "* ". $fileErr;} ?> </span>
<button class="btn btn-default" type="submit" name="insert">Añadir</button>
<?php if ( !empty($result) ){ echo $result; } ?>
</form>
</div>
</div>
在我的网站上,我有一个添加按钮,应该使用 AJAX 上传表单验证。
<?php
//echo "piece of shit";
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'AÑADIR': //ADD FUNCTIONALITY
add_document();
break;
default:
echo "La accion no se indentifica\n" ;
break;
}
}
function add_document() {
echo ' <div id="insertForm" class="col-xs-12 shareholdersForm">
<h3>Insertar</h3>
<form method="POST" enctype="multipart/form-data">
<input class="col-xs-12 form-control <?php if( !empty($nameErr) ) {echo "boxError alert-danger " ;} ?> " value="<?php if( !$success ) {echo $name;}?>" type="text" name="name" placeholder="<?php if( !empty($nameErr) ) {echo $nameErr;}else{ echo "nombre";}?>">
<input class="col-xs-12 form-control <?php if( !empty($dateErr) ) {echo "boxError alert-danger " ;} ?> " value="<?php if( !$success ) {echo $date;}?>" type="text" name="date" placeholder="<?php if( !empty($dateErr) ) {echo $dateErr;}else{ echo "fecha (Ejemplo de formato: 31/10/2017 17:54)";}?>">
<select class="col-xs-12 form-control <?php if( !empty($typeErr) ) {echo "boxError alert-danger" ;} ?> " name="type">
<option value="hechosRelevantes">hecho relevantes</option>
<option value="informacionEmpresa">informacion empresa</option>
<option value="informacionFinanciera">informacion financiera</option>
</select>
<input class="col-xs-12" type="file" name="documentPDF" accept="application/pdf" >
<span class="error col-xs-12" style="float:left"> <?php if( !empty($fileErr) ) {echo "* ". $fileErr;} ?> </span>
<button class="btn btn-default" type="submit" name="insert">Añadir</button>
<?php if ( !empty($result) ){ echo $result; } ?>
</form>
</div>
</div>';
}
function load_delete_document_form($id) {
echo ' <div id="deleteForm" class="col-xs-12 shareholdersForm">
<h3>Eliminar '. $id.'</h3>
<form id="'.$id.'" method="POST">
<button class="btn btn-default buttonFunctionality" type="submit" name="Delete" value="Delete">Eliminar</button>
</form>
</div>
';
exit;
}
?>
为了使用那个 AJAX 代码,我在我的网站上使用了这个 jquery 函数:
<script>
//$(document).ready(function(){
$("body").on("click",".buttonFunctionality", function(){
if($('.displayHere').length !== 0){
$('.displayHere').children().remove()
}
var action = $(this).val();
var id = $(this).parent().attr('id');
console.log(action + " " + id);
$.post("includes/ajax.php",{ action: action, id: id}, function(data, status){
console.log("click1 " + id );
console.log("data " + data);
$('.displayHere').append(data); // This append will append the code I will need in my page
});
});
//});
</script>
由于我的代码,我得到了带有大量 php 代码的表单,没有解释。
问题来自您的 add_document() 函数;
因为它是 php 你不必使用 <?php
?>
而是将字符串连接在一起然后回显整个事情
应该看起来像这样:
function add_document() {
$div = ' <div id="insertForm" class="col-xs-12 shareholdersForm">
<h3>Insertar</h3>
<form method="POST" enctype="multipart/form-data">
<input class="col-xs-12 form-control ';
if( !empty($nameErr) ) {
$div .= "boxError alert-danger ";
}
$div .= '" value="';
if( !$success ) {
$div .= $name;
}
$div .= '" type="text" name="name" placeholder="';
//more code
echo $div;
}
希望你明白了
编辑:
这里的另一个问题是您试图在没有 re-submiting 的情况下在表单的 ajax 一侧进行表单验证;
我建议通过将 required
添加到您的输入标签来使用默认表单验证;
您的函数应如下所示:
function add_document() {
$nameVal = (!$success ) ? $name : "";
$dateVal = (!$success ) ? $date : "";
$resultVal = (!empty($result) ) ? $result : "";
$nameErrVal = (!empty($nameErr)) ? $nameErr : "nombre";
$dateErrVal = (!empty($dateErr)) ? "boxError alert-danger " : "";
$dateErrVal2 = (!empty($dateErr)) ? $dateErr : "fecha (Ejemplo de formato: 31/10/2017 17:54)";
$typeErrVal = (!empty($typeErr)) ? "boxError alert-danger" : "";
$fileErrVal = (!empty($fileErr)) ? "* ". $fileErr : "";
$div = ' <div id="insertForm" class="col-xs-12 shareholdersForm">
<h3>Insertar</h3>
<form method="POST" enctype="multipart/form-data">
<input class="col-xs-12 form-control " value="'.$nameVal.'" type="text" name="name" placeholder="'
.$nameErrVal.'" required>
<input class="col-xs-12 form-control '.$dateErrVal.'" value="'.$dateVal.'"
type="text" name="date" placeholder="'.$dateErrVal2.'" required>
<select class="col-xs-12 form-control '.$typeErrVal.'" name="type">
<option value="hechosRelevantes">hecho relevantes</option>
<option value="informacionEmpresa">informacion empresa</option>
<option value="informacionFinanciera">informacion financiera</option>
</select>
<input class="col-xs-12" type="file" name="documentPDF" accept="application/pdf" required>
<span class="error col-xs-12" style="float:left"> '.$fileErrVal.' </span>
<button class="btn btn-default" type="submit" name="insert">Añadir</button>
'.$resultVal.'
</form>
</div>
</div>';
echo $div;
}
它应该输出类似的东西:https://jsfiddle.net/p6147nh0/11/
我想你可以用 html 属性检查它 required
是否为空输入
对于其他类似用户刚刚使用 php 函数 empty($value)
在评论输入 中输入了 空格
我终于找到了解决办法。这是我的第一种方法:
<div class="displayHere col-xs-12"> </div>
为空。
我点击添加按钮,它会转到 ajax.php 并附加表格和表格
验证。 (这部分是错误的或者至少我没有得到它
工作,我无法将表单验证附加到前面。相反,我
必须检查 AJAX 文件的所有内容,该文件将检查
一切都将 return 只是 html 已经形成。)
3-我填写了表格并点击add_document,表格验证(php)
检查数据并在可能的情况下上传文档并设置
一些输出变量。
因为它不起作用,我尝试向我的 AJAX 发送验证表单所需的所有信息,并从中获取已经创建的 html。
- 为空。
我点击添加按钮(有两个添加按钮,一个用于上传表格,另一个用于发送填写的表格),它将转到 AJAX 并将 return 对我来说
将附加到页面的表单。
相关的
信息公司
信息金融时代
阿纳迪尔
将填写表格并点击 Añadir。该按钮关联了一个
javascript 函数。
$(document).ready(function(){
$("body").on("click",".buttonFunctionality", function(e){
e.preventDefault();
var action = $(this).val();
var id = $(this).parent().attr('id');
var formdata = new FormData($("#insertForm>form")[0]);
formdata.append("action", action);
formdata.append("id",id);
$.ajax({
url: "includes/ajax.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: formdata, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
console.log("SUCCESS");
if($('.displayHere').length !== 0){
$('.displayHere').children().remove()
}
$(".displayHere").append(data);
}
});
});
});
//});
</script>
3-一开始我试图创建一个 JSON 来将信息发送到我的 ajax.php,但是后来,我意识到有一个方法 var formdata = new FormData($(" #insertForm>form") 提供了我处理表单验证所需的所有信息($_POST,$_File ...)。所以最后这个方法是我需要解决它的最后一个细节。
此函数将信息发送到ajax.php,并在ajax.php中处理php代码。
AJAX.php
<?php
session_start();
include 'dbh.inc.php';
$message = $sql = "";
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'AÑADIR':
add_document($_POST['action']);
break;
case 'add':
echo("<script>console.log(' ADD ');</script>");
echo("<script>console.log(' PHP tmp_name :". $_FILES['documentPDF']['tmp_name']."');</script>");
if(isset($_FILES["documentPDF"]["type"]))
{
echo("<script>console.log(' PHP tmp_name :". $_FILES['documentPDF']['tmp_name']."');</script>");
}
add_document($_POST['action']);
break;
case 'Editar':
if (isset($_POST['id'])) {
load_edit_document($_POST['id']);
break;
}
case 'Edit':
if (isset($_POST['id'])) {
edit_document($_POST['id']);
break;
}
case 'Eliminar':
if (isset($_POST['id'])) {
echo("<script>console.log('PHP id: ".$_POST['id']."');</script>");
load_delete_document_form($_POST['id']);
break;
}
case 'Delete':
if (isset($_POST['id'])) {
delete_document($_POST['id']);
break;
}
default:
echo "La accion no se indentifica\n" ;
break;
}
}
function add_document($action) {
echo "<script>console.log('INSIDE ADD_DOCUMENT');</script>";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$nameErr = $dateErr = $typeErr = $fileErr = "";
$name = $date = $type = $file = $matches = "";
$success = true;
if ($_SERVER["REQUEST_METHOD"] == "POST" && $action == 'add' ){
echo "<script>console.log('INSIDE REQUEST_METHOD');</script>";
// name, date, type, path
if (empty($_POST["name"])) {
$nameErr = "El nombre es necesario";
$success = FALSE;
}
else {
$name = test_input($_POST["name"]);
}
if (!empty($_POST["date"])) {
$date = test_input($_POST["date"]);
$time_pattern = "(([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]))?";
//Check the date format http://www.phpliveregex.com/ (0|[1-9]|0[1-9]|[1-2][0-9]|3[0-1])-(0[1-9]|1[0-2])-([0-9]{4})\s+([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])
if (preg_match("/^(0|[1-9]|0[1-9]|[1-2][0-9]|3[0-1])-(0[1-9]|1[0-2])-([0-9]{4})\s*".$time_pattern."/",$date,$matches)){
echo "<script>console.log('yeahh format 1');</script>";
echo "<script>console.log('yeahh format 1 ". $date. " ". str_replace("-","/",$matches['0']) ." yeahh format 1');</script>";
$date = str_replace("-","/",$matches['0']);
}
elseif (preg_match("/^(0|[1-9]|0[1-9]|[1-2][0-9]|3[0-1])\/(0[1-9]|1[0-2])\/([0-9]{4})\s*".$time_pattern."/",$date, $matches)){
}
else{
echo "<script>console.log('noooo ". $date. " " . $matches['0'] ." yeahh format 1');</script>";
$dateErr = "Formato de fecha incorrecto";
$success = FALSE;
}
//The formar mysql is expecting DATETIME '0000-00-00 00:00:00'
if(empty($dateErr)){
if( preg_match("/\s([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])/",$date)){
$date = DateTime::createFromFormat('j/m/Y H:i', $date);
$date = $date->format('d-m-Y H:i');
}
else{
$date = DateTime::createFromFormat('j/m/Y', $date);
$date = $date->format('d-m-Y');
}
echo "<script>console.log('date ".$date."');</script>";
}
}
if (empty($_POST["type"]) ) {
$typeErr = "El tipo de documento es necesario";
$success = FALSE;
}
else{
$type = test_input($_POST["type"]);
}
// Upload the file
if($success ){
if(empty($_FILES['documentPDF']['name'])){
$fileErr = "Debes añadir un documento pdf ";
}
else{
$target_dir = "../shareholders_documents/".$type. "/";
$file_name = basename($_FILES["documentPDF"]["name"]);
$target_file = $target_dir . $file_name;
echo "<script>console.log('".$target_file."');</script>";
$fileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
//echo " vamos a ver que hay aqui " .$target_file;
// Check if pdf already exist
if (file_exists($target_file)) {
$fileErr = "Este documento ya existe.";
$success = false;
}
if ($_FILES["documentPDF"]["size"] > 1000000) {
$fileErr = "El documento es demasiado largo";
$success = false;
}
// Allow certain file formats
if($fileType != "pdf" ) {
$fileErr = "El documento debe estar en formato pdf";
$success = false;
}
// Check if $uploadOk is set to 0 by an error
if ($success == true ) {
if (!move_uploaded_file($_FILES["documentPDF"]["tmp_name"], $target_file)) {
$fileErr ="No se ha podido almacenar el documento ". basename( $_FILES["documentPDF"]["name"]);
$success = false;
}
}
}
}
}
$result="";
// Now we have to prepare the data for the sql operation
if( $action == 'add' && $success ){
$name = test_input($_POST['name']);
$date = $date;
$type = test_input($_POST['type']);
$path = $file_name;
$id = $type ." ". $date . " " . $path ;
//Create $sql sentence
include 'dbh.inc.php';
$sql = "INSERT INTO `shareholders_documents`(`id`, `name`, `date`, `type`, `path`) VALUES ('".$id."','".$name."',STR_TO_DATE('".$date."', '%d-%m-%Y %H:%i'),'".$type."','".$path."')";
$sqlResult = $conn->query($sql);
$message= "";
if($conn->error){
$message = $conn->error;
$success = false;
}
//Sending email
if ($success){
$result='<div class="alert alert-success margin-top-big">El documento se ha subido correctamente'.$name." ".$date." ".$type." ". $path. "\n" . $sql. '</div>';
}
else{
$result = '<div class="alert alert-danger margin-top-big">Algo ha fallado y el documento no se ha podido subir ' . $message . '</div>';
if(empty($fileErr)){ //If we cannot insert the document we must delete the file
unlink($target_file);
}
}
}
//Cleaning global array $_POST
$_POST = array();
$_FILE = array();
//
// Form validation
//
$div = ' <div id="insertForm" class="col-xs-12 shareholdersForm">
<h3>Insertar</h3>
<form method="POST" action="" enctype="multipart/form-data">
<input class="col-xs-12 form-control addingForm ' ;
if( !empty($nameErr) ) {
$div .= "boxError alert-danger " ;
}
$div.= '" value="';
if( !$success ) {
$div .= $name;
}
$div .='" type="text" name="name" placeholder=" ';
if( !empty($nameErr) ) {
$div .= $nameErr;
}else{
$div .= "nombre";
}
$div .= '" required>
<input class="col-xs-12 form-control addingForm ';
if( !empty($dateErr) ) {
$div .= "boxError alert-danger " ;
}
$div .=' " value="';
if( !$success ) {
$div .= $date;
}
$div .= '" type="text" name="date" placeholder=" ';
if( !empty($dateErr) ) {
$div.= $dateErr;
}else{
$div.= "fecha (Ejemplo de formato: 31/10/2017 17:54)";
}
$div .='" required>
<select class="col-xs-12 form-control addingForm ';
if( !empty($typeErr) ) {
$div .= "boxError alert-danger" ;
}
$div.= ' " name="type">
<option value="hechosRelevantes">hecho relevantes</option>
<option value="informacionEmpresa">informacion empresa</option>
<option value="informacionFinanciera">informacion financiera</option>
</select>
<input class="col-xs-12 addingForm" type="file" id="documentPDF" name="documentPDF" accept="application/pdf" >
<span class="error col-xs-12" style="float:left">';
if( !empty($fileErr) ) {
$div .= "* ";
$div .= $fileErr;
}
$div .= ' </span>
<button class="btn btn-default buttonFunctionality" type="submit" name="add" value="add">Añadir</button>
';
if ( !empty($result) ){
$div.= $result;
}
$div .='
</form>
</div>
</div>';
echo $div ;
}
所以这就是我解决它的方法,我知道它现在非常复杂,因为我相信很多初学者都会像我一样得到堆栈。我希望我能为任何人节省一些时间。
感谢那些试图帮助我的人。
大家好,
我正在尝试使用 php 创建 CMS,但在执行下一步时遇到了问题:
我想删除、编辑或添加信息到我的页面,为此我使用了几个按钮和 AJAX 将表单加载到显示器 div。我让删除按钮完美地工作,但是当我尝试添加和编辑按钮时它不起作用,因为他们要求附加一些 html 文本,其中也包含 php 代码,所以没有PHP 解释器来阅读它。
我的做法:
<div class="displayHere col-xs-12"> </div>
为空。- 我点击添加按钮,它会转到 ajax.php 并附加表单和表单验证。
- 我填写了表格并单击 add_document,表格验证 (php) 检查数据并在可能的情况下上传文档并设置一些输出变量。
如何获得此功能?可能是我处理的不好,希望大家分享经验。
例如,对于add函数,我想获得这个功能:
<div id="bodyDiv">
<!--HEADER-->
<header id="header" class=" row">
<?php
include 'includes/loadHeader.php';
echo '<nav class="col-xs-6 cms_nav">
<ul>
<li><input id="buttonAdd" type="submit" class="button buttonFuncitonality" name="AÑADIR" value="AÑADIR" /></li>
</ul>
</nav>';
?>
<div class="displayHere col-xs-12">
<?php
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$nameErr = $dateErr = $typeErr = $fileErr = "";
$name = $date = $type = $file = $matches = "";
$success = true;
if ($_SERVER["REQUEST_METHOD"] == "POST"){
// name, date, type, path
if (empty($_POST["name"])) {
$nameErr = "El nombre es necesario";
$success = FALSE;
}
else {
$name = test_input($_POST["name"]);
}
if (!empty($_POST["date"])) {
$date = test_input($_POST["date"]);
$time_pattern = "(([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]))?";
//Check the date format http://www.phpliveregex.com/ (0|[1-9]|0[1-9]|[1-2][0-9]|3[0-1])-(0[1-9]|1[0-2])-([0-9]{4})\s+([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])
if (preg_match("/^(0|[1-9]|0[1-9]|[1-2][0-9]|3[0-1])-(0[1-9]|1[0-2])-([0-9]{4})\s*".$time_pattern."/",$date,$matches)){
echo "<script>console.log('yeahh format 1');</script>";
echo "<script>console.log('yeahh format 1 ". $date. " ". str_replace("-","/",$matches['0']) ." yeahh format 1');</script>";
$date = str_replace("-","/",$matches['0']);
}
elseif (preg_match("/^(0|[1-9]|0[1-9]|[1-2][0-9]|3[0-1])\/(0[1-9]|1[0-2])\/([0-9]{4})\s*".$time_pattern."/",$date, $matches)){
}
else{
echo "<script>console.log('noooo ". $date. " " . $matches['0'] ." yeahh format 1');</script>";
$dateErr = "Formato de fecha incorrecto";
$success = FALSE;
}
//The formar mysql is expecting DATETIME '0000-00-00 00:00:00'
if(empty($dateErr)){
if( preg_match("/\s([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])/",$date)){
$date = DateTime::createFromFormat('j/m/Y H:i', $date);
$date = $date->format('d-m-Y H:i');
}
else{
$date = DateTime::createFromFormat('j/m/Y', $date);
$date = $date->format('d-m-Y');
}
echo "<script>console.log('date ".$date."');</script>";
}
}
if (empty($_POST["type"]) ) {
$typeErr = "El tipo de documento es necesario";
$success = FALSE;
}
else{
$type = test_input($_POST["type"]);
}
// Upload the file
if($success ){
if(empty($_FILES['documentPDF']['name'])){
$fileErr = "Debes añadir un documento pdf ";
}
else{
$target_dir = "shareholders_documents/".$type. "/";
$file_name = basename($_FILES["documentPDF"]["name"]);
$target_file = $target_dir . $file_name;
echo "<script>console.log('".$target_file."');</script>";
$fileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
//echo " vamos a ver que hay aqui " .$target_file;
// Check if pdf already exist
if (file_exists($target_file)) {
$fileErr = "Este documento ya existe.";
$success = false;
}
if ($_FILES["documentPDF"]["size"] > 500000) {
$fileErr = "El documento es demasiado largo";
$success = false;
}
// Allow certain file formats
if($fileType != "pdf" ) {
$fileErr = "El documento debe estar en formato pdf";
$success = false;
}
// Check if $uploadOk is set to 0 by an error
if ($success == true ) {
//echo "\nmove_uploaded_file(".$_FILES["documentPDF"]["tmp_name"].", ".$target_file.")" ;
if (!move_uploaded_file($_FILES["documentPDF"]["tmp_name"], $target_file)) {
$fileErr ="No se ha podido almacenar el documento ". basename( $_FILES["documentPDF"]["name"]);
$success = false;
}
}
}
}
}
$result="";
// Now we have to prepare the data for the sql operation
if( isset( $_POST["insert"] ) && $success ){
$name = test_input($_POST['name']);
$date = $date;
$type = test_input($_POST['type']);
$path = $file_name;
$id = $type ." ". $date . " " . $path ;
//Create $sql sentence
$sql = "INSERT INTO `shareholders_documents`(`id`, `name`, `date`, `type`, `path`) VALUES ('".$id."','".$name."',STR_TO_DATE('".$date."', '%d-%m-%Y %H:%i'),'".$type."','".$path."')";
$sqlResult = $conn->query($sql);
$message= "";
if($conn->error){
$message = $conn->error;
$success = false;
}
//Sending email
if ($success){
$result='<div class="alert alert-success margin-top-big">El documento se ha subido correctamente'.$name." ".$date." ".$type." ". $path. "\n" . $sql. '</div>';
}
else{
$result = '<div class="alert alert-danger margin-top-big">Algo ha fallado y el documento no se ha podido subir ' . $message . '</div>';
if(empty($fileErr)){ //If we cannot insert the document we must delete the file
unlink($target_file);
}
}
}
//Cleaning global array $_POST
$_POST = array();
$_FILE = array();
?>
<div id="insertForm" class="col-xs-12 shareholdersForm">
<h3>Insertar</h3>
<form method="POST" enctype="multipart/form-data">
<input class="col-xs-12 form-control <?php if( !empty($nameErr) ) {echo 'boxError alert-danger ' ;} ?> " value="<?php if( !$success ) {echo $name;}?>" type="text" name="name" placeholder="<?php if( !empty($nameErr) ) {echo $nameErr;}else{ echo 'nombre';}?>">
<input class="col-xs-12 form-control <?php if( !empty($dateErr) ) {echo 'boxError alert-danger ' ;} ?> " value="<?php if( !$success ) {echo $date;}?>" type="text" name="date" placeholder="<?php if( !empty($dateErr) ) {echo $dateErr;}else{ echo 'fecha (Ejemplo de formato: 31/10/2017 17:54)';}?>">
<select class="col-xs-12 form-control <?php if( !empty($typeErr) ) {echo 'boxError alert-danger ' ;} ?> " name="type">
<option value="hechosRelevantes">hecho relevantes</option>
<option value="informacionEmpresa">informacion empresa</option>
<option value="informacionFinanciera">informacion financiera</option>
</select>
<input class="col-xs-12" type="file" name="documentPDF" accept="application/pdf" >
<span class="error col-xs-12" style="float:left"> <?php if( !empty($fileErr) ) {echo "* ". $fileErr;} ?> </span>
<button class="btn btn-default" type="submit" name="insert">Añadir</button>
<?php if ( !empty($result) ){ echo $result; } ?>
</form>
</div>
</div>
在我的网站上,我有一个添加按钮,应该使用 AJAX 上传表单验证。
<?php
//echo "piece of shit";
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'AÑADIR': //ADD FUNCTIONALITY
add_document();
break;
default:
echo "La accion no se indentifica\n" ;
break;
}
}
function add_document() {
echo ' <div id="insertForm" class="col-xs-12 shareholdersForm">
<h3>Insertar</h3>
<form method="POST" enctype="multipart/form-data">
<input class="col-xs-12 form-control <?php if( !empty($nameErr) ) {echo "boxError alert-danger " ;} ?> " value="<?php if( !$success ) {echo $name;}?>" type="text" name="name" placeholder="<?php if( !empty($nameErr) ) {echo $nameErr;}else{ echo "nombre";}?>">
<input class="col-xs-12 form-control <?php if( !empty($dateErr) ) {echo "boxError alert-danger " ;} ?> " value="<?php if( !$success ) {echo $date;}?>" type="text" name="date" placeholder="<?php if( !empty($dateErr) ) {echo $dateErr;}else{ echo "fecha (Ejemplo de formato: 31/10/2017 17:54)";}?>">
<select class="col-xs-12 form-control <?php if( !empty($typeErr) ) {echo "boxError alert-danger" ;} ?> " name="type">
<option value="hechosRelevantes">hecho relevantes</option>
<option value="informacionEmpresa">informacion empresa</option>
<option value="informacionFinanciera">informacion financiera</option>
</select>
<input class="col-xs-12" type="file" name="documentPDF" accept="application/pdf" >
<span class="error col-xs-12" style="float:left"> <?php if( !empty($fileErr) ) {echo "* ". $fileErr;} ?> </span>
<button class="btn btn-default" type="submit" name="insert">Añadir</button>
<?php if ( !empty($result) ){ echo $result; } ?>
</form>
</div>
</div>';
}
function load_delete_document_form($id) {
echo ' <div id="deleteForm" class="col-xs-12 shareholdersForm">
<h3>Eliminar '. $id.'</h3>
<form id="'.$id.'" method="POST">
<button class="btn btn-default buttonFunctionality" type="submit" name="Delete" value="Delete">Eliminar</button>
</form>
</div>
';
exit;
}
?>
为了使用那个 AJAX 代码,我在我的网站上使用了这个 jquery 函数:
<script>
//$(document).ready(function(){
$("body").on("click",".buttonFunctionality", function(){
if($('.displayHere').length !== 0){
$('.displayHere').children().remove()
}
var action = $(this).val();
var id = $(this).parent().attr('id');
console.log(action + " " + id);
$.post("includes/ajax.php",{ action: action, id: id}, function(data, status){
console.log("click1 " + id );
console.log("data " + data);
$('.displayHere').append(data); // This append will append the code I will need in my page
});
});
//});
</script>
由于我的代码,我得到了带有大量 php 代码的表单,没有解释。
问题来自您的 add_document() 函数;
因为它是 php 你不必使用 <?php
?>
而是将字符串连接在一起然后回显整个事情
应该看起来像这样:
function add_document() {
$div = ' <div id="insertForm" class="col-xs-12 shareholdersForm">
<h3>Insertar</h3>
<form method="POST" enctype="multipart/form-data">
<input class="col-xs-12 form-control ';
if( !empty($nameErr) ) {
$div .= "boxError alert-danger ";
}
$div .= '" value="';
if( !$success ) {
$div .= $name;
}
$div .= '" type="text" name="name" placeholder="';
//more code
echo $div;
}
希望你明白了
编辑:
这里的另一个问题是您试图在没有 re-submiting 的情况下在表单的 ajax 一侧进行表单验证;
我建议通过将 required
添加到您的输入标签来使用默认表单验证;
您的函数应如下所示:
function add_document() {
$nameVal = (!$success ) ? $name : "";
$dateVal = (!$success ) ? $date : "";
$resultVal = (!empty($result) ) ? $result : "";
$nameErrVal = (!empty($nameErr)) ? $nameErr : "nombre";
$dateErrVal = (!empty($dateErr)) ? "boxError alert-danger " : "";
$dateErrVal2 = (!empty($dateErr)) ? $dateErr : "fecha (Ejemplo de formato: 31/10/2017 17:54)";
$typeErrVal = (!empty($typeErr)) ? "boxError alert-danger" : "";
$fileErrVal = (!empty($fileErr)) ? "* ". $fileErr : "";
$div = ' <div id="insertForm" class="col-xs-12 shareholdersForm">
<h3>Insertar</h3>
<form method="POST" enctype="multipart/form-data">
<input class="col-xs-12 form-control " value="'.$nameVal.'" type="text" name="name" placeholder="'
.$nameErrVal.'" required>
<input class="col-xs-12 form-control '.$dateErrVal.'" value="'.$dateVal.'"
type="text" name="date" placeholder="'.$dateErrVal2.'" required>
<select class="col-xs-12 form-control '.$typeErrVal.'" name="type">
<option value="hechosRelevantes">hecho relevantes</option>
<option value="informacionEmpresa">informacion empresa</option>
<option value="informacionFinanciera">informacion financiera</option>
</select>
<input class="col-xs-12" type="file" name="documentPDF" accept="application/pdf" required>
<span class="error col-xs-12" style="float:left"> '.$fileErrVal.' </span>
<button class="btn btn-default" type="submit" name="insert">Añadir</button>
'.$resultVal.'
</form>
</div>
</div>';
echo $div;
}
它应该输出类似的东西:https://jsfiddle.net/p6147nh0/11/
我想你可以用 html 属性检查它 required
是否为空输入
对于其他类似用户刚刚使用 php 函数 empty($value)
我终于找到了解决办法。这是我的第一种方法:
<div class="displayHere col-xs-12"> </div>
为空。我点击添加按钮,它会转到 ajax.php 并附加表格和表格 验证。 (这部分是错误的或者至少我没有得到它 工作,我无法将表单验证附加到前面。相反,我 必须检查 AJAX 文件的所有内容,该文件将检查 一切都将 return 只是 html 已经形成。)
3-我填写了表格并点击add_document,表格验证(php) 检查数据并在可能的情况下上传文档并设置 一些输出变量。
因为它不起作用,我尝试向我的 AJAX 发送验证表单所需的所有信息,并从中获取已经创建的 html。
- 为空。
我点击添加按钮(有两个添加按钮,一个用于上传表格,另一个用于发送填写的表格),它将转到 AJAX 并将 return 对我来说 将附加到页面的表单。
相关的 信息公司 信息金融时代 阿纳迪尔将填写表格并点击 Añadir。该按钮关联了一个 javascript 函数。
$(document).ready(function(){ $("body").on("click",".buttonFunctionality", function(e){ e.preventDefault(); var action = $(this).val(); var id = $(this).parent().attr('id'); var formdata = new FormData($("#insertForm>form")[0]); formdata.append("action", action); formdata.append("id",id); $.ajax({ url: "includes/ajax.php", // Url to which the request is send type: "POST", // Type of request to be send, called as method data: formdata, // Data sent to server, a set of key/value pairs (i.e. form fields and values) contentType: false, // The content type used when sending data to the server. cache: false, // To unable request pages to be cached processData:false, // To send DOMDocument or non processed data file it is set to false success: function(data) // A function to be called if request succeeds { console.log("SUCCESS"); if($('.displayHere').length !== 0){ $('.displayHere').children().remove() } $(".displayHere").append(data); } }); }); }); //}); </script>
3-一开始我试图创建一个 JSON 来将信息发送到我的 ajax.php,但是后来,我意识到有一个方法 var formdata = new FormData($(" #insertForm>form") 提供了我处理表单验证所需的所有信息($_POST,$_File ...)。所以最后这个方法是我需要解决它的最后一个细节。
此函数将信息发送到ajax.php,并在ajax.php中处理php代码。
AJAX.php
<?php
session_start();
include 'dbh.inc.php';
$message = $sql = "";
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'AÑADIR':
add_document($_POST['action']);
break;
case 'add':
echo("<script>console.log(' ADD ');</script>");
echo("<script>console.log(' PHP tmp_name :". $_FILES['documentPDF']['tmp_name']."');</script>");
if(isset($_FILES["documentPDF"]["type"]))
{
echo("<script>console.log(' PHP tmp_name :". $_FILES['documentPDF']['tmp_name']."');</script>");
}
add_document($_POST['action']);
break;
case 'Editar':
if (isset($_POST['id'])) {
load_edit_document($_POST['id']);
break;
}
case 'Edit':
if (isset($_POST['id'])) {
edit_document($_POST['id']);
break;
}
case 'Eliminar':
if (isset($_POST['id'])) {
echo("<script>console.log('PHP id: ".$_POST['id']."');</script>");
load_delete_document_form($_POST['id']);
break;
}
case 'Delete':
if (isset($_POST['id'])) {
delete_document($_POST['id']);
break;
}
default:
echo "La accion no se indentifica\n" ;
break;
}
}
function add_document($action) {
echo "<script>console.log('INSIDE ADD_DOCUMENT');</script>";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$nameErr = $dateErr = $typeErr = $fileErr = "";
$name = $date = $type = $file = $matches = "";
$success = true;
if ($_SERVER["REQUEST_METHOD"] == "POST" && $action == 'add' ){
echo "<script>console.log('INSIDE REQUEST_METHOD');</script>";
// name, date, type, path
if (empty($_POST["name"])) {
$nameErr = "El nombre es necesario";
$success = FALSE;
}
else {
$name = test_input($_POST["name"]);
}
if (!empty($_POST["date"])) {
$date = test_input($_POST["date"]);
$time_pattern = "(([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]))?";
//Check the date format http://www.phpliveregex.com/ (0|[1-9]|0[1-9]|[1-2][0-9]|3[0-1])-(0[1-9]|1[0-2])-([0-9]{4})\s+([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])
if (preg_match("/^(0|[1-9]|0[1-9]|[1-2][0-9]|3[0-1])-(0[1-9]|1[0-2])-([0-9]{4})\s*".$time_pattern."/",$date,$matches)){
echo "<script>console.log('yeahh format 1');</script>";
echo "<script>console.log('yeahh format 1 ". $date. " ". str_replace("-","/",$matches['0']) ." yeahh format 1');</script>";
$date = str_replace("-","/",$matches['0']);
}
elseif (preg_match("/^(0|[1-9]|0[1-9]|[1-2][0-9]|3[0-1])\/(0[1-9]|1[0-2])\/([0-9]{4})\s*".$time_pattern."/",$date, $matches)){
}
else{
echo "<script>console.log('noooo ". $date. " " . $matches['0'] ." yeahh format 1');</script>";
$dateErr = "Formato de fecha incorrecto";
$success = FALSE;
}
//The formar mysql is expecting DATETIME '0000-00-00 00:00:00'
if(empty($dateErr)){
if( preg_match("/\s([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])/",$date)){
$date = DateTime::createFromFormat('j/m/Y H:i', $date);
$date = $date->format('d-m-Y H:i');
}
else{
$date = DateTime::createFromFormat('j/m/Y', $date);
$date = $date->format('d-m-Y');
}
echo "<script>console.log('date ".$date."');</script>";
}
}
if (empty($_POST["type"]) ) {
$typeErr = "El tipo de documento es necesario";
$success = FALSE;
}
else{
$type = test_input($_POST["type"]);
}
// Upload the file
if($success ){
if(empty($_FILES['documentPDF']['name'])){
$fileErr = "Debes añadir un documento pdf ";
}
else{
$target_dir = "../shareholders_documents/".$type. "/";
$file_name = basename($_FILES["documentPDF"]["name"]);
$target_file = $target_dir . $file_name;
echo "<script>console.log('".$target_file."');</script>";
$fileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
//echo " vamos a ver que hay aqui " .$target_file;
// Check if pdf already exist
if (file_exists($target_file)) {
$fileErr = "Este documento ya existe.";
$success = false;
}
if ($_FILES["documentPDF"]["size"] > 1000000) {
$fileErr = "El documento es demasiado largo";
$success = false;
}
// Allow certain file formats
if($fileType != "pdf" ) {
$fileErr = "El documento debe estar en formato pdf";
$success = false;
}
// Check if $uploadOk is set to 0 by an error
if ($success == true ) {
if (!move_uploaded_file($_FILES["documentPDF"]["tmp_name"], $target_file)) {
$fileErr ="No se ha podido almacenar el documento ". basename( $_FILES["documentPDF"]["name"]);
$success = false;
}
}
}
}
}
$result="";
// Now we have to prepare the data for the sql operation
if( $action == 'add' && $success ){
$name = test_input($_POST['name']);
$date = $date;
$type = test_input($_POST['type']);
$path = $file_name;
$id = $type ." ". $date . " " . $path ;
//Create $sql sentence
include 'dbh.inc.php';
$sql = "INSERT INTO `shareholders_documents`(`id`, `name`, `date`, `type`, `path`) VALUES ('".$id."','".$name."',STR_TO_DATE('".$date."', '%d-%m-%Y %H:%i'),'".$type."','".$path."')";
$sqlResult = $conn->query($sql);
$message= "";
if($conn->error){
$message = $conn->error;
$success = false;
}
//Sending email
if ($success){
$result='<div class="alert alert-success margin-top-big">El documento se ha subido correctamente'.$name." ".$date." ".$type." ". $path. "\n" . $sql. '</div>';
}
else{
$result = '<div class="alert alert-danger margin-top-big">Algo ha fallado y el documento no se ha podido subir ' . $message . '</div>';
if(empty($fileErr)){ //If we cannot insert the document we must delete the file
unlink($target_file);
}
}
}
//Cleaning global array $_POST
$_POST = array();
$_FILE = array();
//
// Form validation
//
$div = ' <div id="insertForm" class="col-xs-12 shareholdersForm">
<h3>Insertar</h3>
<form method="POST" action="" enctype="multipart/form-data">
<input class="col-xs-12 form-control addingForm ' ;
if( !empty($nameErr) ) {
$div .= "boxError alert-danger " ;
}
$div.= '" value="';
if( !$success ) {
$div .= $name;
}
$div .='" type="text" name="name" placeholder=" ';
if( !empty($nameErr) ) {
$div .= $nameErr;
}else{
$div .= "nombre";
}
$div .= '" required>
<input class="col-xs-12 form-control addingForm ';
if( !empty($dateErr) ) {
$div .= "boxError alert-danger " ;
}
$div .=' " value="';
if( !$success ) {
$div .= $date;
}
$div .= '" type="text" name="date" placeholder=" ';
if( !empty($dateErr) ) {
$div.= $dateErr;
}else{
$div.= "fecha (Ejemplo de formato: 31/10/2017 17:54)";
}
$div .='" required>
<select class="col-xs-12 form-control addingForm ';
if( !empty($typeErr) ) {
$div .= "boxError alert-danger" ;
}
$div.= ' " name="type">
<option value="hechosRelevantes">hecho relevantes</option>
<option value="informacionEmpresa">informacion empresa</option>
<option value="informacionFinanciera">informacion financiera</option>
</select>
<input class="col-xs-12 addingForm" type="file" id="documentPDF" name="documentPDF" accept="application/pdf" >
<span class="error col-xs-12" style="float:left">';
if( !empty($fileErr) ) {
$div .= "* ";
$div .= $fileErr;
}
$div .= ' </span>
<button class="btn btn-default buttonFunctionality" type="submit" name="add" value="add">Añadir</button>
';
if ( !empty($result) ){
$div.= $result;
}
$div .='
</form>
</div>
</div>';
echo $div ;
}
所以这就是我解决它的方法,我知道它现在非常复杂,因为我相信很多初学者都会像我一样得到堆栈。我希望我能为任何人节省一些时间。
感谢那些试图帮助我的人。