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.

1
  • Object should consist of a key : value pair. You can't just put there an alert(url). Commented Jul 9, 2016 at 7:34

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.