1

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)
4
  • What exactly happens when the upload fails? Do you get any errors? Commented Oct 20, 2015 at 8:18
  • No, no errors...it simply fails Commented Oct 20, 2015 at 8:19
  • Maybe you are not switching the $_FILES['image'] error properly. See php.net/manual/en/features.file-upload.errors.php . Commented Oct 20, 2015 at 8:23
  • i kept alert() after each and ever line, and found out that after var serializedData = $form.serialize(); the line $inputs.prop("disabled", true); below are not being executed Commented Oct 20, 2015 at 8:26

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

So i just have to change the data part...any changes in the php side?
1

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

8 Comments

you are sure that the dir where you want upload file have permission?
uptil now it did, but let me check again
i tried it on line & it works link the dir where file are uploaded have chmod on 777
my index.js is in the subfolder called js, and in index.js im giving the url: "fileupload.php", whereas my fileupload.php is in the root folder, so does dot make any difference?
you dont need index.js only index.php with code i wrote and fileupload.php in the same directory. Because you set in fileupload.php upload/ as dir where to move uploaded file you need to set chmod 777 for upload/
|
0

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

1 Comment

Plugins are fine but it's not a very good way to learn what's happening/
0

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()

1 Comment

i forget sorry in your php file also remove $fileToUpload = $_POST['serializedData'];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.