[英]Image upload via Ajax in PHP[simplest way]
I have studied a lot of answers in stackOverflow but haven't figured out the simplest way of uploading an image from a form. 我在stackOverflow中研究了很多答案,但是还没有弄清楚从表单上载图像的最简单方法。 I am trying to figure out a way to upload an image using Ajax.
我试图找出一种使用Ajax上传图像的方法。 Although the form, PHP and Ajax coding is huge, I am giving you the important parts.
尽管PHP,Ajax编码的形式非常庞大,但我还是为您提供了重要的部分。 When I click the submit button, error message is shown, viz
undefined index
. 单击提交按钮时,显示错误消息,即
undefined index
。
HTML
<form method="post" enctype="multipart/form-data">
<tr>
<th>Image</th>
<td><input type="file" name="image" id="img"></td>
</tr>
</form>
Ajax
$(document).on('click','#sub_prod',function(event){
event.preventDefault();
$.ajax({
url:"product_add_back.php",
method:"post",
data:$('form').serialize(),
dataType:"html",
success:function(strMsg){
$("#prod_add").html(strMsg).show().fadeOut(3000);
}
})
})
PHP
$image_name=$_FILES["image"]["name"];
echo $image_name;
die();
$().serialize()
will not include $_FILES
content, so you need to use FormData
object $().serialize()
将不包含$_FILES
内容,因此您需要使用FormData
对象
$(document).on('click','#sub_prod',function(event){
event.preventDefault();
var formdata = new FormData($('form')[0]);
$.ajax({
url: "product_add_back.php",
method: "post",
data: formData,
processData: false,
contentType: false,
success: function(strMsg){}
});
});
Please note that you pass 3 params: data: formData
, processData: false
and contentType: false
请注意 ,您传递了3个参数:
data: formData
, processData: false
和contentType: false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.