祝大家有美好的一天,
我正在尝试使用 php 创建一个 CMS,但在执行以下操作时遇到了麻烦:
我想删除、编辑或向我的页面添加信息,为此我使用了几个按钮和 AJAX 将表单加载到显示 div。我让按钮删除工作完美,但是当我尝试添加和编辑按钮时它不起作用,因为他们要求附加一些也包含 php 代码的 html 文本,因此没有 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 代码的表单,没有解释。