0

I'm trying to upload image on user registration via ajax. This is how it's look like the form + some fields for name, password and email which are working good.

<form method="post" class="registerForm" enctype="multipart/form-data" id="login-form">
    <div class="form-group">
        <label><b>Profile Image <span class="required">*</span></b></label>
        <input accept="image/*" type="file" id="picture" name="picture" required>
    </div>
    <div class="clearfix">
        <button type="submit" id="login" class="signupbtn">Sign Up</button>
    </div>              
</form>

I have found on another thread here on SO that I need to put this on my ajax script

    var data = $("#login-form").serialize();
    var form = new FormData(document.getElementById('picture'));
    //append files
    var file = document.getElementById('picture').files[0];
    if (file) {   
        form.append('picture', file);
    }

And this is whole ajax

function submitForm()
{
    var data = $("#login-form").serialize();
    var form = new FormData(document.getElementById('picture'));
    //append files
    var file = document.getElementById('picture').files[0];
    if (file) {   
        form.append('picture', file);
    }
    $.ajax({

        type : 'POST',
        url  : 'registration.php',
        data : data,            
        beforeSend: function()
        {
            $("#error").fadeOut();
            $("#login").html('<span class="glyphicon glyphicon-transfer"></span> &nbsp; sending ...');
        },
        success :  function(data)
        {
            if(data=="registered")
            {                    
            }
        }
    });
    return false;
}

And the server side for the picture part and the query

if(!empty($_FILES['picture']) && $_FILES['picture']['size']  >0  ){

    $profilePic = $randomString. basename($_FILES['picture']['name']);
    $uploadfile = $uploaddir .$randomString. basename($_FILES['picture']['name']);

    if (move_uploaded_file($_FILES['picture']['tmp_name'], $uploadfile)) {
    } else {
        $error = "error\n";
    }
}else{
    $error ='Please add your Picture!';
}   
var_dump($_FILES['picture']);
try
{
    $stmt = $db_con->prepare("SELECT * FROM users WHERE email=:email");
    $stmt->execute(array(":email"=>$email));
    $count = $stmt->rowCount();

    if($count==0){
        $stmt = $db_con->prepare("INSERT INTO users (picture) VALUES (:picture)");
        $stmt->bindParam(":picture",$profilePic);

        if($stmt->execute()) {
            echo "registered";
        }
        else { echo "Query could not execute !"; }
    }
    else{ echo "1"; }
}
catch(PDOException $e){
    echo $e->getMessage();
}

I've removed other fields in order keep the code simple as much as possible. All fields got inserted and saved in database except the image name.

What can be the problem? No errors at all. I've got registered on the console and NULL for var_dump($_FILES['picture'])

  • 1
    You can not get files using simple ajax call. You can see this url. This will surely help you. https://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously/8758614#8758614 – Web Artisan Jul 04 '17 at 11:43
  • Still `Null` on the console. I've added this to my ajax since this is the difference I can see: `data: new FormData($('form')[0]), cache: false, contentType: false, processData: false,` –  Jul 04 '17 at 11:48

2 Answers2

0

You must set the contentType option to false, so jQuery won't add a Content-Type heade also set processData flag set to false otherwise jQuery will try to convert your FormData into a string, which will fail.

So ajax code will look like

    $(".signupbtn").click(function(e){
    e.preventDefault();
    var form = new FormData(document.getElementById('picture'));
//append files
var file = document.getElementById('picture').files[0];
if (file) {   
    form.append('picture', file);
}

    $.ajax({

        type : 'POST',
        url  : 'registration.php',
        data : form, 
        contentType: false,
        processData: false,         
        success :  function(data){}
    });
});
Manish Goyal
  • 700
  • 1
  • 7
  • 17
  • Thanks but like this is just reloading the page and doesn't save anything in database, including the fields which normally are saved –  Jul 04 '17 at 12:00
0

jQuery processes the data as a string if you don't use proccessData: false. Bellow code will work just fine. Also included some comments in code

$(document).ready(function (e){
    $("#login-form").on('submit',(function(e){
        e.preventDefault();
        $.ajax({
            url: "registration.php",
            type: "POST",
            data:  new FormData(this), // Data sent to server
            contentType: false, // The content type used when sending data to the server.
            cache: false, // To unable request pages to be cached
            processData:false,  // To send DOMDocument or non processed data file it is set to false
            success: function(data){
                    if(data=="registered"){}
            },
            error: function(){}             
        });
    }));
});
S.I.
  • 3,250
  • 12
  • 48
  • 77