PHPExcel attempting to read Excel file using ajax() call is failing - ajax

I am attempting to read an Excel File using PHPExcel Lib through an ajax call. However, the read attempt is causing an error of PHPExcel_Reader_Exception: Could not open for reading! File does not exist.
My index.php is as follows:-
<?php
ob_start();
ini_set("xdebug.var_display_max_children", -1);
ini_set("xdebug.var_display_max_data", -1);
ini_set("xdebug.var_display_max_depth", -1);
session_start();
if ( isset($_POST['label']) ) {
var_dump($_POST['label']);
}
?>
<!doctype html>
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<script>
var label;
function checkfile(sender) {
var validExts = new Array(".xlsx", ".xls");
var fileExt = sender;
fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
if (validExts.indexOf(fileExt) < 0) {
alert("Invalid file selected, valid files are of " +
validExts.toString() + " types.");
return false;
} else return true;
}
$(function() {
$(document).on('change', ':file', function() {
var input = $(this),
numFiles = input.get(0).files ? input.get(0).files.length : 1,
label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
input.trigger('fileselect', [numFiles, label]);
});
$(document).ready( function() {
$(':file').on('fileselect', function(event, numFiles, label) {
if(checkfile(label)== true){
var input = $(this).parents('.input-group').find(':text'),
log = label;
if(input.length) {
input.val(log);
} else {
// if(log) alert(log);
}
}
$.ajax({
//url:"../uploadxlsx/readxlsx.php",
url:"uploadxlsx/readxlsx.php",
method:"POST",
data:{label:label },
success:function(data){
$('#sheetnames').html(data);
}
});
});
});
});
</script>
</head>
<body>
<br>
<br>
<br>
<div class="container">
<table>
<thead>
<div class="input-group">
<label class="input-group-btn">
<span class="btn btn-primary">
Browse <input type="file" id="uploadfile" name="uploadfile" style="display: none;" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel">
</span>
</label>
<input type="text" class="form-control" readonly="">
</div>
</thead>
</table>
</div>
<div class="input-group" name='sheetnames' id='sheetnames'>
</div>
</body>
</html>
The ajax called php file readxlxs.php is as follows:-
<?php
ini_set("xdebug.var_display_max_children", -1);
ini_set("xdebug.var_display_max_data", -1);
ini_set("xdebug.var_display_max_depth", -1);
ob_start();
include_once $_SERVER['DOCUMENT_ROOT'] . '/CommandWks/phpAssets/Classes/PHPExcel.php';
$exceldata = array();
//$inputfilename = $_POST['label'];
$inputfilename = basename($_FILES['fileName']);
var_dump($inputfilename);
$inputfiletype = PHPExcel_IOFactory::identify($inputfilename);
$objReader = PHPExcel_IOFactory::createReader($inputfiletype);
$objPHPExcel = $objReader->load($inputfilename);
$excelReader = PHPExcel_IOFactory::createReaderForFile($inputfiletype);
$excelObj = $excelReader->load($inputfiletype);
$worksheet = $excelObj->getSheet(0);
$lastRow = $worksheet->getHighestRow();
var_dump($lastRow);
ob_end_flush();
?>
A screenshot of the error displayed is this
Where is the error? Or is it that PHPExcel cannot be used with ajax?

general advice
you could use browser debug console (F12 if chrome) to see if file actually got upload
you could var_dump($_FILES) to see actually what server got
this has nothing to do with begin ajax vs PHPExcel, I think you got it wrong at the basic level of how to handle form data in PHP
and on your question, since your file input is like this
<input type="file" id="uploadfile" name="uploadfile"
variable name must be
$_FILES["uploadfile"]
and "name" is just name, for actual file you'll have to use
$_FILES["uploadfile"]["tmp_name"]
read this for more info on $_FILES array structure
Array
(
[file1] => Array
(
[name] => MyFile.txt (comes from the browser, so treat as tainted)
[type] => text/plain (not sure where it gets this from - assume the browser, so treat as tainted)
[tmp_name] => /tmp/php/php1h4j1o (could be anywhere on your system, depending on your config settings, but the user has no control, so this isn't tainted)
[error] => UPLOAD_ERR_OK (= 0)
[size] => 123 (the size in bytes)
)
)

Related

How to save the content of a textarea using Ckeditor and CodeIgniter?

I'm using Codeigniter with Ckeditor. My problem is that when I submit the content, the data from the textarea is not stored in the database. But when I tried it again it finally did. So the situation is like I have to double click submit button to save it.
I stored the downloaded Ckeditor on a folder named ./Assests/Ckeditor(Sorry for the wrong spelling.I'll fix this later.)
Here's my form in my view folder:
ask_view.php:
<form id="form" enctype="multipart/data" method="post" onsubmit="createTextSnippet();">
<div class="form-group">
<label for="exampleInputEmail1">Title</label>
<input type="text" name ="title" class="form-control" id="title" placeholder="Title" required >
</div>
<input type="hidden" name="hidden_snippet" id="hidden_snippet" value="" />
<div class="form-group">
<label for="exampleInputEmail1">Editor</label>
<textarea name ="text" class="form-control" id="text" rows="3" placeholder="Textarea" required></textarea>
</div>
<input type="submit" class="btn " name="submit" value ="Submit" style="width: 100%;background: #f4a950;color:#161b21;">
</form>
<script src="<?php echo base_url('assests/js/editor.js')?>"></script>
<script type="text/javascript">
CKEDITOR.replace('text' ,{
filebrowserBrowseUrl : '<?php echo base_url('assests/filemanager/dialog.php?type=2&editor=ckeditor&fldr=')?>',
filebrowserUploadUrl : '<?php echo base_url('assests/filemanager/dialog.php?type=2&editor=ckeditor&fldr=')?>',
filebrowserImageBrowseUrl : '<?php echo base_url('assests/filemanager/dialog.php?type=1&editor=ckeditor&fldr=')?>'
}
);
</script>
<script type="text/javascript">
//code used to save content in textarea as plain text
function createTextSnippet() {
var html=CKEDITOR.instances.text.getSnapshot();
var dom=document.createElement("DIV");
dom.innerHTML=html;
var plain_text=(dom.textContent || dom.innerText);
var snippet=plain_text.substr(0,500);
document.getElementById("hidden_snippet").value=snippet;
//return true, ok to submit the form
return true;
}
</script>
<script type="text/javascript">
$('#form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/knowmore2/index.php/ask_controller/book_add',
data: $('form').serialize(),
success: function (data) {
console.log(JSON.parse(data));
}
});
});
</script>
Ask_model.php:
public function book_add($data)
{
$query=$this->db->insert('article', $data);
return $query;
}
Ask_controller.php:
public function book_add(){
$data = $_POST;
$details = array();
$details['title'] = $data['title'];
$details['content'] = $data['text'];
$details['snippet'] = $data['hidden_snippet'];
$details['createdDate']=date('Y-m-d H:i:s');
$result=$this->ask_model->book_add($details);
echo json_encode($details);
}
The content with html tags should be save in a column named content in the database, but it didn't save in the first click. It only saves on the second one,but the other data are saved in the first like the title, etc. So I get 2 rows of data, one without the content and the other with one.
Database:

ajax form request from a while - confuse variable

I want to send a form with a button from a while, but I have a problem. If post the button, the form confuse the variable. E.g: i post the button with id 1, and the script get the variable from the last input.
Code:
index:
<?php
$res = getProdus();
foreach($res as $row) { ?>
<form action="addtocart.php" method="POST">
<div class="col-12 col-sm-6 col-md-4 single_gallery_item women wow fadeInUpBig" data-wow-delay="0.2s">
<div class="product-img">
<img src="img/product-img/product-1.jpg" alt="">
<div class="product-quicview">
<i class="ti-plus"></i>
</div>
</div>
<div class="product-description">
<h4 class="product-price">$39.90</h4>
<p>Jeans midi cocktail dress</p>
<input type="hidden" name="addtcart" value="<?=$row['ID'];?>">
<button type="submit" class="add-to-cart-btn">ADD TO CART</button>
</div>
</div>
</form>
<?php } ?>
the ajax request:
$(document).ready(function() {
$('form').submit(function(event) {
var formData = {
'addtcart' : $('input[name=addtcart]').val()
};
$.ajax({
type : 'POST',
url : 'addtocart.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
and the addtocart.php
<?php
include("includes/functions.php");
session_start();
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
if (empty($_POST['addtcart']))
$errors['addtcart'] = 'Este necesar produsul id-ului.';
if ( ! empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$ok = AddToCart(filtrare($_POST['addtcart']), getSpec("username", "users", "email", $_SESSION['magazin-user']));
if($ok == 1) {
$data['success'] = true;
$data['message'] = 'Success!';
} else {
$data['success'] = false;
$errors['mysqli'] = "Nu s-a realizat bine query-ul.";
$data['errors'] = $errors;
}
}
echo json_encode($data);
?>
Replace your button code with this
<button type="submit" value="<?=$row['ID'];?>" class="add-to-cart-btn">ADD TO CART</button>
and after that replace you
make changes to your script code
$(".add-to-cart-btn").click(function() {
var formData = {
'addtcart' : $(this).val()
};
.
.
.
and your rest of the code.

HTML 5 Upload files using drag and drop

I would like to upload files using a drag and drop
I'm using laravel framework 5.4 and JS. The problem is with what happens after the upload is complete. I can see the file is uploaded to the folder but can't get the name of the file or any reference to it.
This is my view.. I'm uploading files to send as email attachments
{!! Form::open([
'url' => 'send',
'files' => true,
'id'=>'upload',
'enctype'=> 'multipart/form-data'
]) !!}
<div class="box-body">
<div class="form-group">
{!! Form::text('to', null, ['class' => 'form-control', 'placeholder' => 'Send to']) !!}
</div>
<div class="form-group">
{!! Form::text('subject', null, ['class' => 'form-control', 'placeholder' => 'Subject']) !!}
</div>
<div class="form-group">
{!! Form::textarea('content', null, ['class' => 'form-control message-body wysihtml5-sandbox', 'placeholder' => 'Message']) !!}
</div>
<div class="form-group">
<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="320000" />
<div>
<label for="fileselect">Files to upload:</label>
<input type="file" id="fileselect" name="fileselect[]" multiple="multiple" />
<div id="filedrag">or drop files here</div>
</div>
<div id="progress"></div>
<div id="messages">
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<div class="pull-right">
{{--<button class="btn btn-default"><i class="fa fa-pencil"></i> Draft</button>--}}
{!! Form::submit('Send', ['class' => 'btn btn-primary submit']) !!}
</div>
<div class="form-group">
<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="320000" />
<div>
<label for="fileselect">Files to upload:</label>
<input type="file" id="fileselect" name="fileselect[]" multiple="multiple" />
<div id="filedrag">or drop files here</div>
</div>
<div id="progress"></div>
<div id="messages">
</div>
</div><!-- /.box-body -->
<div class="box-footer">
{!! Form::submit('Send', ['class' => 'btn btn-primary submit']) !!}
The scripts I'm using
(function() {
var send = XMLHttpRequest.prototype.send,
token = $('meta[name=csrf-token]').attr('content');
XMLHttpRequest.prototype.send = function(data) {
this.setRequestHeader('X-CSRF-Token', token);
return send.apply(this, arguments);
}
// getElementById
function $id(id) {
return document.getElementById(id);
}
// output information
function Output(msg) {
var m = $id("messages");
m.innerHTML = msg + m.innerHTML;
}
// file drag hover
function FileDragHover(e) {
e.stopPropagation();
e.preventDefault();
e.target.className = (e.type == "dragover" ? "hover" : "");
}
// file selection
function FileSelectHandler(e) {
// cancel event and hover styling
FileDragHover(e);
// fetch FileList object
var files = e.target.files || e.dataTransfer.files;
// process all File objects
for (var i = 0, f; f = files[i]; i++) {
UploadFile(f);
}
}
function UploadFile(file) {
// following line is not necessary: prevents running on SitePoint servers
var xhr = new XMLHttpRequest();
if (xhr.upload && file.size <= $id("MAX_FILE_SIZE").value) {
// create progress bar
var o = $id("progress");
var progress = o.appendChild(document.createElement("p"));
progress.appendChild(document.createTextNode("upload " + file.name));
// progress bar
xhr.upload.addEventListener("progress", function (e) {
var pc = parseInt(100 - (e.loaded / e.total * 100));
progress.style.backgroundPosition = pc + "% 0";
}, false);
// file received/failed
xhr.onreadystatechange = function (e) {
if (xhr.readyState == 4) {
progress.className = (xhr.status == 200 ? "success" : "failure");
}
};
// start upload
xhr.open("POST", '/getAttachments', true);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.send(file);
}
}
// initialize
function Init() {
var fileselect = $id("fileselect"),
filedrag = $id("filedrag"),
submitbutton = $id("submitbutton");
// file select
fileselect.addEventListener("change", FileSelectHandler, false);
// is XHR2 available?
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// file drop
filedrag.addEventListener("dragover", FileDragHover, false);
filedrag.addEventListener("dragleave", FileDragHover, false);
filedrag.addEventListener("drop", FileSelectHandler, false);
filedrag.style.display = "block";
}
}
// call initialization file
if (window.File && window.FileList && window.FileReader) {
Init();
}
})();
The script I used was using the form action attribute to upload the files. Since the form action is to send the email, I routed xhr.open("POST", '/getAttachments', true) to a different controller method that I call in the send method.
My controller methods #getAttachments and #send
public function getAttachments()
if ($fn) {
// AJAX call
file_put_contents(
'uploads/' . $fn,
file_get_contents('php://input')
);
return $fn ; // HERE $fn = false though the name of the file stored is correct
}}
and I tried
Storage::put($fn, file_get_contents('php://input'));
$file = Storage::get($fn) ; return $file;);
public function send( Request $request ) {
$file = $this->getAttachments();
// $file = $false}
I figured it is returning false because if I hit send the page refreshes
and $_SERVER['HTTP_X_FILENAME'] variable is lost, so I tried saving it to the session but no use.. Can't get the files
public function getAttachments()
{
$fn = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);
if ($fn) {
session(['attachments' => $fn]);
Storage::put($fn, file_get_contents('php://input'));
}
}
public function send( Request $request ) {
//Grab uploaded file
if ($request->session()->exists('attachments')) {
$attachments = $request->session()->pull('attachments');
$files = Storage::get($attachments);
}
Don't know why but it doesn't store to the session either.
Not sure what exactly you are trying to do. But if you to want to upload a file by drag and drop then I would suggest you use this awesome js:
http://www.dropzonejs.com/
If you would like to see the implementation, then you can check it over here:
https://github.com/xparthx/Laravel-AWS-S3

Am trying to upload image using ajax php and jquery what am i doing wrong here

$(document).ready(function(){
$("#log").click(function(){
var name = $("#name").val();
var email = $("#email").val();
var img = $("#img").val();
$.ajax({
url:"ajax.php",
type:"POST",
async:false,
data:{
"postD" :1,
"nameD" : name,
"emailD" : email,
"imgD" : img
},
success:function(data){
$("#name").val('');
$("#email").val('');
$("#img").val('');
}
});
});
});
function displaydata(){
$.ajax({
url:"ajax.php",
type:"POST",
async:false,
data:{
"displayP":1
},
success:function(data){
$("#datafromDb").html(data);
}
});
}
<?php
include("db.php");
$sql = "
CREATE TABLE IF NOT EXISTS temptable (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
email VARCHAR(20) NOT NULL,
PRIMARY KEY(id)
);
";
mysqli_query($connect, $sql);
if (isset($_POST['postD'])){
if(!empty($_POST['nameD']) && !empty($_POST['emailD'])&& !empty($_FILES['imgD'])) {
$emailP = $_POST['emailD'];
$nameP = $_POST['nameD'];
$imgP = $_FILES['imgD']['name'];
$tmpname = $_FILES['imgD']['tmp_name'];
$folder = "upload/";
move_uploaded_file($tmpname, $folder.$imgP);
$insert = "INSERT INTO `inserteddata` (`name`, `email`,`img`)
VALUES('{$nameP}','{$emailP}','{$imgP}')";
$qry = mysqli_query($connect, $insert);
if($qry) {
echo "inserted";
}
}else {
echo "make sure all fields are filled";
}
}
if(isset($_POST['displayP'])){
$sel = "SELECT * FROM `inserteddata`";
$res = mysqli_query($connect, $sel);
while($row=mysqli_fetch_array($res)) {
echo "Name = ".$row['name']."<br><br><br>";
}
}
?>
<?php
$connect = mysqli_connect("localhost", "root", "", "ajaxinsert");
if(!$connect) {
echo "database connection error".mysqli_error();
}else {
echo "connected successfuly<br><br><br>";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>ajax insert</title>
<script type="text/javascript" src="jquery-3.2.1.js"></script>
<script type="text/javascript" src="ajax.js"></script>
</head>
<body>
<div id="datafromDb">
<script type="text/javascript">
document.write(displaydata());
</script>
</div>
<br>
<br>
<form enctype="multipart/form-data" action="" method="post">
<input type="text" id="name"><br><br>
<input type="email" id="email"><br><br>
<input type="file" id="img" name="img"><br><br>
<input type="submit" value="Login" >
<a href="" id="log" >add</a>
</body>
</html>
Am trying to upload image using ajax php and jquery what am i doing wrong here. the image should be uploaded without refreshing the page. i have tried the above code. if your see any prolem, help!!
The thing is i want to move the uploaded file to the upload folder and insert the image name to the database as a BLOB.
You can use FormData objects but you need to write the code in plain Javascript because I think JQuery doesn't support it yet. Please read this for more information https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

How to Save File with time as name and return time value with uploadify

what i intend to do, is to use uploadify to upload a file, change its name in uploadify.php for the value of time() ,save it , and return the name of the saved file back to the HTML, im not sure how to do it, currently im using this as guide
http://www.uploadify.com/documentation/uploadify/customizing-the-server-side-upload-script/
and this is my code so far
index.php
'<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"
type="text/javascript"></script>
<script src="jquery.uploadify.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="uploadify.css">
<style type="text/css">
body {
font: 13px Arial, Helvetica, Sans-serif;
}
</style>
</head>
<body>
<form>
<div id="queue"></div>
<input id="file_upload" name="file_upload" type="file" multiple="true">
</form>
<script type="text/javascript">
<?php $timestamp = time();?>
$(function() {
$('#file_upload').uploadify({
'formData' : {
'timestamp' : '<?php echo $timestamp;?>',
'token' : '<?php echo md5('unique_salt' . $timestamp);?>',
'name' : 'somename'
},
'method' : 'post',
'swf' : 'uploadify.swf',
'uploader' : 'uploadify.php',
onUploadComplete : function(data, file , response){
alert('The file was saved to: ' + data);
alert(response);
}
});
});
$(document).ready(function() {
$("#FormSubmit").click(function (e) {
var img = 'localhost/uploads/'+ $("#hidden").val;
var cuenta_sap = $("#cuenta_sap").val();
var ubicacion = $("#ubicacion").val();
var codigo_centro_beneficio = $("#codigo_centro_beneficio").val();
var nombre = $("#nombre").val();
var proyecto = $ ("#proyecto").val();
var departamento = $ ("#departamento").val();
var tipo_activo = $("#tipo_activo").val();
var proveedor = $("#proveedor").val();
var modelo = $("#modelo").val();
var numero_serie = $("#numero_serie").val();
var marca = $ ("#marca").val();
var numero_remision = $("#numero_remision").val();
var myData ='cuenta_sap='+ cuenta_sap + '&ubicacion='+ ubicacion +
'&codigo_centro_beneficio='+ codigo_centro_beneficio + '&nombre=' + nombre + '&proyecto='
+ proyecto + '&departamento='+ departamento + '&tipo_activo=' + tipo_activo
+'&proveedor='+ proveedor +'&modelo=' + modelo + '&numero_serie=' + numero_serie +'&marca='
+ marca + '&numero_remision='+ numero_remision;
e.preventDefault();
if(cuenta_sap==''||ubicacion==''||codigo_centro_beneficio==''
||nombre==''||proyecto==''||departamento
==''||tipo_activo==''||proveedor==''||modelo==''
||numero_serie==''||marca==''||numero_remision=='')
{
alert("Formato incompleto!");
return false;
}
$("#FormSubmit").hide(); //hide submit button
$("#LoadingImage").show(); //show loading image
$.ajax({
type: "POST", // HTTP method POST or GET
url: "response.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //
success:function(result){
$("#responds").delay(10000).fadeIn();
$("#responds").append("<li class='res'>"+result+"</li>");
$('.res').remove();
$("#proyecto").val(''); //empty text field on successful
$("#departamento").val(''); //empty text field on successful
$("#tipo_activo").val(''); //empty text field on successful
$("#modelo").val(''); //empty text field on successful
$("#numero_serie").val(''); //empty text field on successful
$("#marca").val(''); //empty text field on successful
$("#numero_remision").val(''); //empty text field on successful
$("#cuenta_sap").val(''); //empty text field on successful
$("#ubicacion").val(''); //empty text field on successful
$("#nombre").val(''); //empty text field on successful
$("#codigo_centro_beneficio").val(''); //empty text field on successful
$("#FormSubmit").show(); //show submit button
$("#LoadingImage").hide(); //hide loading image
},
error:function (xhr, ajaxOptions, thrownError){
$("#FormSubmit").show(); //show submit button
$("#LoadingImage").hide(); //hide loading image
alert(thrownError);
}
});
});
$("body").on("click", "#responds .del_button", function(e) {
e.preventDefault();
var clickedID = this.id.split('-'); //Split ID string (Split works as PHP explode)
var DbNumberID = clickedID[1]; //and get number from array
var myData = 'recordToDelete='+ DbNumberID; //build a post data structure
$('#item_'+DbNumberID).addClass( "sel" ); //change background of this element by adding class
$(this).hide(); //hide currently clicked delete button
$.ajax({
type: "POST", // HTTP method POST or GET
url: "response.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(response){
//on success, hide element user wants to delete.
$('#item_'+DbNumberID).fadeOut();
},
error:function (xhr, ajaxOptions, thrownError){
//On error, we alert user
alert(thrownError);
}
});
});
});
</script>
<div class="content_wrapper" id="wrapepr">
<div class="form_style">
<input name="hidden" id="hidden" type="text"></input>
<br>
<a>Datos</a>
<br>
<input name="cuenta_sap" id="cuenta_sap" placeholder="cuenta sap" class="input"></input>
<select name="departamento" class="input" id="departamento">
<option value = "">seleccione departamento</option>
<?php
include("db.php");
$stmt = $db->prepare("SELECT `id`, `departamento` FROM `departamentos`");
$stmt->execute();
$stmt->bind_result($id,$departamento);
while ($stmt->fetch()){
echo "<option value='$id'>$departamento</option>";
}
?>
</select>
<select name="proyecto" class="input" id="proyecto" >
<option value = "" >seleccione proyecto</option>
<?php
$stmt = $db->prepare("SELECT `id` ,`proyecto` FROM `proyectos`");
$stmt->execute();
$stmt->bind_result($id,$proyecto);
while ($stmt->fetch()){
echo "<option value='$id'>$proyecto</option>";
}
?>
</select>
<select name="tipo" class="input" id="tipo_activo">
<option value = "" class="input" >tipo de activo</option>
<?php
$stmt = $db->prepare("SELECT `id` ,`tipo` FROM `tipo_activo`");
$stmt->execute();
$stmt->bind_result($id,$tipo_activo);
while ($stmt->fetch()){
echo "<option value='$id' class='input'>$tipo_activo</option>";
}
?>
</select>
<select name="proveedor" class="input" id="proveedor">
<option value = "" class="input" >seleccione proveedor</option>
<?php
$stmt = $db->prepare("SELECT `id` ,`nombre` FROM `proveedores`");
$stmt->execute();
$stmt->bind_result($id,$nombre);
while ($stmt->fetch()){
echo "<option value='$id' class='input'>$nombre</option>";
}
?>
</select>
<input name="codigo_centro_beneficio" id="codigo_centro_beneficio" placeholder="codigo centro
beneficio" class="input"></input>
<input name="nombre" id="nombre" placeholder="nombre" class="input"></input>
<input name="modelo" id="modelo" placeholder="modelo" class="input"></input>
<input name="numero_serie" id="numero_serie" placeholder="numero_serie" class="input">
</input>
<input name="marca" id="marca" placeholder="marca" class="input"></input>
<input name="numero_remision" id="numero_remision" placeholder="numero remision" class="input">
</input>
<input name="upload" id="upload" class="input" type="file"></input>
<button id="FormSubmit">registrar</button>
<img src="images/loading.gif" id="LoadingImage" style="display:none" />
</div>
<ul id="responds" >
</ul>
</div>
</body>
</html>'
and uploadify.php
'
$targetFolder = '/uploads'; // Relative to the root
$verifyToken = md5('unique_salt' . $_POST['timestamp']);
if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
$now = time();
$name = $_POST('name')FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
$targetFile = rtrim($targetPath,'/') . '/' . $now .'.'. $fileParts['extension'];
echo rtrim($targetPath,'/') . '/' . $now .'.'. $fileParts['extension'];
if(file_exists($targetFile)){
++$now;
$targetFile = rtrim($targetPath,'/') . '/' . $now .'.'. $fileParts['extension'];
$name $targetPath,'/') . '/' . $now .'.'. $fileParts['extension'];
echo $name;
}
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
}
else {
echo 'Invalid file type.';
}
?>'
I found the answer to this, after a while of searching and reading uploadify manuals, it turns out if you use onUploadComplete, and you just upload one single fine, the method will never excecute, and it will keep waiting for more files, instead for one file only, you have to use onUploadSuccess, and read the data returned by it using file,data,response as parameters.

Resources