Jerry
Jerry

Reputation: 420

PHP code is not uploading file

On the submit() event of the form, I'm trying to send the serialzedData to my PHP code for uploading the file using AJAX(both of which I'm new to). The PHP Code for uploading the file normally works if used directly without AJAX. I'm guessing its the AJAX portion that is not working...Any ideas?

Form(index.php)

<form id="upload-file" enctype="multipart/form-data">                                     
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload File" name="submit" id="upload_button">                                    
</form>

JQUERY/AJAX(index.js)

$(document).ready(function(){
    var request;
    $("#upload-file").submit(function(){

        if (request) {
            request.abort();
        }

        var $form = $(this);
        var $inputs = $form.find("input, select, button, textarea");
        var serializedData = $form.serialize();
        $inputs.prop("disabled", true);

        request = $.ajax({
            url: "fileupload.php",
            type: "post",
            data: serializedData
        });

        request.done(function (response, textStatus, jqXHR){        
            console.log("Hooray, it worked!");
        });    

        request.fail(function (jqXHR, textStatus, errorThrown){        
            console.error(
                "The following error occurred: "+
                textStatus, errorThrow
            );
        });

        request.always(function () {        
            $inputs.prop("disabled", false);
        });

        event.preventDefault();
    });
});

PHP(fileupload.php)

<?php       
    $fileToUpload = $_POST['serializedData'];   
    if ($_FILES["fileToUpload"]["error"] > 0){
        echo("Error");      
    }
    else{
        if (file_exists("upload/" . $_FILES["fileToUpload"]["name"])){                                  
            echo("File Exists");    
        }
        else{
            move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
            "upload/" . $_FILES["fileToUpload"]["name"]);
            echo("File Uploaded");          
        }
    }
?>

And the directory structure is

-index.php
-js(folder)
    -index.js
-fileupload.php
-upload(folder)

Upvotes: 1

Views: 87

Answers (4)

Luca Frassineti
Luca Frassineti

Reputation: 56

then try this new simply code in your index.php

    <form id="upload-file" enctype="multipart/form-data">                                     
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload File" name="submit" id="upload_button"> 
</form>

<script>
$( document ).ready(function() {

        $('#upload-file').submit(function(event) {
        event.preventDefault();

 $.ajax({
        url: "fileupload.php",
        type: "post",
        dataType: "HTML",
        data: new FormData(this),
        processData: false,
        contentType: false,
        success: function(response){ 
            if(response == 'File Uploaded'){ 
            // do something
            alert ('0k file uploaded');
        }
        },
      error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
      }

    });
       });


                    });
    </script> 

and remove

$fileToUpload = $_POST['serializedData']; 

in fileupload.php

Upvotes: 1

Jai
Jai

Reputation: 74738

As you are trying to upload files with ajax, then you should know that only with FormData() one can achieve that. So you need to change something like this:

request = $.ajax({
        url: "fileupload.php",
        type: "post",
        data: {serializedData : new FormData($('#upload-file')[0])}, //<----pass the form in the FormData()
        processData:false, // required
        contentType:false  // required
    });

With this line:

{serializedData : new FormData($('#upload-file')[0])}

You don't have to change much at server side. $_POST['serializedData']; will get the posted values.

Upvotes: 2

Luca Frassineti
Luca Frassineti

Reputation: 56

try this remove line

var serializedData = $form.serialize();

and replace data in

request = $.ajax({
        url: "fileupload.php",
        type: "post",
        data: serializedData
    });

with

data: $('#upload-file').serialize()

Upvotes: 0

Zaman
Zaman

Reputation: 551

In order to send the "file" object via ajax you need to create it as a object and send it, in that case i would prefer using plugin. Using plugin is best choice for this.You don't have to remember all options.Just replace your 'ajax' to 'ajaxForm'.

plugin url: http://jquery.malsup.com/form/#ajaxForm

Upvotes: 0

Related Questions