Page refreshes after image upload - php

After I've uploaded an image my page refreshes and I'm not sure how to stop that from happening. I do have e.preventDefault().
I do know that it might have to do with this line
if(in_array($ext, $allowed) && move_uploaded_file($temp, 'uploads/'.$name))
Here is my code
$(document).ready(function(){
var dropZone = document.getElementById('drop-zone');
$(".upload-area").on('drop', function(e){
e.preventDefault();
var files_list = e.originalEvent.dataTransfer.files;
var formData = new FormData();
for(i = 0; i < files_list.length; i++){
formData.append('file[]', files_list[i]);
}
uploadData(formData);
dropZone.ondragover = function(e){
return false;
}
dropZone.ondragleave = function(e){
return false;
}
});
function uploadData(formdata){
$.ajax({
url: 'upload.php',
type: 'post',
data: formdata,
contentType: false,
processData: false,
dataType: 'json',
success: function(response){
addThumbnail(response);
}
});
}
function addThumbnail(data){
var len = $("#uploadfile div.thumbnail").length;
var num = Number(len);
num = num + 1;
var src = data.src;
// console.log(len);
$("#thumbnail_"+num).append('<img src="'+src+'" width="100%" height="78%">');
}
my upload.php
$allowed = ['png', 'jpg'];
foreach($_FILES['file']['name'] as $key => $name)
{
$temp = $_FILES['file']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
if(in_array($ext, $allowed) && move_uploaded_file($temp, 'uploads/'.$name))
{
$return_arr = array("name" => $filename,"size" => $filesize);
}
echo json_encode($return_arr);
}
my index.php
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="files[]" id="file" multiple>
<!-- Drag and Drop container-->
<div class="upload-area" id="drop-zone">
<h1>Drag and Drop file here<br/>Or<br/>Click to select file</h1>
</div>
</form>

Put submit button in hidden format. Follow below steps.
In HTML,
<input type="submit" id="submitBtn" style="display:none;">
In Javascript,
function submitMe() {
$("#submitBtn").trigger("click");
}
$(".upload-area").on('drop', function(e){
----
----
submitMe();
});

Related

How to insert file and other input type using php and ajax using function

I am trying to insert file and text to database using ajax but it is not working.
the main problem is file which is not inserting in database
Here is my code
<form id="descriptionsubmit" enctype = "multipart/form-data">
<textarea class="form-control" id="textarea-description" placeholder="Write Something"></textarea>
<input type="file" name="upload-pic" id="upload-pic" class="inputfile" >
<button type="submit" class="update-btn">Next</button>
</form>
Ajax for same
the alert(data)is showing nothing
$(function(){
$('form#descriptionsubmit').on('submit', function (e) {
e.preventDefault();
var file_data = $('#upload-pic').prop('files')[0];
var formData = new FormData(this);
$.ajax({
method: "POST",
url : "AJAXSubmitClientData.php",
data :formData,
dataType : "html",
contentType: false,
enctype: 'multipart/form-data',
cache: false,
processData:false,
success:function(data)
{
alert(data);
}
});
Php code Here the description is inserting but file not
if(isset($_POST['formData']))
{
$file = array(
"name" => $_FILES['form_data']['name'],
"tmp_name" => $_FILES['form_data']['tmp_name']
);
print_r($file);
$fileinserted = $objMaster->imageinsert($file);
$dataDescription = array(
"description" => $_POST['description'],
"projectProfile" => $fileinserted,
);
echo $insertdata = $objMaster->updateJobPostTable($dataDescription,$_SESSION['lastinsertid']);
echo 1;
}
imageinsert Function
public function imageinsert($file, $path = "") {
$fname = "";
$uploadpath = "";
if ($path == "") {
$uploadpath = $this->upload1;
} else {
$uploadpath = $this->upload1 . $path . "/";
}
$current_timestamp = $this->timeStamp();
$filename = basename($file['name']);
$newname = $current_timestamp . $filename;
if ((move_uploaded_file($file['tmp_name'], $uploadpath . $newname))) {
$fname = $newname;
}
return $fname;
}
Any help is appreciated
HTML Page :-
change the button property value to type="button" instead of type="submit" & add onclick Event Attribute.
<form id="descriptionsubmit" action="" method="post" enctype = "multipart/form-data">
<textarea class="form-control" name="textarea-description" placeholder="Write Something"></textarea>
<input type="file" name="upload-pic" id="upload-pic" class="inputfile" >
<button type="button" onclick="addData()" class="update-btn">Next</button>
</form>
JS AJax Code:-
function addData() {
var formData = new FormData($('#descriptionsubmit')[0]);
formData.append('action', 'add');
$.ajax({
method: 'post',
processData: false,
contentType: false,
cache: false,
enctype: 'multipart/form-data',
url: 'AJAXSubmitClientData.php',
data: formData,
success:function(msg){
alert(msg);
}
});
}
AJAXSubmitClientData.php
<?php
include('dbconn.php');
if(isset($_POST["action"]) && $_POST["action"]=="add"){
echo $a = $_POST["textarea-description"];
echo $g = $_FILES["upload-pic"]["name"];
// insert code here.
}
?>

How to insert and move multiple image using codeigniter?

view:
<script>
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
product_name = $("#product_name").val();
color = $("#colorWell").val();
$.ajax({
type:"POST",
data:{"product_name":product_name, "color":color},
url:"<?php echo base_url(); ?>admin/products",
success:function(data){
alert(data);
}
});
});
});
</script>
<input type="text" class="form-control" id="product_name" name="product_name">
<input type="color" id="colorWell" name="color">
<input type="file" id="product_image" name="product_image[]" multiple>
<input type="submit" class="btn btn-primary" id="submit" name="submit">
controller:
public function products()
{
$product_name = $this->input->post('product_name');
$color = $this->input->post('color');
$dataInfo = array();
$files = $_FILES;
$cpt = count($_FILES['product_image']['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES['product_image']['name']= $files['product_image']['name'][$i];
$_FILES['product_image']['type']= $files['product_image']['type'][$i];
$_FILES['product_image']['tmp_name']= $files['product_image']['tmp_name'][$i];
$_FILES['product_image']['error']= $files['product_image']['error'][$i];
$_FILES['product_image']['size']= $files['product_image']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload();
$dataInfo[] = $this->upload->data();
}
$data = array(
'product_name' => $product_name,
'color' => $color,
'product_image' => implode(",",$dataInfo['product_image']),
);
$result_set = $this->db->insert('add_product',$data);
if($sql == true)
{
echo 'New Product Added';
}
else
{
echo 'Unable to Proceed!';
}
}
private function set_upload_options()
{
$config = array();
$config['upload_path'] = ''.base_url().'resource/product/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
return $config;
}
In this code I am trying to insert and wants to move an image into a folder. But Now, problem is that when I click on submit button it throw an error as show in below:
Message: Undefined index: product_image
and query looks:
INSERT INTO `product` (`product_name`, `color`, `product_image`) VALUES ('men hoodies','#004080', NULL)
I don't know where am I doing wrong. So, How can I solve this issue? Please help me.
Thank You
Send all formdata with file in your ajax.
HTML code like this...
<form method="POST" id="YourFormID" enctype="multipart/form-data">
<input type="text" class="form-control" id="product_name" name="product_name">
<input type="color" id="colorWell" name="color">
<input type="file" id="product_image" name="product_image[]" multiple>
<input type="submit" class="btn btn-primary" id="submit" name="submit">
</form>
Ajax code here....
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
var formData = new FormData($('form#YourFormID')[0]);
$.ajax({
type:"POST",
data:formData,
url:"<?php echo base_url(); ?>admin/products",
success:function(data){
alert(data);
}
});
});
});
</script>
You are not send file in your ajax request. therefore not found index product_image
You didn't submit the files data.
Use formData to upload files data, and append any other input you like to add to formData :
<script>
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
product_name = $("#product_name").val();
color = $("#colorWell").val();
var formData = new FormData();
$.each($("#product_image"), function (i, obj) {
$.each(obj.files, function (j, file) {
formData.append('product_image[' + i + ']', file);
});
});
formData.append('product_name', product_name);
formData.append('color', color);
$.ajax({
type:"POST",
data:formData,
processData: false,
contentType: false,
url:"<?php echo base_url(); ?>admin/products",
success:function(data){
alert(data);
}
});
});
});
</script>
use array_column like below to add get all product_image values
implode(",",array_column($dataInfo, 'product_image'))

how to fix image input value "null" in laravel 5.6?

in my laravel application I am using dropzone programmatically to upload images. this is my Controller to store images in VehicleController
$photos = $request->file('file');
dd($photos);
if (!is_array($photos)) {
$photos = [$photos];
}
if (!is_dir($this->photos_path)) {
mkdir($this->photos_path, 0777);
}
for ($i = 0; $i < count($photos); $i++) {
$photo = $photos[$i];
$name = sha1(date('YmdHis') . str_random(30));
$save_name = $name . '.' . $photo->getClientOriginalExtension();//this is line 75
$resize_name = $name . str_random(2) . '.' . $photo->getClientOriginalExtension();
Image::make($photo)
->resize(250, null, function ($constraints) {
$constraints->aspectRatio();
})
->save($this->photos_path . '/' . $resize_name);
$photo->move($this->photos_path, $save_name);
$upload = new Upload();
$upload->filename = $save_name;
$upload->resized_name = $resize_name;
$upload->original_name = basename($photo->getClientOriginalName());
$upload->save();
}
return Response::json([
'message' => 'Image saved Successfully'
], 200);
and programatically jquery is
Dropzone.autoDiscover = false;
// Dropzone class:
var myDropzone = new Dropzone("div#my-dropzone", { url: '/form'});
routes
Route::post('form','VehicleController#store');
My blade file is
<div class="dropzone" id="my-dropzone">
<div class="dz-message">
<div class="col-xs-8">
<div class="message">
<p>Drop files here or Click to Upload</p>
</div>
</div>
</div>
<div class="fallback">
<input type="file" name="file" multiple>
</div>
</div>
but when my form submit button clicked following errors occurred,
1/1) FatalErrorException
Call to a member function getClientOriginalExtension() on null
in VehicleController.php line 75
when I use dd(photos); on
$photos = $request->file('file');
result comming in 'null' massage then, how can fix this problem?
Please try using below AJAX Code.
<form method="post" action="{{url('form')}}" enctype="multipart/form-data">
Remove the Action(action="{{url('form')}}") from your form Tag.
var datastring = $('#fromid').serialize();
$.ajax({
url: "controller url",
type: 'post',
contentType: "application/x-www-form-urlencoded",
data: datastring,
success: function(data){
if(data == '100'){
if($('#file').val() != ''){
var form = $('#fromid')[0];
var formData = new FormData(form);
var imageurl='controller image upload url';
$.ajax({
url:imageurl,
type:"post",
data:formData,
processData:false,
contentType:false,
cache:false,
async:false,
success: function(data){
setTimeout(function(){
window.location.href="redirect url";
},4000);
}
});
}else{
setTimeout(function(){
window.location.href="redirct url";
},4000);
}
}else{
alert(data);
}
}
});
-------- Controller code.
Print_r($_FILES); //You got the result.
Need to add enctype attribute as:
<form action="" method="post" enctype="multipart/form-data">input here</form>
Please add enctype="multipart/form-data" in form. Like this:
<form action="" method="post" enctype="multipart/form-data">

Need fix on stopping page reloading after file uploading

I'm trying to upload files to the server without page refresh. The uploading works but the page reloads after the uploading is done which is not what I wanted. I'm redirecting to an iframe ("myFrame") to stop the page reloading but it appears this doesn't work correctly. What did I do wrong?
HTML
<form id="upload" target="myFrame" action="sql/main-pix-upload.php" method="post" enctype="multipart/form-data">
<input id="main-pix" class="hidden" name="main_pix" type="file" onchange="uploadPix()" accept="image/*"/>
<label class="gi gi-camera mb-0 text-white" for="main-pix" type="button" title="Change Picture"></label>
</form>
<iframe class="hidden" name="myFrame"></iframe>
SCRIPT
function uploadPix(){
var form = document.getElementById('upload');
form.onsubmit = function(e){
e.preventDefault()
var formData = new FormData(this);
$.ajax({
url: 'sql/main-pix-upload.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false
})
});
};
PHP
$account = $_SESSION['account'];
$order = $_SESSION['order'];
$id = $_SESSION['id'];
$pathPix = ('../accounts/'.$account.'/'.$order.'/pix/'.$id.'/');
if(!is_dir($pathPix)){
mkdir($pathPix, 0777, true);
}
$file_name = $_FILES['main_pix']['name'];
$file_size = $_FILES['main_pix']['size'];
$extension = pathinfo($file_name, PATHINFO_EXTENSION);
$new_name = "main-pix.png";
$temp = ($_FILES["main_pix"]["tmp_name"]);
$target_file = ($pathPix.$new_name);
if(0 < $_FILES['main_pix']['error']){
echo 'Error: ' . $_FILES['main_pix']['error'] . '<br>';
}else{
move_uploaded_file($temp, $target_file);
}
Either use:
form.onsubmit = function(e) {
e.preventDefault()
};
or:
form.addEventListener("submit", function(e) {
e.preventDefault();
});
And then you have to make the HTTP-Call by yourself using AJAX.

file upload and form data on single form using ajax

I have a html form with 2 input filed and a file upload form and i want to send these data to some index.php file using ajax what i did so far is
<form class="col-md-3" id="form" name="reg" method="post" action="index.php" enctype="multipart/form-data">
<label>Name</label>
<input type="text" name="name" class="form-control" id="name">
<label>Address</label>
<input type="text" name="address" class="form-control">
<div id="sugg">
</div>
<input type="file" name="file">
<input type="button" name="submit" class="btn-default" id="btn" value="submit">
</form>
jquery for send data using ajax is
$("#btn").click(function() {
$.ajax({
url: "index.php",
type: "POST",
data: new FormData($('form')[0]),
cache: false,
conentType: false,
processData: false,
success: function(result) {
console.log(result);
}
});
});
php file has just this
echo $_POST["name"];
but in my browser window i am undefined index
I found similar questions but all that doesn't solved my problem that's why i asking your help please help me to find my error
I am create below code according to my need and you can make changes according to your requirement:
when you click upload/select file button use this function :
$('input[type=file]').on('change', function(e){
e.preventDefault();
$this = $(this);
if($this.prop("files")){
if(setImagestoUpload(e, $this.prop("files"), $this.attr("name"))){
var reader = new FileReader();
reader.onload = function(e){
$('.brandLogo img').attr("src", e.target.result);
$this.parent().prev("img.imageSelection").attr("src", e.target.result);
};
reader.readAsDataURL(this.files[0]);
}
}
});
function setImagestoUpload(e, $file, name){
e.preventDefault();
var type = [];
var isSize = [];
$($file).each(function(i, v){
type[i] = isImage(v);
isSize[i] = isValidSize(2, v.size);
});
if($.inArray(false, type) === -1){
if($.inArray(false, isSize) === -1){
/*if(checkTotalFileInputs() > 1 && files.length>0){
$.each($file, function(ind, val){
files[name] = val;
});
files[name] = $file[0];
}else{
files = $file;
}*/
formData.append(name, $file[0]);
console.log(files);
return true;
}else{
alert("Error: Upload max size limit 2MB");
}
}else{
alert("Please select only image file format to upload !");
return false;
}
}
function isImage(file){
var type = file.type.split("/");
if(type[0] === "image"){
return true;
}else{
return false;
}
}
and when you submit form then use below function:
function fileAndFormSubmit(ev, $this, get, options){
var defaults = {
redirect : false,
redirectTo : "#",
redirectAfter : 5000
};
var settings = $.extend({}, defaults, options);
removeErrorAndSuccess();
var $form = $($this).parent('form');
/*var formData = new FormData();
if(files.length > 0){
$.each(files, function(key, val){
formData.append(key, val);
});
}*/
var doc = {
data : $form.serialize()
};
formData.append("doc", doc.data);
/*Call to ajax here*/
}

Categories