在CodeIgniter中使用AJAX上载文件即使值为null/undefined,仍然执行 [英] Upload file using AJAX in CodeIgniter Still executed even the value is null/undefined
问题描述
如果还没有输入文件,我想执行另一个ajax.但它仍会发布表单操作.
I want to execute another ajax if the file is not input yet. But it still posting the form action.
这是我的查看代码:
<form method="POST" id="quiz_file" action="<?php echo site_url('home/upload_quiz/' . $kelas);?>" enctype="multipart/form-data">
<input name="filequiz" id="filequiz" type="file" />
</form>
这是我的JS:
$('#submitquiz').on('click', function(event) {
var inputFile = $('input[name=filequiz]');
document.getElementById('submitquiz').disabled = true;
var fileToUpload = inputFile[0].files[0];
// make sure there is file to upload
if (undefined != fileToUpload)
{
var uploadURI = $('#quiz_file').attr('action');
var formData = new FormData();
formData.append("file", fileToUpload);
alert('if');
$.ajax({
url: uploadURI,
type: 'post',
data:
{
formData : formData,
asid : asid_quiz,
value : cmbValue
},
processData: false,
contentType: false,
success: function(data)
{
}
});
}
else
{
alert('else');
$.ajax(
{
type: 'POST',
url:'<?php echo site_url("home/assignment_score"); ?>',
data:
{
asid : asid_quiz,
value : cmbvalue,
kelas : <?php echo $kelas;?>,
dataType:"JSON"
},
success: function(data)
{
console.log('asdasd' + data);
alert('Quiz score submitted');
}
});
当我刚执行它时,它显示警报消息"else".但是它仍然会执行表单操作中的上载操作.
When i just executed it, it show alert message "else". But it still perform the upload action from form action.
这怎么可能发生?如何停止执行上载动作并在该其他"侧执行另一个ajax请求?
How this could be happen ? How to stop performing the upload action and perform the another ajax request in that 'else' side ?
推荐答案
如果您的submitquiz按钮类型为submit,则必须防止单击时发生submit事件,也可以将其更改为输入类型按钮.
If your submitquiz button type is submit you have to prevent submit event on click or you can change it to input type button.
如果您使用ajax发送数据,我也更喜欢您,那么您必须使用输入按钮而不是提交
I prefer you too if you are send data using ajax then you have to use input button instead of submit
$('#submitquiz').on('click', function(event) {
event.preventDefault();
这篇关于在CodeIgniter中使用AJAX上载文件即使值为null/undefined,仍然执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!