Ajax 成功事件多错误不起作用
Ajax success event mutiple error not working
我有一个带有文件上传和进度条的表单。我使用 Ajax 提交提交表单。如果成功,它可以正常工作,但是当进程页面中的 2 个错误(如文件大小和扩展名)Ajax 成功部分没有响应时。
网页形式 :
<div class="col-md-8">
<form id='frm_upld' action="process.php" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<div id="status"></div>
<div class="form-group">
<label >Title</label>
<input type="text" id="imgTitle" class="form-control" name="imgTitle" value="" placeholder="Title">
</div>
<div class="form-group">
<label >Description</label>
<input type="text" id="imgdes" class="form-control" name="imgdes" value="" placeholder="Description">
</div>
<div class="form-group">
<label >Email</label>
<input type="text" id="email" class="form-control" name="email" value="" placeholder="Email">
</div>
<div class="form-group">
<label >Contact</label>
<input type="text" id="contact" class="form-control" name="contact" value="" placeholder="Contact">
</div>
<div class="form-group">
<label class="label" for="FileUpload">
Image File</label>
<input id="fileToUploadgallery" name="fileToUploadgallery" type="file" >
<label class="label" for="FileUpload"> ( File Must be jpg, jpeg ,png type)</label>
</div>
<div id="progresscstom">
<div class="progress progress-striped active">
<div class="progress-bar progress-bar-success bar"></div >
<div class="progress-bar percent">0%</div >
</div>
</div>
<button type="submit" name="submit" value="Submit" id="submit" class="btn btn-success">Submit</button>
</form> <!-- End Reg-Form -->
</div>
脚本代码:
<script>
$(document).ready(function() {
var bar = $('.bar');
var percent = $('.percent');
var statusmsg = $('#status');
$('form').ajaxForm({
dataType: 'json',
beforeSubmit: function() {
$('#frm_upld').validate({
rules:
{
imgTitle:
{
required: true
},
imgdes:
{
required: true
},
email:
{
required: true
},
contact:
{
required: true,
number: true,
minlength: 11,
maxlength: 11
},
fileToUploadgallery:
{
required: true
}
},
// Messages for form validation
messages:
{
imgTitle:
{
required: 'Please enter Title'
},
imgdes:
{
required: 'Please enter Description'
},
email:
{
required: 'Please enter email address'
},
contact:
{
required: 'Please enter contact number'
},
fileToUploadgallery:
{
required: 'Please select a File'
}
} });
return $('#frm_upld').valid();
statusmsg.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
$("#submit").prop('disabled', true); // disable button
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
success: function(data) {
var percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
alert(data);
if(data.type ==='success'){
statusmsg.html(data.message);
$("#frm_upld")[0].reset();
$("#submit").prop('disabled', false); // enable button
$("html, body").animate({ scrollTop: 0 }, "slow");
}else if(data.type === 'error'){
statusmsg.html(data.message);
$("#submit").prop('disabled', false); // enable button
$("html, body").animate({ scrollTop: 0 }, "slow");
}
}
});
});
</script>
PHP代码:
<?php
header('Content-type: application/json');
// Your db connection here
if(isset($_POST['submit']) && !empty($_POST['imgTitle']))
{
$response = array('type'=>'', 'message'=>'');
$imgTitle = $_POST['imgTitle'];
date_default_timezone_set("Asia/Dhaka");
$upload_date = date('Y-m-d h:i:s');
//$type = 1;
$time = time();
// your post data
$fileName = $_FILES["fileToUploadgallery"]["name"]; //basename($_FILES["fileToUploadgallery"]["name"]);
$fileSize = $_FILES["fileToUploadgallery"]["size"];
$tmp_file = $_FILES['fileToUploadgallery']['tmp_name'];
//$imageFileType = pathinfo($fileName,PATHINFO_EXTENSION);
$upload_file_name = "uploads/" . $time; // file upload with time you can change the file name here
$extension1 = getExtension($fileName); // file extentions function calling
$extension = strtolower($extension1);
$target_file = $upload_file_name . "." . $extension;
$uploadOk = 1;
// Check if file already exists
if (file_exists($target_file)) {
$response['type'] = 'success';
$response['message'] = '<div class="alert alert-warning"><strong>File Already Exists </div>';
echo json_encode($response);
$uploadOk = 0;
}
// Check file size
if ($fileSize > 704857600) {
$response['type'] = 'error';
$response['message'] = '<div class="alert alert-warning"> File Size must be less than 700MB.</div>';
echo json_encode($response);
$uploadOk = 0;
}
// Allow certain file formats
if($extension != "png" && $extension != "mp4" && $extension != "docx" && $extension != "pdf" && $extension != "jpg") {
$response['type'] = 'error';
$response['message'] = '<div class="alert alert-warning"> File Extention must be jpg ,jpeg or png type.</div>';
echo json_encode($response);
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$response['type'] = 'error';
$response['message'] = '<div class="alert alert-warning"> Sorry, your file was not uploaded.</div>';
echo json_encode($response);
$uploadOk = 0;
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($tmp_file, $target_file)) {
// $data = array ($imgTitle,$upload_date,$target_file);
$result = false; // "";// your data insert query
if($result){
$response['type'] = 'success';
$response['message'] = '<div class="alert alert-success"><strong>Congratulations!</strong> Added Successfully.</div>';
echo json_encode($response);
}else{
$response['type'] = 'error';
$response['message'] = '<div class="alert alert-warning"> Sorry, your file was not uploaded.</div>';
echo json_encode($response);
}
} else {
$response['type'] = 'error';
$response['message'] = '<div class="alert alert-warning"> Sorry, your file was not uploaded.</div>';
echo json_encode($response);
}
}
}else{
$response['type'] = 'error';
$response['message'] = '<div class="alert alert-warning"> Sorry, your file was not uploaded.</div>';
echo json_encode($response);
}
// getting file extentions
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
?>
您的代码在SUCCESS
上运行良好,因为输出仅打印一次。
如果出现错误,JSON
输出对一个错误进行两次回显,对 2 个错误进行三次回显,依此类推。因此,JavaScript
无法验证输出。
您需要更改代码,以便仅打印一次JSON
,并连接错误消息以一次显示所有可能的错误。
进行了纠正,请尝试以下代码:
// Check if file already exists
if (file_exists($target_file)) {
//$response['type'] = 'success'; //REMOVE THIS LINE
$response['message'] = '<div class="alert alert-warning"><strong>File Already Exists </div>';
//echo json_encode($response); //REMOVE THIS LINE
$uploadOk = 0;
}
// Check file size
if ($fileSize > 704857600) {
//$response['type'] = 'error'; //REMOVE THIS LINE
$response['message'] = '<div class="alert alert-warning"> File Size must be less than 700MB.</div>';
//echo json_encode($response); //REMOVE THIS LINE
$uploadOk = 0;
}
// Allow certain file formats
if($extension != "png" && $extension != "mp4" && $extension != "docx" && $extension != "pdf" && $extension != "jpg") {
//$response['type'] = 'error'; //REMOVE THIS LINE
$response['message'] = '<div class="alert alert-warning"> File Extention must be jpg ,jpeg or png type.</div>';
//echo json_encode($response); //REMOVE THIS LINE
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$response['type'] = 'error';
// CONCATENATE THE ERROR MESSAGE
$response['message'] = $response['message'] . '<div class="alert alert-warning"> Sorry, your file was not uploaded.</div>';
echo json_encode($response);
$uploadOk = 0;
// if everything is ok, try to upload file
}
相关文章:
- jquery中出现NaN错误.已经尝试过ParseInt,但仍然不起作用
- 未捕获的类型错误:无法设置属性'innerHTML'如果为null,则将脚本移动到正文不会;不起作用
- 错误检查在Javascript中不起作用
- Javascript设置日期不起作用,显示错误的时间
- javascript函数,该函数不起作用,但不会显示任何错误
- 属性选择器不起作用(语法错误、无法识别的表达式)
- .fillStyle 不起作用,控制台中没有错误
- 简单的jquery不起作用,并返回错误
- 点击按钮dons'它在IE9中不起作用,但没有错误消息(它在chrome中起作用)
- jQuery验证不起作用:需要知道错误
- jQuery alerts在jQuery 1.11.2上不起作用;类型错误:n.browser未定义;
- Twitter引导程序弹出在网站上不起作用:未获取引用错误
- 错误验证在AngularJS中不起作用
- 使用Javascript在模态内部的标签上显示错误消息不起作用
- 当展开点击 li 的 ul 事件时,JS JQUERY 错误不起作用
- Ajax 成功事件多错误不起作用
- 地理定位功能错误不起作用
- 滚动到第一个错误不起作用
- Ajax-jQuery和Ajax错误/不起作用
- 在catch块中抛出新的错误不起作用