1

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

<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:

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);

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

Vishal Kumar
  • 4,419
  • 1
  • 25
  • 31

1 Answers1

3

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.

Community
  • 1
  • 1
SJB
  • 193
  • 1
  • 1
  • 9
  • Fine... so what about the other input data that I am getting through var form = $('#myProfileForm'); var formData = $(form).serialize(); I also need them + File data – Vishal Kumar Jul 09 '16 at 07:55