Donatas Donatas - 1 year ago 94
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;">
<input type="submit" class="btn btn-success" id="createLinkButton" value="Sukurti nuorodą" />

Then I've got this ajax:

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

function uploadFiles(event)

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

type: 'POST',
url: '../php_includes/uploadNavigationIcon.php',
success: function (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

echo "S";

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

Answer Source

Try this, its a tested and working code:

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

                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 */


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download