Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialEdward campbell malan van wyk
6,403 PointsPHP file upload
I have a basic form to upload files to my web server.
<form enctype="multipart/form-data" action="" method="post"> Browse for File to upload: <br> <input name="UploadFileField" type="file" id="UploadFileField"><br> <button onClick="getFilePath();" type="button" id="UploadButton" name="upload_button" value="Upload the File" style="width:100px; height:auto">Upload File</button> </form>
The following function posts the filepath to a php script.
function getFilePath()
{
var filepath = $('#filePath').text();
$.post("assets/php/uploadFile.php", {filepath:filepath}, function(result){alert(result)});
}
In the php file i check if a file is selected to be uploaded then i create the necessary variables needed to upload a file.
if(isset($_FILES['UploadFileField'])) { $UploadName = $_FILES['UploadFileField']['name']; $UploadTmp = $_FILES['UploadFileField']['tmp_name']; $UploadType = $_FIles['UploadFileField']['type'];
Finaly my question, the php script is a separate file. thus it does not see the 'UploadFileField' name that is given to the input tag in a different script.
How can I let the php script with my upload php see this input tags name? or am I being stupid about this....
:/
TIA
1 Answer
Konrad Traczyk
22,287 PointsHi Edward,
TBH i dont understand why you're using ajax for this?
If you'd like to pass file to other script file you place the filepath in forms tag action attribute. Like this:
<form action="assets/php/uploadFile.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
If this doesnt convince you i suggest you to ask google about "file upload through AJAX".
PS. In jQuery we don't use .text() to get value from input you should use .val() function