Donatas Donatas - 5 days ago 4
PHP Question

Yet another jquery ajax file upload issue

This is probably repost as I might not searched deep enough in stackoverflow, though a few posts that I found haven't helped me enough. So I'm trying to do a simple thing - upload an image using ajax. I've got this HTML:

<form class="form-inline" id="navigationLinkCreationForm" >
<input type="text" class="form-control" placeholder="Nuorodos pavadinimas" id="linkName" />
<label class="btn btn-default btn-file">
Įkelti ikoną(1:1)<input id="selectNavigationIcon" name="navigationIcon" type="file" style="display: none;">
</label>
<input type="submit" class="btn btn-success" id="createLinkButton" value="Sukurti nuorodą" />
</form>


Then I've got this ajax:

$('#createLinkButton').on('click', uploadFiles);

function uploadFiles(event)
{
event.preventDefault();

var formData = new FormData($('#navigationLinkCreationForm'));

$.ajax({
type: 'POST',
url: '../php_includes/uploadNavigationIcon.php',
data:formData,
success: function (data)
{
console.log(data);
},
processData: false,
contentType: false,
cache: false
});
}


And finally I've got a simple uploadNavigationIcon.php file which just outputs "S" if files have been submitted

<?php
if(isset($_GET['files']))
{
echo "S";
}


After running this I'm just getting empty output, which just means that files weren't submitted.

Answer

Try this, its a tested and working code:

$(document).ready(function(){
    $('#upload').on('click', function() {
        var file_data = $('#pic').prop('files')[0];
        var form_data = new FormData();
        form_data.append('file', file_data);

        $.ajax({
                url         : 'upload.php',     // point to server-side PHP script 
                dataType    : 'text',           // what to expect back from the PHP script, if anything
                cache       : false,
                contentType : false,
                processData : false,
                data        : form_data,                         
                type        : 'post',
                success     : function(output){
                    alert(output);              // display response from the PHP script, if any
                }
         });
         $('#pic').val('');                     /* Clear the file container */
    });
});

upload.php

<?php
    if ( $_FILES['file']['error'] > 0 ){    // file data can't be fetched by using $_GET
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    }
    else {
        if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
        {
            echo "File Uploaded Successfully";
        }
    }

?>
Comments