Uploaded file is not passing through JavaScript to PHP - javascript

Here i'm trying to pass uploaded file and a text input from HTML->JavaScript->PHP. But it is only passing the text input and failed to pass the file , i'm not getting that file in PHP. As a result it is showing undefined index error for "$u_file" in the PHP file. I don't understand where is the problem.
Here goes the HTML file
<body>
<div class="container">
<form class="form-horizontal" action="">
<h2><b>Post your job</b></h2><br><br>
<div class="form-group">
<label class="control-label col-sm-2">Job Position:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="jName" placeholder="Enter job name" name="jName" required>
<p id="jErr"></p>
</div>
</div>
<div class="form-group">
<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
<label class="control-label col-sm-2">Add some detailed description:</label>
<div class="col-sm-10">
<input id="u_file" value="u_file" type="file" name="u_file" size="5000000" multiple onchange="showname()"><br><br>
</div>
</form>
</div>
<div class="container-fluid text-center">
<br><button name="submitJob" id="submitJob" type="submit" class="btn btn-default" onclick="job_checker()">Submit</button>
<p id="submitJobErr"></p></div>
</form>
</div>
</body>
Here goes the JavaScript file
signFlagj = 0;
function job_checker() {
checkJobName();
databasejobEntry();
}
function checkJobName() {
var jobnameET = document.getElementById("jName");
var jobnameError = document.getElementById("jErr");
jobname = jobnameET.value;
console.log(jobname);
var regex = /^[a-zA-Z ]*$/;
if(!regex.test(jobname)){
jobnameError.innerHTML = "Only letters and white space allowed";
signFlagj = 1;
}
else {
jobnameError.innerHTML = "";
}
}
function showname() {
jobFilename = document.getElementById('u_file');
console.log('Selected file: ' + jobFilename.files.item(0).name);
console.log('Selected file: ' + jobFilename.files.item(0).size);
console.log('Selected file: ' + jobFilename.files.item(0).type);
}
function databasejobEntry() {
if(signFlagj==1) {
console.log("fill up correctly!");
alert("Sign up correctly!");
}
else
{
console.log('Selected file: ' + jobFilename.files.item(0).name);
console.log(jobname);
var submitError = document.getElementById("submitJobErr");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
console.log(this.readyState);
if(this.readyState == 4 && this.status == 200)
{
console.log(this.status);
var response = xhttp.responseText;
console.log(response);
submitError.innerHTML=response;
alert(response);
if(String(response.trim()) === "Success") {
alert("Successfully submitted :)");
window.location.href = "uploadJob.html";
}
}
}
xhttp.open("GET", "uploadJob.php?jobname="+jobname+"&jobFilename="+jobFilename,true);
xhttp.send();
}
}
Here goes the PHP file
require_once('DBconnection.php');
ini_set('display_errors', 1);
ini_set('log_errors', 1);
$val="";
$jobName = $_GET["jobname"];
echo "$jobName";
$u_file = $_FILES['jobFilename'];
$file_type = $_FILES['jobFilename']['type'];
$file_size = $_FILES['jobFilename']['size'];
$file_name = $_FILES['jobFilename']['name'];
print_r($u_file);
//echo "****************";
$currentdir = getcwd();
$targetfolder = $currentdir . "/testupload/";
// echo "****************";
print_r($targetfolder);
$targetfile = $targetfolder . basename( $_FILES['jobFilename']['name']) ;
//print_r($targetfolder);
print_r($currentdir);
//echo "****************";
$uploadOk=1;
print_r($file_type);
if ($file_type != "application/pdf" && $file_type != "image/png" && $file_type != "image/jpeg" && $file_type != "image/jpg") {
echo "Sorry, only JPG, JPEG, PNG & PDF files are allowed.";
$uploadOk = 0;
}
if (file_exists($targetfile)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
if($uploadOk==0){
echo "Problem in uploading file";
}
else {
if(move_uploaded_file($_FILES['jobFilename']['tmp_name'], $targetfile)) {
$fileUpQueryjob = "INSERT INTO jobs (job_name,job_filename) VALUES ('$jobName','$file_name')";
$upJob = $db->query($fileUpQueryjob);
if ($upJob == true) {
$val = "Success";
echo "The file ". basename( $_FILES['jobFilename']['name']). " is uploaded";
}
else
echo "Error: " . $fileUpQueryjob . "<br>" . mysqli_error($db);
}
}
//echo "$val";
$db->close();

Use POST request instead of GET request. If necessary warp it in new FormData and post it.

Related

How to delete uploaded files PHP ajax

I want to delete a file uploaded after I click on a submit button or after the page is reloaded.
I did this drop zone to drag and drop file:
<div id="drop_file_zone" class="centered" ondrop="upload_file(event)" ondragover="return false">
<div id="drag_upload_file" class="centered">
<p><strong>Drop file here</strong></p>
<p>or</p>
<p>
<input class="btn btn-danger btn-sm" id="selectfile3" type="button" value="Select File" onclick="file_explorer();" />
</p>
<input type="file" id="selectfile"/>
<div class="img-content" style="text-align: center;"></div>
</div>
</div>
On my drag_drop.js file:
var fileobj;
function upload_file(e) {
e.preventDefault();
fileobj = e.dataTransfer.files[0];
ajax_file_upload(fileobj);
}
function file_explorer() {
document.getElementById('selectfile').click();
document.getElementById('selectfile').onchange = function () {
fileobj = document.getElementById('selectfile').files[0];
ajax_file_upload(fileobj);
};
}
function ajax_file_upload(file_obj) {
if (file_obj != undefined) {
var form_data = new FormData();
form_data.append('file', file_obj);
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/app/helpers/upload_file.php", true);
xhttp.onload = function (event) {
oOutput = document.querySelector('.img-content');
if (xhttp.status == 200) {
if(this.responseText == 'false'){
console.log('no type');
} else {
oOutput.innerHTML = "<img src='/app/assets/img/pdf.png' alt='The Image' width='32' height='32'/><p>" + this.responseText + "</p>";
}
} else {
oOutput.innerHTML = "Error " + xhttp.status + " occurred when trying to upload your file.";
}
}
xhttp.send(form_data);
}
}
And on the upload_file.php this function:
<?php
$arr_file_types = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
if (!(in_array($_FILES['file']['type'], $arr_file_types))) {
echo "false";
return;
}
if (!file_exists('uploads')) {
mkdir('uploads', 0777);
}
$filename = $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $filename);
echo $filename;
die;
but I don't really know how to delete these temps documents when I press the button (this button will save the document on a database) or when the page is reloaded.

How to upload image with php, js and local storage?

I have managed to upload an image with PHP and HTML before but now I have to do this with js and ajax. And I have been advised to also use local storage to store it on the server before insert it into the database. I have started and had a little go. I have added the php, html and js code below. Thanks in advance for any help.
$username = $_POST['username'];
$message = "Hello!";
if($_POST['submit'] == "Upload Image"){
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
$message = "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
$message = "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
$message = "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
$message = "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
$message = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$message = "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)) {
$uploadedfilename= basename( $_FILES["fileToUpload"]["name"]);
$query = "UPDATE users SET imagename='$uploadedfilename' WHERE username='$username'";
mysqli_query($db_server, $query) or die("Insert failed. ". mysqli_error($db_server));
$message = "<strong>Image $uploadedimage upload successful!</strong>";
} else {
$message = "Sorry, there was an error uploading your file.";
}
}
}
$currentimagename = "profilepic.png";
$query="SELECT imagename FROM users WHERE username='$username'";
$result = mysqli_query($db_server, $query) or die("image load failed. ". mysqli_error($db_server));
if($row = mysqli_fetch_array($result)){
if($row['imagename']<>""){
$currentimagename = $row['imagename'];
}
}
mysqli_free_result($result);
echo $message;
HTML
<h2 id="username" class="usernamemessage"></h2>
<img src="profilepic.png" alt="profilepic" style="width:200px;height:200px;">
<div class="buttons">
<button class="button">Upload Image</button>
<form id="imageForm" method='POST' class="imageform">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
JS
// When upload image button is clicked
$(document).ready(function() {
var imageform = $("#imageForm");
$("#imageForm").on('submit', function(event) {
event.preventDefault();
var imageValue = document.getElementById("fileToUpload").value;
var imageform = new FormData(this);
//Get Storage
var username = window.localStorage.getItem("username");
imageform.append('username', username);
// Call AJAX
$.ajax({
type: 'POST',
url: 'image.php',
data: imageform,
processData: false,
contentType: false,
success: function(response) {
if(response == "Success"){
document.getElementById("image").innerHTML = "Image Change Successful";
//Local Storage
window.localStorage.setItem("fileToUpload", imageValue);
} else {
console.log(response);
document.getElementById("error").innerHTML = response;
}
}
});
return false;
});
});
I have seen in your form tag you didn't added below part
enctype='multipart/form-data'
Please add this in form tag your code will work## Heading ##

Uploading an image, then displaying it as a Canvas on the next page

I'm attempting to create a page that allows the manipulation of an uploaded image by using Canvas. So far, I've had no luck forwarding the image from one page (the submit form) to the other, which contains the canvas. I'm using PHP, Javascript and HTML in order to try and send the image from the submit form to the canvas space.
This is the submitting form.
<form action="designer.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="name">Name</label><?php
include('/tbp3/php/autoload.php');
header('Content-Type: application/json');
$fullpath = $_SESSION['activeImg'];
$size = getimagesize($fullpath);
echo json_encode(array('x' => $size[0], 'y' => $size[1], 'path' => $fullpath, 'lastPosJson' => isset($_SESSION['lastPos']) ? $_SESSION['lastPos'] : '[]'));
$db->close();
?>
<p>2-32 characters</p>
<input class="form-control" type="text" name="name" id="name">
</div>
<div class="form-group">
<p>JPEG/PNG under 2MB only</p>
<label class="btn btn-default" for="image">Choose Image</label>
<span></span>
<input class="inputfile" type="file" name="image" id="canvas">
</div>
<div class="form-group">
</div>
<input class="btn btn-primary" type="submit" value="Next">
</form>
This is the JavaScript I use in order to confirm the uploaded file is a PNG or JPEG. Note: I'm a novice at Javascript.
var validTypes = ['png', 'jpg', 'jpeg'];
$(document).ready(function(){
$('form').submit(function(e){//on submission..
var file = $('#upload').val();
var isValid = true;
var error = '';
if(file == ''){
error = 'Select a file before proceeding!';
$('#upload').addClass('validation-error');
isValid = false;
} else{
var type = /[^\.]*$/.exec(file).toString().toLowerCase();
if($.inArray(type, validTypes) == -1){
error = type + ' is an invalid type for the image! Please use ' + validTypes.join(', ').replace(/,([^,]*)$/, " or$1.");
$('#upload').addClass('validation-error');
isValid = false;
}
}
});
And this is on the page 'Designer.php'. I want the image to be displayed on the tag.
<div class="row canvasarea">
<div class="col-xs-6 header">Canvas</div>
<div class="col-xs-6 header">Live View</div>
</div>
<div class="row canvasarea">
<div class="col-xs-6 help">TEXT</div>
<div class="col-xs-6 help">TEXT</div>
</div>
<div class="row canvasarea">
<div class="col-xs-6">
<canvas id='canvas'></canvas></div>
<div class="col-xs-6">
<img id='liveupdate'/><br></div>
The PHP script I'm using to save it to the server.
<?php
require('/var/www/html/tpb3/php/autoload.php');
session_start();
$megabyte = 8000000;
$db = "new Database();";
function getImage(){
$id = $this->getTemplateId();
$type = $this->getFiletype();
return "img/template/$id.$type";
}
function addTemplate($templateId, $filetype){
if(!$this->isLoggedIn()){
echo "You're not logged in";
return '';
}
function isValidFileType($type){
$type = strtolower($type);
$types = array('jpeg', 'jpg', 'png');
for($i = 0; $i < count($types); $i++){
if($type === $types[$i]){
return true;
}
}
return false;
}
function isPng($filepath){
$img = #imagecreatefrompng($filepath);
if($img === false){
return false;
} else{
echo "Not a PNG";
imagedestroy($img);
return true;
}
}
function isJpeg($filepath){
$img = #imagecreatefromjpeg($filepath);
if($img === false){
return false;
} else{
echo "Not a JPEG";
imagedestroy($img);
return true;
}
}
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
if(!empty($_POST['selectedType']) ){
$selectedType = $_POST['type'];
}
if(isset($_POST["type"]))
$selectedType = $_POST["type"];
$dir = $selectedType == 'template' ? 'temp' : 'sourceimages';
if(isset($_POST["submit"])) {
$valid = true;
$id = uniqid();
$type = strtolower(pathinfo(basename($_FILES['upload']['name']), PATHINFO_EXTENSION));
$uploadFileDest = 'img/template/$id.$type';
$size = #getimagesize($_FILES["upload"]["tmp_name"]);
$error = '';
if($size === false) {
$error .= "Main image not a valid image, ";
$valid = false;
} elseif($size[0] > 2000 || $size[1] > 2000){
$error .= "Image larger than 2000px, ";
$valid = false;
} elseif(!isValidFileType($type)){
$error .= "Not a valid filetype, ";
$valid = false;
} elseif(!isJpeg($_FILES["upload"]["tmp_name"]) && !isPng($_FILES["upload"]["tmp_name"])){
$error .= "Image is not a valid jpg/png. ";
$valid = false;
} elseif ($_FILES["upload"]["size"] > 2 * $megabyte) {
$error .= "File larger than 2 MB, ";
$valid = false;
}
}
if($valid = true){
if($selectedType == 'template'){
$_SESSION['activeId'] = $id;
$_SESSION['activeImg'] = $uploadFileDest;
move_uploaded_file($_FILES["upload"]["tmp_name"], $uploadFileDest);
header('Location: designer.php');
} else{
$response = $db->addSourceImage($id, $type);
if($response == ';success'){
move_uploaded_file($_FILES["upload"]["tmp_name"], $uploadFileDest);
$_SESSION['lastId'] = $id;
header('Location: success.php');
} else{
header('Location: submit.php?e='.urlencode("Database failed with message: $response"));
}
}
} else{
header('Location: submit.php?e='.urlencode(substr($error, 0, strlen($error) - 2)));
}
}
?>
Any push into the right direction would be appreciated.

Cannot set property 'innerHTML' of null in AJAX Call

I have looked through about 30 different articles about this error on this site and have not found the answer I need.
I am getting the dreaded Cannot set property 'innerHTML' of null message when I click a cell in my div table i created. I have checked the order of the page load to make sure that the JS is below the html tags.
I think is may have to do with using a variable name in the getElementById syntax.
Here is my code I am using (sorry for the noobish style of coding):
<HTML>
</HEAD>
<BODY>
<table border=1>
<tr><td colspan="11"><center><h2>Away Team</h2></center></td></tr>
<?php
$ROWMAX=3;
$COLMAX=3;
//Rows = j
for($j=-1;$j<=$ROWMAX-1;$j++){
echo "<tr>";
//Columns = i
for($i=-1;$i<=$COLMAX-1;$i++) {
if($i == -1 && $j == -1){
echo "<th class='header-cols'></th>"; }
elseif($i == -1 && $j >= 0){
echo "<th class='header-rows'><h1>$j</h1></th>";
}
elseif($j<0){
echo "<th class='header-cols'><h1>$i</h1></th>";
}
else {
$sql = "SELECT name FROM picks WHERE col=$i AND row=$j LIMIT 1";
$data = $conn->query($sql);
while($rows=$data->fetch_assoc()){
$currName = $rows['name'];
$cellStatus = $rows['status'];
}
echo "<td class='grid-cells'>
<div id='cell-$j-$i' class='$cellStatus' onclick='setCoords($j,$i);'>
<div class='grid-num'>" . (($i+1)+($j*$COLMAX)) . "</div>
<div class='grid-name-$j-$i'>$currName</div>
</div>
</td>";
$currName="";
}
}
echo "</tr>";
} ?>
</table>
<form method="post" onSubmit="setSquare()">
<div>
<h3>Submit Your Picks:</h3>
<label for="name" class="ui-hidden-accessible">Name:</label>
<input type="text" name="name" id="nameid" placeholder="Name"><br />
<label for="email" class="ui-hidden-accessible">Email:</label>
<input type="text" name="email" id="emailid" placeholder="Email"><br />
<input type="submit" data-inline="true" id='submitbtn' class='btndisabled' value="Make Picks" disabled>
<div id='row-div'></div>
<div id='col-div'></div>
</div>
</form><SCRIPT>
function setCoords(row_coords, col_coords){
var txt_name = document.getElementById("nameid").value;
var txt_email = document.getElementById("emailid").value;
if (txt_name != "" && txt_email != ""){
document.getElementById("cell-"+row_coords+"-"+col_coords).className = "picked";
setSquare(row_coords, col_coords);
document.getElementById("submitbtn").className = "btnenabled";
}
else
{ alert("Please fill in your name and email before making a pick"); }
}
function setSquare(row,col)
{
//get id vales from form
var name_id = document.getElementById("nameid").value;
var email_id = document.getElementById("emailid").value;
var row_id = row;
var col_id = col;
var gridname = "grid-name-"+row+"-"+col;
//run the ajax code here
if(name_id != ""){
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
document.getElementById(gridname).innerHTML = this.responseText;
//alert("grid-name-"+row_id+"-"+col_id);
//alert(this.responseText);
}
};
xmlhttp.open("POST","save-square.php?name="+name_id+"&email="+email_id+"&row="+row_id+"&col="+col_id,true);
xmlhttp.send();
}
}
</SCRIPT>
</BODY>
</HTML>
Spot the differences:
<div id='cell-$j-$i' class='$cellStatus' onclick='setCoords($j,$i);'>
^^
<div class='grid-name-$j-$i'>$currName</div>';
^^^^^
var gridname = "grid-name-"+row+"-"+col;
document.getElementById(gridname).innerHTML = this.responseText;
^^
class is NOT an id, and will NOT be found by a getElementById() - note the ID part of that function name.
Change the Html code below
<div class='grid-name-$j-$i'>$currName</div>
to
<div id='grid-name-$j-$i'>$currName</div>
Because you are reference them by ID in your code
document.getElementById(gridname).innerHTML = this.responseText;

File not Uploading in File Reader

I am using File Reader for selecting and uploading images.
My images are selected previewing but not uploaded when i hit submit button.
In upload.php the output of $_FILES is an empty array.
Where is problem?
html
<form action="upload.php" method="post" enctype="multipart/form-data">
<div id="wrapper" style="margin-top: 20px;">
<input id="fileUpload" multiple="multiple" type="file"/>
<input type="submit" value="Upload Image" name="upload">
<div id="image-holder">
</div>
</div>
</form>
Javascript
<script>
$(document).ready(function() {
$("#fileUpload").on('change', function() {
//Get count of selected files
var countFiles = $(this)[0].files.length;
var imgPath = $(this)[0].value;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
var image_holder = $("#image-holder");
image_holder.empty();
if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
if (typeof(FileReader) != "undefined") {
//loop for each file selected for uploaded.
for (var i = 0; i < countFiles; i++)
{
var reader = new FileReader();
reader.onload = function(e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(image_holder);
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[i]);
}
} else {
alert("This browser does not support FileReader.");
}
} else {
alert("Pls select only images");
}
});
});
</script>
upload.php
<?php
require_once './include/db_connection.php';
if(isset($_POST['upload']))
{
print_r($_FILES);
die();
if(!empty($_FILES)){
$targetDir = "upload/";
$fileName = $_FILES['file']['name'];
$targetFile = $targetDir.$fileName;
if(move_uploaded_file($_FILES['file']['tmp_name'],$targetFile))
{
//insert file information into db table
$sql = mysqli_query($link,"INSERT INTO files (file_name, uploaded) VALUES('".$fileName."','".date("Y-m-d H:i:s")."')");
echo 'file inserted';
}
else
{
echo 'Query not working';
}
}
else
{
echo 'No file selected';
}
}
Your file input doesn't have a name.
The name of a form control is used to determine what key it will have in the submitted data. Controls without them will not be successful (i.e. will not appear in the submitted data at all).

Categories