[英]Submit form having file using java script submit button
java-script : i have a form that feed value to a controller via ajax call . java-script:我有一种形式,可以通过ajax调用将值提供给控制器。 The form get serialized in ajax call and the controller return 'true' on success but the problem is that my form have a file and the file can't be serialized .
表单在ajax调用中被序列化,并且控制器在成功时返回“ true”,但是问题是我的表单有一个文件,并且该文件无法序列化。 I am working out how i can receive the file in my controller using this ajax call .
我正在研究如何使用此Ajax调用在控制器中接收文件。
function save()
{
if(save_method == 'On_submitted')
{
url = "<?php echo site_url('MyController/insertForm')?>";
$.ajax({
url : url,
type: "POST",
data:$('#form_name').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_name').modal('hide');
alert('added successfully');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
}
When i omit the input file fields than its working fine , the main problem is to send the file to controller via java-script . 当我忽略输入文件字段而不是其正常工作时,主要问题是通过java-script将文件发送给控制器。 i have tries but i am don't know what is wrong and how can i do it .
我尝试过,但是我不知道哪里出问题了,我该怎么做。
you should not use dataType: "JSON"
if you sending files. 如果您发送文件,则不应使用
dataType: "JSON"
。
you can form data
for request using (filesForm = name of form): 您可以使用(filesForm =表单名称)来形成请求
data
:
var formData = new FormData(document.forms.filesForm);
then add other keys: 然后添加其他键:
formData.append("key", keyValue);
and to send this data, add this options to ajax call: 并发送此数据,请将以下选项添加到ajax调用中:
contentType: false,
cache: false,
processData: false,
you need contentType = false (it will be multipart/form-data in fact) if you wish to upload files. 如果您要上传文件,则需要contentType = false(实际上是多部分/表单数据)。 and final ajax call should be like this:
最后的ajax调用应如下所示:
$.ajax({
url: url,
data: formData,
contentType: false,
cache: false,
processData: false,
type: 'POST',
success: function (result) {
$("#result").html(result)
},
error: function (result) {
$("#result").html(result)
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.