0

I'm trying to create little photo uploader with PHP and Ajax. So i'm not a php guy and i have some problems with that, always Something went wrong with your upload! status. But when i set this as form action i have success action. Can anyboody help?

HTML:

<form onsubmit="return submitForm()" method="POST" enctype="multipart/form-data">
    <input type="file" name="pic" id="pic" multiple/>
    <input type="submit" value="Upload" for="pic"/>
</form>

PHP:

<?php

$demo_mode = false;
$upload_dir = 'uploads/';
$allowed_ext = array('jpg','jpeg','png','gif');

if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
    exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){

    $pic = $_FILES['pic'];

    if(!in_array(get_extension($pic['name']),$allowed_ext)){
        exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
    }
    if($demo_mode){
        $line = implode('       ', array( date('r'), $_SERVER['REMOTE_ADDR'], $pic['size'], $pic['name']));
        file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);

        exit_status('Uploads are ignored in demo mode.');
    }
    if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
        exit_status('File was uploaded successfuly!');
    }
}
exit_status('Something went wrong with your upload!');

function exit_status($str){
    echo json_encode(array('status'=>$str));
    exit;
}
function get_extension($file_name){
    $ext = explode('.', $file_name);
    $ext = array_pop($ext);
    return strtolower($ext);
}
?>

and JS:

function submitForm() {
    console.log("submit event");
    $.ajax({
        type: "POST",
        url: "post_file.php",
        enctype: 'multipart/form-data'
    }).done(function( data ) {
        console.log("PHP Output:");
        console.log( data );
    });
    return false;
}

Much Thx!

Lukas
  • 7,384
  • 20
  • 72
  • 127
  • instead of `exit_status()` use `die()` or `exit()` and your error maybe in the html form instead of `onsubmit="return submitForm()"` use `onsubmit="submitForm()"` it may not be the fix tho :) – roun512 May 06 '14 at 22:50
  • possible duplicate of [How can I upload files asynchronously with jQuery?](http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery) – showdev May 06 '14 at 22:51

1 Answers1

0

You can't transfer file data through AJAX (like that anyway). It used to be impossible, and so iframe hacks were used to get around it, but now with HTML5 you can do it using FormData. Take a look at this: Using HTML5 file uploads with AJAX and jQuery

Community
  • 1
  • 1
sahbeewah
  • 2,690
  • 1
  • 12
  • 18