File upload not submitting through ajax - php

I created a form upload which contains some inputs but when I submitted the form to ajax, ajax was unable to grap the file name.
I keep on getting Notice: Undefined index: userImage in C:\wamp\www\osun\i_admin\php_action\uploadImage.php on line 14 . userImage is the name of the file
index.php
<?php include('header.php'); ?>
<?php include('top.php'); ?>
<?php include('links.php'); ?>
<section class="content">
<div class="container-fluid">
<div class="block-header">
<h2>Worker of the Month</h2>
</div>
<!-- Basic -->
<div class="row clearfix">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="card">
<div id="error" class="closeit"></div>
<div id="messages"></div>
<div class="body">
<form enctype="multipart/form-data" id="uploadImageForm">
<div class="form-group form-float">
<div class="form-line">
<input type="text" class="form-control" name="name" id="name">
<label class="form-label">Worker's Name</label>
</div>
</div>
<div class="form-group form-float">
<div class="form-line">
<input type="text" class="form-control" name="dept" id="dept">
<label class="form-label">Department</label>
</div>
</div>
<div class="form-group form-float">
<div class="input-group">
<div class="form-line">
<input type="text" data-type="date" id="date" name="date" placeholder="Date" class="form-control datepicker">
</div>
</div>
</div>
<div class="form-group form-float">
<div class="form-line">
<textarea name="description" id="description" cols="30" rows="5" class="form-control no-resize"></textarea>
<label class="form-label">Description</label>
</div>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Photo</label>
<div id="kv-avatar-errors-2" class="center-block" style="width:800px;display:none"></div>
<div class="kv-avatar center-block" style="width:200px">
<input id="avatar-2" name="userImage" type="file" class="file-loading">
</div>
</div>
<div class="form-group" align="center">
<button type="input" name="submit" class="btn btn-success btn-md btn-icon waves-effect" id="btn-submit" ><i class="fa fa-check-square-o"></i> Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- #END# Basic -->
</div>
</section>
<?php include('footer.php'); ?>
uploadimage.php
include('../../includes/functions.php');
if($_POST) {
$valid = array('success' => false, 'messages' => array());
$name = $mysqli->real_escape_string($_POST['name']);// user name
$dept = $mysqli->real_escape_string($_POST['dept']);
$desc = $mysqli->real_escape_string($_POST['description']);// user email
$yr = $mysqli->real_escape_string($_POST['date']);
$fileName = $_FILES['userImage']['name'];
$type = explode('.', $fileName);
$type = $type[count($type) - 1];
$url = '../user_images/' . uniqid(rand()) . '.' . $type;
if(in_array($type, array('gif', 'jpg', 'jpeg', 'png'))) {
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
if(move_uploaded_file($_FILES['userImage']['tmp_name'], $url)) {
// insert into database
$sql = "INSERT INTO worker_of_the_month (name, dept, description, given, img) VALUES ('$name','$dept','$desc','$yr', '$url')";
if($mysqli->query($sql) === TRUE) {
$valid['success'] = true;
$valid['messages'] = "Successfully Saved.";
}
else {
$valid['success'] = false;
$valid['messages'] = "Error while saving. " . $mysqli->error;
}
$mysqli->close();
}
else {
$valid['success'] = false;
$valid['messages'] = "Error while saving. " . $mysqli->error;
}
}
}
echo json_encode($valid);
// upload the file
}
Ajax.js
$('document').ready(function() {
/* validation */
$("#uploadImageForm").validate({
rules:
{
name:{
required: true
},
dept:{
required: true
},
description:{
required: true
},
date:{
required: true
},
},
messages:
{
name: "Worker name required",
dept: "Worker department name required",
description: "Enter description for this honour.",
date: "Please select date",
},
submitHandler: submitForm
});
/* validation */
/* form submit */
function submitForm()
{
var data = $("#uploadImageForm").serialize();
$.ajax({
type : 'POST',
url : 'php_action/uploadImage.php',
data : data,
beforeSend: function()
{
$("#error").fadeOut();
$("#btn-submit").html('<img src="../img/processing.gif" width="30" /> processing');
},
success : function(data)
{
if(data.success == true)
{
$("#btn-submit").html('<img src="../img/processing.gif" width="30" /> Saving ...');
$("#messages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
data.messages +
'</div>');
$('#uploadImageForm')[0].reset();
/*setTimeout(' window.location.href = "success.php"; ',4000);*/
}
else{
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> '+data+' !</div>');
$("#btn-submit").html('<span class="fa fa-check-square-o"></span> Save');
});
}
}
});
return false;
}
/* form submit */
});
</script>
What am I doing wrong?

You need to use a FormData() to pass files.
Change
var data = $('#uploadImageForm').serialize();
to
var form = $('#uploadImageForm')[0];
var data = new FormData(form);
As #ThisGuyHasTwoThumbs pointed you should set cache, contentType and processData via your ajax call
$.ajax({
cache: false,
processData: false,
contentType: false,
//other ajax parameters
});

You cannot POST files via AJAX like you have your code now.
This is how you can upload files using javascript and way better option:
PHP:
<?php
$fileName = $_FILES['afile']['name'];
$fileType = $_FILES['afile']['type'];
$fileContent = file_get_contents($_FILES['afile']['tmp_name']);
$dataUrl = 'data:' . $fileType . ';base64,' . base64_encode($fileContent);
$json = json_encode(array(
'name' => $fileName,
'type' => $fileType,
'dataUrl' => $dataUrl,
'username' => $_REQUEST['username'],
'accountnum' => $_REQUEST['accountnum']
));
echo $json;
?>
HTML:
<!DOCTYPE html>
<!--
Copyright 2012 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Author: Eric Bidelman (ericbidelman#chromium.org)
-->
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
<title>xhr.send(FormData) Example</title>
</head>
<body>
<input type="file" name="afile" id="afile" accept="image/*"/>
<script>
document.querySelector('#afile').addEventListener('change', function(e) {
var file = this.files[0];
var fd = new FormData();
fd.append("afile", file);
// These extra params aren't necessary but show that you can include other data.
fd.append("username", "Groucho");
fd.append("accountnum", 123456);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'handle_file_upload.php', true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
console.log(percentComplete + '% uploaded');
}
};
xhr.onload = function() {
if (this.status == 200) {
var resp = JSON.parse(this.response);
console.log('Server got:', resp);
var image = document.createElement('img');
image.src = resp.dataUrl;
document.body.appendChild(image);
};
};
xhr.send(fd);
}, false);
</script>
<!--[if IE]>
<script src="http://ajax.googleapis.com/ajax/libs/chrome-frame/1/CFInstall.min.js"></script>
<script>CFInstall.check({mode: 'overlay'});</script>
<![endif]-->
</body>
</html>
Quick example taken from: https://gist.github.com/ebidel/2410898

Related

Problems to send image from Ajax, FormData and receive with PHP

Help, try upload a image from a form with js, using Ajax,FormData
MODAL FORM,
FORM USED TO COLLECT THE INFORMATION AND THE IMAGE
<div id="modal-editar" style="display: none">
<form id="pais-editar" >
<div class="Listar-table">
<div class="Listar-table-dato">
<span class="">Nombre Empresa</span>
</div>
<div class="Listar-table-dato">
<span class="Forms-table">
<input type="text" name="conf[pais]" id="pais-ed" required="">
</span>
</div>
</div>
<div class="Listar-table">
<div class="Listar-table-dato">
<span class="">MONEDA (Abreviatura)</span>
</div>
<div class="Listar-table-dato">
<span class="Forms-table">
<input type="text" name="conf[moneda]" id="moneda-ed" required="">
</span>
</div>
</div>
<div class="Listar-table">
<div class="Listar-table-dato">
<span class="">Bandera</span>
</div>
<div class="Listar-table-dato">
<span class="Forms-table">
<input type="file" name="bandera" accept="image/x-png,image/gif,image/jpeg" />
</span>
</div>
</div>
<div id="mensaje-editar">
</div>
<div class="Contendedor-filtro-der Contener-btn" style="text-align: center;">
<input type="submit" class="Btn-naranja-auto" name="" value="Guardar Pais">
</div>
</form>
</div>
JS FUNCTION, THIS TAKES THE INFORMATION FROM THE FORM AND SEND IT USING AJAX
$('body').on('submit', '#pais-editar', function(e) {
e.preventDefault();
$('#modal-editar').iziModal('startLoading');
var data = new FormData();
$.each($('#bandera'), function(i, obj) {
$.each(obj.files, function(j, file) {
data.append('bandera', file);
});
});
otradata = $('#pais-editar').serializeArray();
$.each(otradata, function(key, input) {
data.append(input.name, input.value);
});
data.append('conf[id]', pais_id);
data.append('conf[opc]', 'pais-editar');
$.ajax({
url: 'libs/ac_configuracion',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
dataType: 'json',
success: function(data) {
$('#modal-editar').iziModal('stopLoading');
if (data.status == true) {
$('#modal-editar').iziModal('resetContent');
iziToast.success({
title: 'Correcto',
message: data.msg,
position: 'center',
overlay: true,
displayMode: 1,
target: '#mensaje-editar',
pauseOnHover: false
});
lista_paises(1);
} else {
iziToast.error({
title: 'Error',
message: data.msg,
position: 'center',
overlay: true,
displayMode: 1,
target: '#mensaje-editar',
pauseOnHover: false
});
}
}
});
});
and finally this is my php code that receives the data, uploads the image and edits the information
$codigo = explode('-', $data['id']);
#$nombre_adjunto = $_FILES['bandera']['name'];
#$tmp_adjunto = $_FILES['bandera']['tmp_name'];
$folder_gastos = '../banderas';
$trozo1=explode(".", $nombre_adjunto);
$nombre_archivo= 'bandera_'.($data['pais']).'.'.end($trozo1);
#$target_path = $folder_gastos.'/'.$nombre_archivo; //Indicamos la ruta de destino, así como el nombre del archivo
move_uploaded_file($tmp_adjunto, $target_path);
$dats = ['nombre_pa' => $data['pais'], 'moneda_pa' => $data['moneda'] , 'bandera' => $nombre_archivo];
$nuevo = $db
->where('Id_pa', $codigo[1])
->update('paises', $dats);
if ($nuevo) {
$msg['status'] = true;
$msg['msg'] = 'País Editado';
} else {
$msg['status'] = false;
$msg['msg'] = 'No se ha podido editar el país';
}
echo json_encode($msg);
it's supposed to work, the text information arrives but the image does not

Unable to get posted FormData form data in php

I am using Angular in this code to send formData to my upload.php file and then from upload.php, copying file to another Direcrtory and insert its address to MySQL musiclist data base but my code isn't working and not even showing any Error I don't know what to do
Any help would be Appreciable
<body>
<div class="container" ng-app="myapp" ng-controller="cntrl">
<div class="col-md-4">
<input type="file" file-input="files">
</div>
<div class="col-md-6">
<button class="btn btn-info" ng-click="uploadfile()">upload</button>
</div>
</div>
<div class="container" ng-app="myapp" ng-controller="cntrl">
<div class="col-md-4">
<input type="file" file-input="files">
</div>
<div class="col-md-6">
<button class="btn btn-info" ng-click="uploadfile()">upload</button>
</div>
</div>
</body>
</html>
<script>
var app = angular.module("myapp",[]);
app.directive("fileinput", function($parse){
return{
link : function($parse,element,attrs){
element.on("change", function(event){
var files = event.target.files;
$parse(attrs.fileInput).assign(element[0].files);
$scope.apply();
});
}
}
});
app.controller("cntrl",function($scope,$http){
$scope.uploadfile = function(){
var form_data= new FormData();
angular.forEach($scope.files, function(file){
form_data.append('file',file);
});
$http.post('upload.php', form_data,
{
transformRequest: angular.identity,
headers{'Content-Type': undefined ,'Process-Data': false}
}).success(function(response){
alert(response);
});
}
});
upload.php Code is
<?PHP
$connect= mysqli_connect("localhost","root","","musiccloud");
if(!empty($_FILES)){
$path='uploads/'.$_FILES['file'['name'];
if(move_uploaded_file($_FILES['file']['tmp_name'],$path))
{
$Insertquery= "INSERT INTO musiclist(name) VALUES('".$_FILES['file']
['name']."')";
if(mysqli_query($connect,$Insertquery))
{
echo 'file Uploaded';
}
else{
echo 'file Not Uploaded';
}
}
}
else{
echo 'some Error';
}
?>

I am not getting any text value in form input in codeigniter

I am very new to Codeigniter. I m trying to create a form with some text input field along with two image upload field. The image uploading working fine but the text input field value are not coming. Can anyone please check my code and tell me where I am doing wrong Here is my Code:
Front End
<body>
<div class="custom-container">
<div id="msg"></div>
<form id="product-upload" action="/index.php/uploadproduct/upload" method="POST" accept-charset="utf-8" enctype="multipart/form-data"">
<div class="form-group">
<label for="product-name">Product name</label>
<input type="text" name="product_name" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Code</label>
<input type="text" name="product_code" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Link</label>
<input type="text" name="product_link" class="form-control">
</div>
<div class="form-group">
<label for="product-image">Product image</label>
<input type="file" id="product-image" name="product_image" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Screenshots</label>
<input type="file" id="product-screen" name="product_screen" class="form-control" multiple>
</div>
<div class="form-group">
<input id="add-product" type="Submit" class="btn btn-primary" value="Add new product">
</div>
</form>
</div>
</body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#add-product').click(function(e){
e.preventDefault();
var formData = new FormData();
//for product profile images
var productProfile = $('#product-image').prop('files')[0];
formData.append('file',productProfile);
// for product detail image
var imageCount = document.getElementById('product-screen').files.length;
for (var i = 0; i< imageCount; i++) {
formData.append("files[]", document.getElementById('product-screen').files[i]);
}
//AJAX Call
$.ajax({
url: 'http://localhost/ci/index.php/uploadproduct/upload/', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
beforeSend: function() {
// setting a timeout
$('#msg').html('Loading');
},
success: function (response) {
$('#msg').html(response); // display success response from the server
$('input').attr('value').html();
},
error: function (response) {
$('#msg').html("no response"); // display error response from the server
}
});
});
});
</script>
Controller Script is this
public function upload(){
$uploadData = "";
//Get the details
$productName = $_POST['product_name'];
$productCode = $this->input->post('product_code');
$productLink = $this->input->post('product_link');
$uploadData = $productName.','.$productCode.','.$productLink;
// setting cofig for image upload
$config['upload_path'] = 'uploads/profile/';
$config['allowed_types'] = '*';
$config['max_filename'] = '255';
$config['encrypt_name'] = TRUE;
//$config['max_size'] = '1024'; //1 MB
// Get the profile image
$errorMsg = "";
if (isset($_FILES['file']['name'])) {
if (0 < $_FILES['file']['error']) {
$errorMsg = 'Error during file upload' . $_FILES['file']['error'];
} else {
if (file_exists('uploads/profile/' . $_FILES['file']['name'])) {
$errorMsg = 'File already exists : uploads/profile/' . $_FILES['file']['name'];
} else {
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file')) {
$errorMsg = $this->upload->display_errors();
} else {
$data = $this->upload->data();
$errorMsg = 'File successfully uploaded : uploads/profile/' . $_FILES['file']['name'];
$uploadData = $uploadData.','.$data['full_path'];
}
}
}
} else {
$errorMsg = 'Please choose a file';
}
//upload product screenshots
$config['upload_path'] = 'uploads/';
if (isset($_FILES['files']) && !empty($_FILES['files'])) {
$no_files = count($_FILES["files"]['name']);
$link="";
for ($i = 0; $i < $no_files; $i++) {
if ($_FILES["files"]["error"][$i] > 0) {
$errorMsg = "Error: " . $_FILES["files"]["error"][$i] . "<br>";
} else {
if (file_exists('uploads/' . $_FILES["files"]["name"][$i])) {
$errorMsg = 'File already exists : uploads/' . $_FILES["files"]["name"][$i];
} else {
$fileOriginalNmame = $_FILES["files"]["name"][$i];
$explodeFile = explode(".",$fileOriginalNmame);
$fileExtenstion = end($explodeFile);
$fileName = md5(md5(uniqid(rand(), true)).$_FILES["files"]["name"][$i]).'.'.$fileExtenstion;
move_uploaded_file($_FILES["files"]["tmp_name"][$i], 'uploads/' . $fileName);
$link= $link.$fileName.',';
}
}
}
$uploadData =$uploadData .','. $link;
$errorMsg = $uploadData;
} else {
$errorMsg = 'Please choose at least one file';
}
echo $errorMsg;
}
And if anyone can improve my controller code that will be very helpful tnx.
FormData() Method:
As per our definition .FormData() submit a element data in a Key/Value form. The Form element must have a name attribute. One advantage of FormData() is now you can post a files on next page.
Simple Syntax:
var formData = new FormData(form);
Highlight Points:
This method does post files.
This method post complete form using Get & Post method including files.
var formData = new FormData();
formData.append('username', 'joe');
In addition you could add a key/value pair to this using FormData.append.
So your code broke because you need to pass value of input as key/pair format that you missed except for file.
Hope this will help you.
Please find solution describe below.
$(document).ready(function(){
$('#add-product').click(function(e){
e.preventDefault();
var formData = new FormData();
//for product profile images
var productProfile = $('#product-image').prop('files')[0];
formData.append('file',productProfile);
// for product detail image
var imageCount = document.getElementById('product-screen').files.length;
for (var i = 0; i< imageCount; i++) {
formData.append("files[]", document.getElementById('product-screen').files[i]);
}
var inputs = $('#product-upload input[type="text"],input[type="email"]');
$.each(inputs, function(obj, v) {
var name = $(v).attr("name");
var value = $(v).val();
formData.append(name, value);
});
//AJAX Call
$.ajax({
url: 'http://localhost/ci/index.php/uploadproduct/upload/', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
beforeSend: function() {
// setting a timeout
$('#msg').html('Loading');
},
success: function (response) {
$('#msg').html(response); // display success response from the server
$('input').attr('value').html();
},
error: function (response) {
$('#msg').html("no response"); // display error response from the server
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="custom-container">
<div id="msg"></div>
<form id="product-upload" action="/index.php/uploadproduct/upload" method="POST" accept-charset="utf-8" enctype="multipart/form-data">
<div class="form-group">
<label for="product-name">Product name</label>
<input type="text" name="product_name" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Code</label>
<input type="text" name="product_code" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Link</label>
<input type="text" name="product_link" class="form-control">
</div>
<div class="form-group">
<label for="product-image">Product image</label>
<input type="file" id="product-image" name="product_image" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Screenshots</label>
<input type="file" id="product-screen" name="product_screen" class="form-control" multiple>
</div>
<div class="form-group">
<input id="add-product" type="Submit" class="btn btn-primary" value="Add new product">
</div>
</form>
</div>
Let me know if it not works for you.

how to pass the two file value in next page through AJAX while adding muliple image in single form field

Here i have two form fields(file upload),first user select the logo and select one banner image means value is getting in next page (home.php).suppose user select one logo and select multiple banner image means i can not get the value in next page (home.php).how can do this ?
<script>
var i=0;
$(document).on("click",".add_banner",function() {
i++;
var htmlText = '';
htmlText += '<div class="form-group"><label class="col-md-3 control-label">Project Banners</label><div class="col-md-6"><div class="fileupload fileupload-new" data-provides="fileupload"><div class="input-append"><div class="uneditable-input"><i class="fa fa-file fileupload-exists"></i><span class="fileupload-preview"></span></div><span class="btn btn-default btn-file"><span class="fileupload-exists">Change</span><span class="fileupload-new">Select file</span>';
htmlText +='<input type="file" name="banners[]" id="banners' + i +'">';
htmlText += '</span><span style="margin-left:10px"><button type="button" class="btn btn-default add_banner" id="add_banner">Add</button></span>Remove</div></div></div></div>';
$('#add_banner_append').append(htmlText);
});
</script>
<script>
$(document).ready(function(){
$('#btn-submit').click(function(){
if($('#empForm').valid()){
var formData = new FormData();
var formData = new FormData($('#empForm')[0]);
formData.append('logo', $('input[type=file]')[0].files[0]);
formData.append('banners', $('input[type=file]')[1].files[1]);
$.ajax({
type:'POST',
url :"php/home.php",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
if(data == "Success"){
$("#alert_success").show();
$("#alert_success").fadeOut(3000);
setTimeout(function () {
window.location.href = "dashboard.php";
}, 2000); //will call the function after 2 secs.
}
},
error:function(exception){
alert('Exeption:'+exception);
}
});
return false;
}
});
});
// Shorthand for $( document ).ready()
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form class="form-horizontal form-bordered" method="POST" id="empForm">
<div class="form-group">
<label class="col-md-3 control-label">Project Logo</label>
<div class="col-md-6">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="input-append">
<div class="uneditable-input">
<i class="fa fa-file fileupload-exists"></i>
<span class="fileupload-preview"></span>
</div>
<span class="btn btn-default btn-file">
<span class="fileupload-exists">Change</span>
<span class="fileupload-new">Select file</span>
<input type="file" id="logo" name="logo" required="" data-msg-required="File" value="" aria-required="true">
</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Project Banners</label>
<div class="col-md-6">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="input-append">
<div class="uneditable-input">
<i class="fa fa-file fileupload-exists"></i>
<span class="fileupload-preview"></span>
</div>
<span class="btn btn-default btn-file">
<span class="fileupload-exists">Change</span>
<span class="fileupload-new">Select file</span>
<input type="file" id="banners" name="banners[]" required="" data-msg-required="File" value="" aria-required="true">
</span><span style="margin-left:10px">
<button type="button" class="btn btn-default add_banner" id="add_banner">Add</button></span>
</div>
</div>
</div>
</div>
<div id="add_banner_append"></div>
<div class="form-group">
<div class="col-md-3">
</div>
<div class="col-md-6">
<input type="button" class="btn btn-primary btn-block" id="btn-submit" name="submit" value="SUBMIT">
</div>
</div>
</form
$postedBanners = array();
/* foreach ($_FILES['banners']['name'] as $key => $value) {
$postedBanners[$key] = array(
'name' => $_FILES['banners']['name'][$key],
'type' => $_FILES['banners']['type'][$key],
'tmp_name' => $_FILES['banners']['tmp_name'][$key],
'error' => $_FILES['banners']['error'][$key],
);
} */
$uploads_dir = '/banners';
foreach ($_FILES["banners"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["banners"]["tmp_name"][$key];
// basename() may prevent filesystem traversal attacks;
// further validation/sanitation of the filename may be appropriate
$name = $_FILES["banners"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
You are missing enctype in both html form and ajax calling. You should add enctype in form like as <form class="form-horizontal form-bordered" method="post" id="empForm" enctype="multipart/form-data">.
Aslo add enctype in ajax calling -
$('#btn-submit').click(function(){
if($('#empForm').valid()){
var formData = new FormData();
var formData = new FormData($('#empForm')[0]);
formData.append('logo', $('input[type=file]')[0].files[0]);
formData.append('banners', $('input[type=file]')[1].files[1]);
$.ajax({
type:'POST',
url :"test.php",
enctype: 'multipart/form-data',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
if(data == "Success"){
$("#alert_success").show();
$("#alert_success").fadeOut(3000);
setTimeout(function () {
window.location.href = "dashboard.php";
}, 2000); //will call the function after 2 secs.
}
},
error:function(exception){
alert('Exeption:'+exception);
}
});
return false;
}
});
I have added enctype: 'multipart/form-data' in ajax calling.
At server end you need to get all multiple added banner image as following -
if(!empty($_FILES['banners']['name'])){
$postedBanners = array();
foreach ($_FILES['banners']['name'] as $key => $value) {
$postedBanners[$key] = array(
'name' => $_FILES['banners']['name'][$key],
'type' => $_FILES['banners']['type'][$key],
'tmp_name' => $_FILES['banners']['tmp_name'][$key],
'error' => $_FILES['banners']['error'][$key],
);
}
echo '<pre>';
print_r($postedBanners);
}
I will return output as following -
Array
(
[0] => Array
(
[name] => preview.png
[type] => image/png
[tmp_name] => /private/var/tmp/php9Fyir9
[error] => 0
)
)
For Upload banner images in a folder.
$uploads_dir = '/uploads';
foreach ($_FILES["banners"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["banners"]["tmp_name"][$key];
// basename() may prevent filesystem traversal attacks;
// further validation/sanitation of the filename may be appropriate
$name = basename($_FILES["banners"]["name"][$key]);
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}

AJAX Maile sender + Multiple Attachment + Bootstrap plugin

i just have write script for sending emails. It take random email and send with random values - all works fine. Now i just want add option to send multiple images - Select random one and send with email.
I using bootstrap and i was find this plugin: http://plugins.krajee.com/file-input
But when i try to upload images i get 405 error. Meaby do you know any other way to send attachments with ajax?
Here is my code:
$("#dodawarka").submit(function(e){
e.preventDefault();
var tytul = $("#tytul").val();
var kontos = $("#lkonta").val();
var tresc = $("#tresc").val();
var jemail = $("#kemaile").val();
var jemail = $("#kemaile").val();
var dataString = 'listakont=' + kontos + '&tytul=' + tytul + '&tresc=' + tresc + '&emailjaki=' + jemail;
$.ajax({
type: "POST",
url: "dodaj.php",
data: dataString,
beforeSend: function(){
$('#tytul, #tresc, #przyciskx').prop( "disabled", true );
$('.wczytywanie').show();
},
success: function(){
$('#ddodaneok').show();
$('#dodawarka').slideUp();
$('#linkizwrotne').show();
},
error: function(){
$('#kurwasabledy').show();
}
});
return false;
});
And:
<form role="form" enctype="multipart/form-data" id="dodawarka" method="post">
<div class="form-group" id="listakont" style="visibility:hidden; position: absolute;">
<label for="listakont">Lista kont na które zostaną wysłane wpisy</label>
<textarea class="form-control" rows="10" id="lkonta" disabled></textarea>
</div>
<div class="form-group" id="ssssemail" style="visibility:hidden; position: absolute;">
<label for="ssssemail">Emaile z których będzie można wysyłam wpisy podaj w formacie</label>
<textarea class="form-control" rows="10" id="kemaile"></textarea>
</div>
<div class="form-group">
<label for="tytul">Podaj tytuł wpisu <em>+spintax</em></label>
<input type="tytul" class="form-control" id="tytul" required>
</div>
<div class="form-group">
<label for="tresc">Treść wpisu <em>+spintax</em></label>
<textarea class="form-control" rows="25" id="tresc" required></textarea>
</div>
<div class="form-group">
<label for="obrazki">Dodaj obrazki</label>
<input id="input-id" type="file" class="file" data-preview-file-type="text" multiple=true data-min-file-count="1">
</div>
<button type="submit" class="btn btn-default" id="przyciskx"><img src="img/infinity.gif" class="wczytywanie" /> Wyślij na zaplecza</button>
</form>
Try :
<input id="input-id" type="file" class="file" data-preview-file-type="text" multiple name="files[]" data-min-file-count="1">
Added: name="files[]"and only multiple not multiple=true.
And in php do:
$output = '';
if(is_array($_FILES)){
foreach($_FILES['files']['name'] as $name => $value)
{
$file_name = explode(".", $_FILES['files']['name'][$name]);
$allowed_ext = array("jpg", "jpeg", "png", "gif");
if(in_array($file_name[1], $allowed_ext))
{$new_name = $userid.md5(rand()).".".$file_name[1];
$sourcePath = $_FILES['files']['tmp_name'][$name];
$targetPath = "uploadedimages/".$new_name;
include_once("connection.php"); // your connection to DB and select DB
$sql = "INSERT into images(userid, imgpath) VALUES ('$userid', '$targetPath')";
$query = $conn->query($sql);
if($query && move_uploaded_file($sourcePath, $targetPath))
{
$output .= '<div class="col-md-3"><img src="'.$targetPath.'" class="img-thumbnail" width="150px" height="180px"/></div>';
}
}
}
}
echo $output;

Categories