Upload with java script

0

I have the following code for image upload however it only works if js is on the same page of the form and does not work coming from the external file js, I would like to use external because I use other functions, could someone explain me why does not the external js work or give some hint? grateful!

HTML

<head>

<title>Image Upload Form</title>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/teste.js"></script>

</head>

<body>
<form method="post" id="fileinfo" name="fileinfo" ">
<label>Select a file:</label><br>
<input type="file" name="file" required onchange='return submitForm();'/>
 <input type="submit" value="Upload" />
</form>
<div id="output"></div>

external js

function submitForm() {
        console.log("submit event");
        var fd = new FormData(document.getElementById("fileinfo"));
        fd.append("label", "WEBUPLOAD");
        $.ajax({
          url: "../teste.php",
          type: "POST",
          data: fd,
          processData: false,  
          contentType: false   
        }).done(function( data ) {
            console.log("PHP Output:");
            console.log( data );
        });
        return false;
    }

Php

if ($_POST["label"]) {
$label = $_POST["label"];
}
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 200000)
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
    $filename = $label.$_FILES["file"]["name"];
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

    if (file_exists("upload/" . $filename)) {
        echo $filename . " already exists. ";
    } else {
        move_uploaded_file($_FILES["file"]["tmp_name"],
        "upload/" . $filename);
        echo "Stored in: " . "upload/" . $filename;
    }
}
} else {
echo "Invalid file";
}
?>
    
asked by anonymous 16.08.2016 / 03:34

1 answer

1

It works, both external and embedded in code. You just need to set the correct path. I think you've changed the code path and so it does not work. If test.php is in root, along with HTML, change:

url: "../teste.php"

To:

url: "teste.php",

Or use the absolute path that has no error.

    
16.08.2016 / 04:29