使用AJAX的PHP中的图像上传Jquery无法正常工作

时间:2022-08-28 07:42:54

I have a form with 4 text fields and one image file. I have to upload it via AJAX call. After working for 2 days... I have made it working ..however there is an issue

我有一个包含4个文本字段和一个图像文件的表单。我必须通过AJAX调用上传它。工作了2天后......我已经让它工作了......但是有一个问题

<script type="text/javascript">
$(document).ready(function(){

// Variable to store your files
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
// Grab the files and set them to our variable
function prepareUpload(event)
{
  files = event.target.files;
  //alert(files);
}


$("#myProfileForm").submit(function(event){
    event.preventDefault();
    document.getElementById("messageBlock").style.display = 'none';
    // Serialize the form data.
    var form = $('#myProfileForm');
    var formData = $(form).serialize();

    // Submit the form using AJAX.
$.ajax({
    type: 'POST',
    dataType: 'json',
    processData: false, 
    contentType: false, 
    url: $(form).attr('action')+'?'+files,
    data: formData
    alert(url);
}).done(function(response) {
    var formMessages = $('#form-messages');

    if(response.error){
        document.getElementById("messageBlock").style.display = 'block';
        $(formMessages).html(response.message);
    }else{
        document.getElementById("messageBlock").style.display = 'block';
        $(formMessages).html(response.message);
    }
})
}); 
});
</script>

My PHP file code:

我的PHP文件代码:

if (isset($_FILES['image_url'])){
$name       = $_FILES['image_url']['name'];  
$image_url = $name;
$temp_name  = $_FILES['image_url']['tmp_name'];  
if(isset($name)){
if(!empty($name)){      
    $location = 'uploads/';      
    if(move_uploaded_file($temp_name, $location.$name)){
    //echo 'File uploaded successfully';
            $image_url = UPLOADED_IMG_URL.''.$location.''.$name;
    }
}       
}  else {
$image_url = DEFAULT_IMAGE;
}
}else {
$image_url = '../../API/v1/uploads/default.PNG';
}

The PHP code works well. The issue is with the AJAX call. When I comment the //alert(url);

PHP代码运行良好。问题出在AJAX调用上。当我评论// alert(url);

Things stop working as if (isset($_FILES['image_url'])) returns false. Not sure..what is causing the issue.

事情停止工作,好像(isset($ _ FILES ['image_url']))返回false。不确定......导致问题的原因是什么。

1 个解决方案

#1


2  

serialize() would not work with multipart data ,instead, you should use Formdata() method. check out this stack question; also remove that alert from $.ajax ; you cant do that.

serialize()不适用于多部分数据,相反,您应该使用Formdata()方法。查看这个堆栈问题;也从$ .ajax删除该警报;你不能这样做。

#1


2  

serialize() would not work with multipart data ,instead, you should use Formdata() method. check out this stack question; also remove that alert from $.ajax ; you cant do that.

serialize()不适用于多部分数据,相反,您应该使用Formdata()方法。查看这个堆栈问题;也从$ .ajax删除该警报;你不能这样做。