user9304280
user9304280

Reputation:

Uploading File Images with AJAX and PHP

I am attempting to create an upload document which will upload a profile picture. I am having trouble capturing the data from the changePicture form which only has an input for the images and a submit. I have never used the FormData object to date, so I am still learning around this. Any guidance would be useful.

See my HTML

<form id="changePicture" method="post" enctype="multipart/form-data">
        <div class="form-group">
            <label for="name">Update Your Profile Picture</label>
            <input type="file" id="profilePic" class="form-control" name="profilePic">
            <input type="hidden" value="<?php echo $id; ?>" name="id">
        </div>
        <button type="submit" id="updateProfileBtn" class="btn btn-success float-right">Upload Image</button>
 </form>

Here is my AJAX code:

function updateProfilePic(){
$("#changePicture").on("submit", function(e) {
    e.preventDefault();

    $("#spinner").show();

    setTimeout(function(){
        $.ajax({
           url: "../ajax/admin/updateProfilePic.php",
           type: "POST",
           data: new FormData(this),   
           cache: false,
           contentType: false,
           processData: false,
           success: function(result){
               $("#spinner").hide();
               $("#changePicture").append(result);

               setTimeout(function(){
                $("#changePicture").slideDown();
               }, 1500);
           }
        });
    }, 3000);
});    
}

The PHP file at this moment only echos out "Working" to see it accesses the page alright, which it does. However, when I attempt to locate the file through a variable nothing has been sent and returns undefined index.

Upvotes: 1

Views: 316

Answers (2)

Christoph
Christoph

Reputation: 194

Why are you wrapping your AJAX call in a

setTimeout(function() {..})

?

By doing this, you cannot simply write new FormData(this), because the this context does not refer to the form that you are looking for.

Try executing the code without the timeout, or try storing the form data in a global variable

Edit: Example added:

var myFormData;

function updateProfilePic(){
$("#changePicture").on("submit", function(e) {
    e.preventDefault();

    $("#spinner").show();
    myFormData = new FormData(this);

    setTimeout(function(){
       $.ajax({
           url: "../ajax/admin/updateProfilePic.php",
           type: "POST",
           data: myFormData, 
           ....

Upvotes: 1

Carlos Alves Jorge
Carlos Alves Jorge

Reputation: 1985

this will be undefined because it's inside ajax's scope

Try:

me = this; 

$.ajax({ 
url: "../ajax/admin/updateProfilePic.php", 
type: "POST", 
data: new FormData(me),
...

As, for me, when using ajax I always prefer to base64encode the image and pass it as a JSON to PHP but i guess that's a personal preference...

Upvotes: 1

Related Questions