-1

I am trying to get an image from html tag in my JavaScript file and then use AJAX to call a PHP script that uploads it to the database.

My issue is getting the file data and then passing it to the PHP properly using AJAX.

What are my options for this?

Rob
  • 126
  • 9

3 Answers3

2

Have a look at this article from MDN on uploading a user-selected file

Getting files from <input type="file" /> with id="input":

var inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
    var fileList = this.files; /* now you can work with the file list */
}

Asynchronus file upload example from the article:

function sendFile(file) {
    var uri = "/index.php";
    var xhr = new XMLHttpRequest();
    var fd = new FormData();

    xhr.open("POST", uri, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            // Handle response.
            alert(xhr.responseText); // handle response.
        }
    };
    fd.append('myFile', file);
    // Initiate a multipart/form-data upload
    xhr.send(fd);
}

Also check out How can I upload files asynchronously?

Community
  • 1
  • 1
llernestal
  • 576
  • 2
  • 8
2

You can just use a FormData() object to retrieve file from your input element and pass to your ajax function. Here is an example:

     var data = new FormData();
     var file = $('#yourInput').files[0];
     var params = $('#yourForm').serializeArray();
     $.each(params,function(key, element){
         data.append(element.name, element.value);
     });
     data.append($('#yourInput').name, file);
    $.ajax({
    url: 'yourfile.php',
    data: data,
    type: 'POST',
    contentType: false,
    processData: false,
    success: function(result){
        alert(result);
    }
Oluwatumbi
  • 1,321
  • 1
  • 12
  • 19
1

Assuming you are using jquery (if you are not, ignore this answer):

Using jquery's get or post functions tend to be problematic for file uploads, it's best to use the ajax function so you can pass all desired options:

        yourOnSubmitHandlerFunction() {     
            //make form object with specific enctype
            var form = document.createElement('form');
            form.enctype = "application/x-www-form-urlencoded";

            //FormData object to store all form key/values
            var formdata = new FormData(form);

            //get file data
            var file = document.getElementById('image_upload_input_id').files[0];
            //append file data       
            if (file) {
                formdata.append('image_input_name', file);
            }

            //append other inputs
            formdata.append('input1_name', val);
            formdata.append('input2_name', val);

            //submit form to remote file with POST
            $.ajax("phpfile.php", {
                type: "POST",
                data: formdata,             
                cache: false,
                contentType: false,
                processData: false,
                success: function(data, textStatus){ /* Success */ }
            });
        });
Kevin M
  • 331
  • 1
  • 6
  • Thanks! This works great!. I was not using a form and the document.createElement('form'); was the key. – Rob Jan 28 '15 at 18:00