0

i'm trying to post an html form using javascript and i can't find how to pass as a parameter the file. If i post the form without using javascript everything works fine. My issue is that i don't know how to pass the file array into a javascript variable. I tried different ways but i can't find the correct one:

var fileToUpload1 = $("#fileToUpload2").val();
var fileToUpload1 = document.getElementById("fileToUpload2").files[0];
var fileToUpload1 = document.forms['imageform2']['fileToUpload2'].files[0];

I post my code in case it helps. html form and javascript are both in the same file. Upload code is in a seperate file named upload.php.

html form:

                <form id="imageform2" action="upload.php" method="post" enctype="multipart/form-data">
                    <p> Add new photo</p>
                    <p>Description :
                    <textarea id="description2" name= "description2" rows=6 cols=20 required></textarea></p>
                    Category :
                     <select id="category2" name="category">
                        <option value="0">Face</option>
                        <option value="1">Landscape</option>
                        <option value="2">Attraction</option>
                        <option value="3">Object</option>
                    </select>
                    <p>Select image:
                    <input id="fileToUpload2" type="file" name="fileToUpload2" required></p>
                    <input id="submit" type="button" value="Submit">
                    <input type="reset" value="Reset">
                </form> 

javascript:

<script>
    $(document).ready(function() {
        $("#submit").click(function() {
            var description1 = $("#description2").val();
            var category1 = $("#category2").val();
            var fileToUpload1 = $("#fileToUpload2").val();
            alert(description1 + " " + category1 + " " + fileToUpload1);
            if (description1 == '' || category1 == '') 
            {
                if (description1 == '') alert("Insertion Failed description is Blank....!!");
                else if (category1 == '') alert("Insertion Failed category is Blank....!!");
                //else if (fileToUpload1 == '') alert("Insertion Failed fileToUpload is Blank....!!");
                else alert("Insertion Failed Some Fields are Blank....!!");
            } 
            else 
            {
                // Returns successful data submission message when the entered information is stored in database.
                $.post("upload.php", 
                {
                    description: description1,
                    category: category1,
                    fileToUpload: fileToUpload1
                }, function(data) {
                alert(data);
                });
            }
        });
    });
</script>

upload:

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
session_start();

if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 2000000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        //echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
        $_SESSION['uploaded']="true";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>
1
  • What is alert(description1 + " " + category1 + " " + fileToUpload1); giving you? $("#fileToUpload2").val(); <-- gives you C:[PATH]\ExImg.jpg -- document.getElementById("fileToUpload2").files[0]; <-- gives you an object that you need to get the name field from. So just add '.name' and you'll get the input name. document.getElementById("fileToUpload2").files[0].name will give you Image.filetype without the users path. Commented Jun 17, 2016 at 2:20

1 Answer 1

1

Use FormData to submit a form with AJAX containing file inputs.

First, let's watch for the onsubmit event to fire on the form instead of the onclick event on the button.

In order to use FormData, we need to use $.ajax() instead $.post() because there are settings that need to be added for it to work. FYI $.post() is a shorthand way of using $.ajax() for POST requests. If you need to have more configuration settings, like we do now, use $.ajax().

$(document).ready(function() {
    $("#imageform2").submit(function(e) {
        e.preventDefault();
        // simplified validation logic
        if ($("#description2").val() == '') {
            alert("Insertion Failed description is Blank....!!");
        } else if ($("#category2").val() == '') {
            alert("Insertion Failed category is Blank....!!");
        } else if ($("#fileToUpload2").val() == '') {
            alert("Insertion Failed fileToUpload is Blank....!!");
        } else {
            // send request 
            $.ajax({
                type: this.method,
                url: this.action,
                data: new FormData(this), // important
                processData: false, // important
                contentType: false, // important
                success: function (data) {
                    alert(data);
                }
            });
        }
    });
});

Next on the server-side, let's improve your file checking a little. You should always check the existence of superglobal variable before manipulating it.

Let's wrap the validation logic inside a try and catch. There's no point in continuing the validation if there is an error at a certain point. We'll quit the validation if an error occurs by throwing an exception with the appropriate message.

// just in case, let's turn on the errors
error_reporting(E_ALL);
ini_set('display_errors', 1);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $file = isset($_FILES['fileToUpload2']['tmp_name']) ? $_FILES['fileToUpload2'] : null;
    // start validation
    try {
        // check if file was NOT provided
        if (!$file ||
            !file_exists($file['tmp_name']) || 
            !is_uploaded_file($file['tmp_name']) || 
            $file['error'] !== UPLOAD_ERR_OK) {
            throw new Exception('No file was given.');
        }
        // check if file is NOT an image
        $size = getimagesize($file['tmp_name']);
        if ($size === false) {
            throw new Exception('File is not an image.');
        }
        // check if file already exists
        $target_dir = 'uploads/';
        $target_file = $target_dir . basename($file['name']);
        if (file_exists($target_file)) {
            throw new Exception('File already exists.');
        }
        // check file size is too large
        if ($file['size'] > 2000000) {
            throw new Exception('File is too large.');
        }
        // check file extension is NOT accepted
        $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($extension, ['jpg', 'png', 'gif'])) {
            throw new Exception('Only JPEG, PNG & GIF files are allowed.');
        }
        // if it passes all checks, try uploading file 
        if (!move_uploaded_file($file['tmp_name'], $target_file)) {
            throw new Exception('There was an error uploading your file.');
        }
        // if we reach this point, then everything worked out!
        echo 'The file ' . basename($file['name']) . ' has been uploaded.';
    } catch (Exception $e) {
        echo $e->getMessage();
    }
}

Of course, the validation could be improved a lot more -- but this is just a quick example.

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

3 Comments

It works like a charm thanks you. A small issue with the validation (it works correct for all my other pictures) but it returns 'No file was given' for a picture named Hearthstone Screenshot 05-15-16 20.48.12
That means one of the 4 conditions in the first validation is failing. I would start by looking what value $file['error'] contains. It will be a number between 0 and 8.
Thnx for the tip, The problem was that the uploaded file exceeds the upload_max_filesize directive in php.ini but i won't change it i guess. Thnx again.

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.