I am trying to make a form for editing a product but if I upload a image the image can not be found by my PHP code it throws this error:
Notice: Undefined index: image in C:\xampp\htdocs\pages\shopmanager\admin\producteditor.php on line 10
Notice: Undefined index: image in
C:\xampp\htdocs\pages\shopmanager\admin\producteditor.php on line 11
Upload failed
This is my Code:
$db = new Database;
$product = mysqli_fetch_array($db->db_query("SELECT * FROM product WHERE ID = '" . $_GET['id'] . "'"));
$image = mysqli_fetch_array($db->db_query("SELECT name,src FROM images WHERE id =".$product['image-id']));
$category = $db->db_query("SELECT * FROM category");
$productcat = mysqli_fetch_array($db->db_query("SELECT `cat-id` FROM `category-product` WHERE `prod-id` = ".$product['ID']));
if(isset($_POST['submit'])){
$uploaddir = '/../../../src/images/';
$uploadfile = $uploaddir . basename($_FILES['image']['name']);
if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
}
?>
<!--page content-->
<div class="col-9">
<div style="background-color:#c6c8ca !important; color:black" class="jumbotron">
<div class="container">
<form class="well form-horizontal" action="producteditor.php?id=<?= $_GET['id'] ?>" method="post"
id="producteditor_form">
<fieldset>
<!-- Upload image input-->
<input id="upload" name="image" type="file" onchange="readURL(this);"
class="form-control border-0" accept="image/*" hidden>
<div class="input-group-append">
<label for="upload" class="btn btn-light m-0 rounded-pill px-4"> <i
class="fa fa-cloud-upload mr-2 text-muted"></i><small
class="text-uppercase font-weight-bold text-muted"> Kies
bestand</small></label>
</div>
<!-- Uploaded image area-->
<div class="image-area mt-4"><img id="imageResult"
src="../../../<?=$image['src']?>" alt="<?=$image['name']?>"
class="img-fluid rounded shadow-sm mx-auto d-block">
</div>
</div>
</div>
</div>
<!-- Button -->
<div class="form-group">
<div class="text-center">
<button class="btn btn-lg btn-success form-spacing-top"
name="submit">Opslaan</button>
</div>
</div>
</fieldset>
</form>
</div>
</div><!-- /.container -->
</div>
</div>
<div class="col"></div>
</div>
</div>
<script>
/* ==========================================
SHOW UPLOADED IMAGE
* ========================================== */
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#imageResult')
.attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
$(function() {
$('#upload').on('change', function() {
readURL(input);
fetch(url, {
method: 'POST',
body: readURL(input)
});
});
});
/* ==========================================
SHOW UPLOADED IMAGE NAME
* ========================================== */
var input = document.getElementById('upload');
var infoArea = document.getElementById('upload-label');
input.addEventListener('change', showFileName);
function showFileName(event) {
var input = event.srcElement;
var fileName = input.files[0].name;
infoArea.textContent = 'File name: ' + fileName;
}
</script>
Your <form> needs to have the enctype='multipart/form-data' attribute.
See: What does enctype='multipart/form-data' mean?
Related
I am working on a cms with Codeigniter. I am trying to upload file from system. I am receiving the file but the do_upload method is not working. There are similar questions on this topic, but none of the answers of them worked.
Here is my method:
public function fileupdate($productId=False){
$formData = $this->input->post();
if (isset($formData['activityNewFile'])) {
foreach ($formData['activityNewFile'] as $key => $value) {
$rndNumber = rand(1,500);
$fileLastName = sef_url($formData['activitynewfilename'.$value]);
// Set preference
$config['upload_path'] = '../assets/';
$config['allowed_types'] = 'pdf|doc|docx|xls|xlsx';
$config['max_size'] = '80960'; // max_size in kb
$config['file_name'] = $fileLastName;
$upFile = 'activitynewfile'.$value;
// Load upload library
$this->load->library('upload',$config);
// File upload
if($this->upload->do_upload($upFile)){
// Get data about the file
$uploadData = $this->upload->data();
$filename = $uploadData['file_name'];
$daData = array(
'productId' => $productId,
'productFileName' => $formData['activitynewfilename'.$value],
'productFile' => $filename
);
$productfileInsert = $this->db->insert('productfile',$daData);
}
}
}
$this->success("İşlem tamamlandı.");
}
HTML part:
<form class="m-form m-form--fit m-form--label-align-right" role="form" method="POST" id="product_file_edit" action="<?=base_url('product/product/fileupdate/'.$productInfo->productId);?>" enctype="multipart/form-data" onsubmit="return false; form_gonder('product_file_edit')" >
<div class="modal-body">
<div class="form-group m-form__group row">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="col-md-12" style="margin-bottom: 10px;padding: 0;" id="file_row">
<button onclick="addFileRow('file_add')" class="btn btn-primary btn-sm">
<i class="zmdi zmdi-plus"></i> Add
</button>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button onclick="form_gonder('product_file_edit')" class="btn btn-green btn-sm">
Save
</button>
</div>
</form>
Javascript part:
function addFileRow(tur){
if(tur=="file_add"){
emreFile = Math.floor(Math.random() * 10);
myhtmlFile = '<div class="col-md-12 row" id="filenew'+emreFile+'" style="padding: 0;margin: 0;margin-bottom: 10px;"><div class="input-group"><input type="hidden" name="activityNewFile[]" value="'+emreFile+'"><img src="../assets/file/pdfword.png" style="width: 38px;float: left;height: 38px;"><input type="text" name="activitynewfilename'+emreFile+'" class="form-control" placeholder="Dosya Adı" style="width: 45%;float: left;height: 39px;"><input type="file" name="activitynewfile'+emreFile+'" accept=".xls,.xlsx,.doc,.docx,.pdf" class="form-control" placeholder="Dosya Adı" style="width: 46%;opacity: 1;float: right;position: relative;"><span class="input-group-btn"><button class="btn btn-red btn-fab btn-fab-sm animate-fab" onclick="deleteNewFileRow('+emreFile+')" type="button"><i class="zmdi zmdi-delete"></i></button></span></div></div>';
var icerikFile = myhtmlFile;
jQuery("#file_row").prepend(icerikFile);
}
}
I would be very grateful if you could find out what the problem is.
Your problem is actually the file is not loading properly. There is no error in your codes. Make sure file_uploads is turned on on your server. Make sure the upload_max_filesize value is not smaller than your file size.
This question already has answers here:
jQuery Ajax File Upload
(27 answers)
Closed 3 years ago.
I am having problem with uploading file with JavaScript Popup. This is my first experience to upload file with such JavaScript popup. I don't know how to pass the input[type:file] to the ajax function and then send to the php file for uploading.
This is the button which calls the popup:
<a class="btn btn-primary btn-sm" data-toggle="modal" data-target="#uploadDocument">Upload Document</a>
<div class="modal fade" id="uploadDocument" role="dialog">
<div class="modal-dialog" style="top: 20%;">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header" style="background-color: #367FA9">
<h4 class="modal-title" id="myModalLabel" style="color:white">Upload Document</h4>
</div>
<!-- Modal Body -->
<div class="modal-body" style="padding-top: 20px; padding-right: 40px; padding-left: 40px;">
<!-- <img src="police/images/new.jpg" width="120px" height="100px"> -->
<p id="uploadMD"></p>
<form role="form" id="uploadForm" >
<div class="form-group">
<input type="hidden" name="" id="rowid" value="<?php echo $id; ?>">
</div>
<div class="form-group">
<label>Document Name</label>
<input type="text" name="" id="documentName" class="form-control">
</div>
<div class="form-group">
<label>Document</label>
<input type="file" class="form-control" placeholder="Please Select File" id="documentFile">
</div>
<div class="form-group text-center">
<button type="button" class="btn btn-primary submitBtn block" style="background-color: #367FA9" onclick="uploadDocument()" style="width: 100%;">Upload Document</button>
</div>
</form>
</div>
<!-- Modal Footer -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The javascript code is as follows:
<script>
function uploadDocument(){
var rowid = $('#rowid').val();
var documentName = $('#documentName').val();
var documentFile = $('#documentFile').val();
if(documentName.trim() == '' ){
alert('Please write file name');
$('#documentName').focus();
return false;
}else if(documentFile.trim() == '' ){
alert('Please Select File');
$('#documentFile').focus();
return false;
}else {
$.ajax({
method:'POST',
url:'upload.php',
enctype: 'multipart/form-data',
data:'&rowid='+rowid+'&documentName='+documentName+'&documentFile='+documentFile,
success: function(result){
$('#uploadForm').trigger('reset');
if(result == '1'){
$('#uploadMD').html('<span style="color:green;">Your File is uploaded. Thank you</span>');
setTimeout(function(){ window.location.reload() }, 5000);
}
else{
$('#uploadMD').html('<span style="color:red;">Uploading Problem</span>').fadeIn().delay(5000).fadeOut();
}
}
});
}
}
</script>
and the upload.php file is here:
<?php
$rowid = $_POST['rowid'];
$documentName = $_POST['documentName'];
$file_name = $_FILES['documentFile']['name'];
$file_move = move_uploaded_file($file_tmp,"../uploads/ps/".$file_name);
include "../include/configs.php";
if ($file_move) {
$q2 = "UPDATE requests SET support_doc='$file_name' WHERE slug='$id'";
$query = mysqli_query($con, $q2);
if ($query) {
echo $success = 1;
}
}
?>
Thanks in advance.
Try formdata to pass in php file ajax call
var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
// ... Other options like success and etc
});
Thanks
I have a form with some fields and after submit finish i want to reset whole form but only reset input text areas not input type file.
I check every similar questions and solutions but none of them work for me.Some solutions refresh page which i don't want that.
<form class=" dropzone px-5" id="mydropzone">
<h2 class="text-center">Lets create your menu</h2>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputCalories">Calorie</label>
<input type="text" class="form-control" id="inputCalories" required>
</div>
<div class="form-group col-md-6">
<label for="cc">Calorie Calculator</label>
<button id="cc" class="btn btn-primary btn-lg"><i class="fas fa-calculator mr-2"></i>Click Me</button>
</div>
</div>
<div class="form-row">
<div class="form-group ml-2 col-sm-6">
<label>Menu Item Image</label>
<div id="msg"></div>
<div class="progress" id="uploader">
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100" style="width: 10%"></div>
</div>
<input type="file" name="img[]" class="file" accept="image/*" id="fileButton">
<div class="input-group my-3">
<input type="text" class="form-control" disabled placeholder="Upload File" id="file" required>
<div class="input-group-append">
<button type="button" class="browse btn btn-primary"><i class="fas fa-folder-open mr-2"></i>Browse...</button>
</div>
</div>
<div class="ml-2 col-sm-6">
<img src=" " id="preview" class="img-thumbnail">
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-block mb-3">Submit Menu</button>
<!-- -------------------------------------------------------------------------- -->
</div>
</form>
And my create menu which clear all fields after form submit.
// create menu
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
fileButton.addEventListener('change', function(e) {
var file = e.target.files[0];
var storageRef = firebase.storage().ref('foodImg/' + file.name);
var task = storageRef.put(file);
task.on('state_changed', function progress(snapshot) {
var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
uploader.value = percentage;
}, function(error) {
console.error(error);
}, function() {
task.snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log('File available at', downloadURL);
const createMenuForm = document.querySelector('#mydropzone');
createMenuForm.addEventListener('submit', (e) => {
e.preventDefault();
db.collection('restaurants').add({
foodLine: {
menuTitle: createMenuForm.menuTitle.value
},
food: {
foodName: createMenuForm.foodName.value,
imageURL: downloadURL,
inputCalories: createMenuForm.inputCalories.value,
menuItemDescription: createMenuForm.menuItemDescription.value,
menuItemInfo: createMenuForm.menuItemInfo.value
}
}).then(() => {
//reset form
createMenuForm.reset();
fileButton.value = "";
var preview = document.getElementById('preview');
preview.value = "";
}).catch(err => {
console.log(err.message);
});
});
});
});
});
Can you try these things also
document.getElementById("myForm").reset();
$("#myForm").trigger("reset");
I think you try to access createMenuForm outside the scope where const createMenuForm was declared.
Try to declare it above the event listener:
// create menu
const createMenuForm = document.querySelector('#mydropzone');
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
// ...
or directly with
document.querySelector('#mydropzone').reset();
i debug and find that preview need to be clean
document.getElementById("preview").src = "#";
I am trying to upload image with some required field like name, description. When i am inserting data without the image field it works, but when trying to upload the image file as well its not inserting data to database. Could anyone tell me what may be wrong with my code?
Controller
public function store(Request $request)
{
$this->validate($request, [
'cat_name' => 'required|max:255',
'description' => 'required|min:6',
'cat_pic' => 'required|image|mimes:jpg,jpeg,png',
]);
$fileName = null;
if ($request()->hasFile('cat_pic')) {
$file = $request()->file('cat_pic');
$fileName = time().'.'.$file->getClientOriginalExtension();
$destinationPath = public_path('/uploads/products/cats/');
$file->move($destinationPath, $fileName);
$this->save();
}
Catagories::create([
'cat_name' => $request->input('cat_name'),
'description' => $request->input('description'),
'cat_pic' => $fileName,
]);
Session::flash('alert', __('messages.created'));
Session::flash('alertClass', 'success');
return redirect()->route('catagories');
}
View
<div class="col-md-4 offset-5">
<div class="form-group">
<form role="form" action="<?php echo e('/products/cats') ?>" method="POST" id="createcat" >
{{ csrf_field() }}
<p>
Create New Product Category
</p>
<div class="form-group">
<label for="cat_name">
Name*:</label>
<input type="text" class="form-control"
id="cat_name" name="cat_name" required maxlength="50">
</div>
<div class="form-group">
<label for="cat_pic">Category Image* </label>
<input data-preview="#preview" class="form-control" name="cat_pic" type="file" id="cat_pic">
<img class="col-md-6" id="preview" height="100px" width="20px" src="">
</div>
<div class="form-group">
<label for="description">
Description*:</label>
<textarea class="form-control" type="textarea" name="description"
id="description" placeholder="Category Description"
maxlength="600" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-lg btn-success btn-block" id="btncreatecat">Create</button>
</form>
</div>
</div>
#endsection
#push('scripts')
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#cat_pic").change(function(){
readURL(this);
});
</script>
Route
Route::resource('products/cats', 'Admin\CatController');
and some JQuery to preview the image
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#cat_pic").change(function(){
readURL(this);
});
</script>
you need to add enctype="multipart/form-data" to the <form> tag.
Like this:
<form role="#" action="#" method="#" id="#" enctype="multipart/form-data">
So your form can send other things than text.
I realized the problem is I just forgot to add enctype="multipart/form-data" inside the form tag.
I am writing a code for image upload and want to implement AJAX for real time preview. As I have to upload four images on different button and they call different PHP file to upload in respective directory.
My code is working fine for single image upload as it needs to pass form ID.
but not working for all four images.
Please help me out and provide solution.
Below is the code -
<script type="text/javascript">
$(document).ready(function (e) {
$("#upload").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "update_profile_img.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer").html(data);
},
error: function()
{
}
});
}));
});
</script>
<div class="col-md-6">
<!-- Horizontal Form -->
<div class="box box-info">
<div class="box-header with-border">
<h3 class="box-title">Upload Documents</h3>
</div><!-- /.box-header -->
<!-- form start -->
<?php include('update_profile_img.php');?>
<?php include('update_car_img.php');?>
<?php include('update_licen_img.php');?>
<?php include('update_doc_img.php');?>
<p style="color:green"><?php echo $successMessage;?></p>
<p style="color:red"><?php echo $Error;?></p>
<div class="box-body">
<form role="form" action="#" id="upload" method="POST" enctype="multipart/form-data">
<div class="form-group">
<img class="form-control" style="width:100px; height:100px" alt="" src=<?php echo $target_file; ?> >
<label for="exampleInputFile">Profile Image</label>
<input type="file" class="form-control" name="image" id="image" />
<input type="hidden" class="form-control" name="user_id" value="<?php echo $user_id;?>" />
<button type="submit" name="profile_btn" class="btn btn-primary">Upload</button> <!-- -->
<small>File should be in image format.</small>
</div>
<div class="form-group">
<img class="form-control" style="width:100px; height:100px" alt="" src=<?php echo $target_file1;?> >
<label for="exampleInputFile">Car Image</label>
<input type="file" class="form-control" name="car_image" id="car_image" />
<button type="submit" name="car_btn" class="btn btn-primary">Upload</button>
<small>File should be in image format.</small>
</div>
<div class="form-group">
<img class="form-control" style="width:100px; height:100px" alt="" src=<?php echo $l_img;?> >
<label for="exampleInputFile">Driving License</label>
<input type="file" class="form-control" name="drivelic" id="drivelic"/>
<button type="submit" name="licen_btn" class="btn btn-primary">Upload</button>
<small>File should be in image format.</small>
</div>
<div class="form-group">
<img class="form-control" style="width:100px; height:100px" alt="" src=<?php echo $d_img;?> >
<label for="exampleInputFile">Vehicle Documents</label>
<input type="file" class="form-control" name="vehicledoc" id="vehicledoc"/>
<button type="submit" name="doc_btn" class="btn btn-primary">Upload</button>
<small>File should be in image format.</small>
</div>
</form>
<div class="box-footer">
</div>
</div><!-- /.box-body -->
</form>
</div><!-- /.box -->
</div><!-- /.box-body -->
</div><!--/.col (right) -->
</div> <!-- /.row -->
</section><!-- /.content -->
</div><!-- /.content-wrapper -->
PHP code to upload profile image update_profile_img.php-
<?php
include('../config/conn.php');
$Error ="";
$successMessage ="";
if (isset($_POST['profile_btn'])){
if(!empty($_POST['user_id']) && !empty($_FILES['image']))
{
if($_FILES['image'] != "jpg" && $_FILES['image'] != "png" && $_FILES['image'] != "jpeg" && $_FILES['image'] != "gif" && $_FILES["image"]["size"] > 2097152 )
{
//echo "6";
$Error="Invalid Image!";
}
else
{ $id=$_POST['user_id'];
$target_dir = "images/profile/";
$db_dir = "images/profile/";
$date=rand(0,999);
$datemd=md5($date);
$date=substr($datemd,2,-7);
//$unique_id=substr($date, 3, -3);
$target_file = $target_dir .$date. basename($_FILES["image"]["name"]);
$user_image = $db_dir .$date. basename($_FILES["image"]["name"]);
//$pic=addslashes (file_get_contents($_FILES['image']['tmp_name']));
if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file))
{
$sql = "UPDATE pooler SET image='$user_image' WHERE id='$id'";
if ($conn->query($sql) === TRUE)
{
//echo "1";
$successMessage="Profile Image Updated Successfully!";
return '$target_file';
}
else
{
//echo "2";
$Error="Error in Updating Image!";
}
}
else
{
$Error="Image Not Inserted Properly!";
}
}
}
else
{
//echo "4";
$Error="Fill The Required Fields!";
}
}
?>
PHP code to upload car image
<?php
include('../config/conn.php');
$Error ="";
$successMessage ="";
if (isset($_POST['car_btn'])){
if(!empty($_POST['user_id']) && !empty($_FILES['car_image']))
{
if($_FILES['car_image'] != "jpg" && $_FILES['car_image'] != "png" && $_FILES['car_image'] != "jpeg" && $_FILES['car_image'] != "gif" && $_FILES["car_image"]["size"] > 2097152 )
{
//echo "6";
$Error="Invalid Image!";
}
else
{ $id=$_POST['user_id'];
$target_dir = "images/car/";
$db_dir = "images/car/";
$date=rand(0,999);
$datemd=md5($date);
$date=substr($datemd,2,-7);
//$unique_id=substr($date, 3, -3);
$target_file1 = $target_dir .$date. basename($_FILES["car_image"]["name"]);
$user_image = $db_dir .$date. basename($_FILES["car_image"]["name"]);
//$pic=addslashes (file_get_contents($_FILES['image']['tmp_name']));
if (move_uploaded_file($_FILES["car_image"]["tmp_name"], $target_file1))
{
$sql = "UPDATE pooler SET car_image='$user_image' WHERE id='$id'";
if ($conn->query($sql) === TRUE)
{
//echo "1";
$successMessage="Car Image Updated Successfully!";
return 'target_file1';
}
else
{
//echo "2";
$Error="Error in Updating Image!";
}
}
else
{
$Error="Image Not Inserted Properly!";
}
}
}
else
{
//echo "4";
$Error="Fill The Required Fields!";
}
}
?>
I also try to include all upload file code in one file and pass different Target_file variable as target_file and target_file1.