how to process an upload file in mootools? - php

I already search about this and I cannot use ajax in file uploading, but all I need to do is process my file through an ajax then pass it to my controller (where I created and object file to save in a directory), so how can I process an upload file trough an ajax mootols, I already do it and nothings happens, no plugins please, I need just to someone guide me
this is my code
#f1_upload_process{
z-index:100;
position:absolute;
visibility:hidden;
text-align:center;
width:400px;
margin:0px;
padding:0px;
background-color:#fff;
border:1px solid #ccc;
}
</style>
<p id="f1_upload_process">Loading...<br/></p>
<p id="result"></p>
<form method="post" action="" enctype="multipart/form-data">
<label for="file">Subir un archivo</label>
<input type="file" name="file" id="fileArchivo" />
<input type="submit" name="submit" id="btnSubir" value="upload file" />
<iframe name="iframUpload" id="iframeUpload" type="file" style="display:none"></iframe>
</form>
mootools ajax
window.addEvent("domready",function(){
cargarIndex();
});
function cargarIndex()
{
var prueboRequest = new Request({
method: 'POST',
url: '../CONTROLLER/inicio.php',
onRequest: function() {},
onSuccess: function(texto, xmlrespuesta){
document.getElementById('subirarchivo').innerHTML= texto;
$('btnSubir').addEvent('click',function(){beginUploading()});
},
onFailure: function(){alert('Error!');}
}).send();
}
function beginUploading(){
var prueboRequest = new Request({
method: 'POST',
url: '../Controller/ControllerSubirArchivo.php',
onRequest: function() {},
onSuccess: function(texto, xmlrespuesta){
onFailure: function(){alert('Error!');}
}).send();
I already search but all I have found is this but with jquery, and I want something similar to:
$(function(){
var btnUpload=$('#upload');
var status=$('#status');
new AjaxUpload(btnUpload, {
action: 'upload-file.php',
//Name of the file input box
name: 'uploadfile',
onSubmit: function(file, ext){
if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
// check for valid file extension
status.text('Only JPG, PNG or GIF files are allowed');
return false;
}
status.text('Uploading...');
},
onComplete: function(file, response){
//On completion clear the status
status.text('');
//Add uploaded file to list
if(response==="success"){
$('<li></li>').appendTo('#files').html('<img src="./uploads/'+file+'" alt="" /><br />'+file).addClass('success');
} else{
$('<li></li>').appendTo('#files').text(file).addClass('error');
}
}
});
});
}

As Dimitar Christoff said, no way to have an ajax file upload without a little bit of cross browser headache for now…
I would recommend the plupload project so you're sure it's cross browser. A plugin from the forge could also do the trick but separating the javascript file upload library is a good idea these days. Considering that the implementation of the HTML5 API is still partial on a lot of browsers, you may have to update the script soon…

Related

HTML prevent from redirect upload php

I need to prevent the page redirected to the upload php when click upload button.
How can I do this in below code.
<form id="myForm" action="http://example/DB_1/AccessWeb/file_upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload1">
</form>
<button onclick="myFunction()"> Upload
</button>
<script>
function myFunction(){
document.getElementById("myForm").submit();
}
</script>
A very basic, quickly written example of how to send a file - using ajax to the same page so that the user doesn't get redirected. This is plain vanilla javascript rather than jQuery.
The callback function can do more than print the response - it could, for instance, be used to update the DOM with new content based upon the success/failure of the upload.
<?php
$field='fileToUpload';
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_FILES ) ){
$obj=(object)$_FILES[ $field ];
$name=$obj->name;
$tmp=$obj->tmp_name;
$size=$obj->size;
$error=$obj->error;
$type=$obj->type;
if( $error==UPLOAD_ERR_OK ){
/*
This is where you would process the uploaded file
with various tests to ensure the file is OK before
saving to disk.
What you send back to the user is up to you - it could
be json,text,html etc etc but here the ajax callback
function simply receives the name of the file chosen.
*/
echo $name;
} else {
echo "bad foo!";
}
exit();
}
?>
<!doctype html>
<html>
<head>
<title>File Upload - using ajax</title>
<script>
document.addEventListener('DOMContentLoaded',function(e){
var bttn=document.getElementById('bttn');
bttn.onclick=function(e){
/* Assign a new FormData object using the buttons parent ( the form ) as the argument */
var data=new FormData( e.target.parentNode );
var xhr=new XMLHttpRequest();
xhr.onload=function(e){
document.getElementById('status').innerHTML=this.response;
}
xhr.onerror=function(e){
alert(e);
}
xhr.open('POST',location.href,true);
xhr.send(data);
};
},false);
</script>
</head>
<body>
<form method='post' enctype='multipart/form-data'>
Select image to upload:
<input type='file' name='fileToUpload'>
<input type='button' id='bttn' value='Upload' />
</form><div id='status'></div>
</body>
</html>
Using JQuery AJAX methods will allow you to send and receive information to a specified url without the need to refresh your page.
You will need to include the JQuery library in your HTML page aswell. You can either download it and put it in your project folder or include an online library here, like so:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
So your form will now look like this:
<form id="myForm" method="post" >
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload1">
<input type="submit">
</form>
Then you can use this code to simply upload your image to your file upload page (tested and working for myself):
<script>
$(document).ready(function ()
{
$("#myForm").submit(function (e)
{
//Stops submit button from refreshing page.
e.preventDefault();
var form_data = new FormData(this);
$.ajax({
url: 'http://example/DB_1/AccessWeb/file_upload.php', //location of where you want to send image
dataType: 'json', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response)
{
alert('success');
},
error: function ()
{
alert('failure');
}
});
});
});
</script>
use AJAX With jQuery
$("#myForm").submit(function()
{
var formData = new FormData(this);
$.post($(this).attr("action"), formData, function(response) {
//Handle the response here
});
return false;
});

how so I respond to user while POST is processing?

I have a form that takes a json file and POSTs to a server side process. It's a lengthy process and I want to message it's progress back to the user in real time with multiple messages.
What are my options?
This process can take 10-15 minutes or higher. I am not looking for the answer "AJAX". there is more to it than that.
this is what I got for a form:
<form method="POST" accept-charset="UTF-8" class="smart-form" id="import-course" enctype="multipart/form-data">
<fieldset>
<div class="row">
<section class="col col-md-12">
<label class="input input-file">
<input class="button" name="import" type="file">
</label>
</section>
</div>
</fieldset>
<footer>
<button class="btn btn-primary" id="submit-import-file" type="button">Save</button>
<a onclick="history.back();" class="btn btn-default">Cancel</a>
</footer>
</form>
Here is my ajax:
$(document).ready(function(){
$("#submit-import-file").on('click',function(){
console.log('click');
$('#import-course').hide();
var formData = new FormData($('#import-course')[0]);
$.ajax({
url: '{{URL::route("courses.import")}}', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
success: function(data){
console.log(data);
},
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});
});
function progressHandlingFunction(e){
console.log(e);
}
and here is my server side pay attention to the comments.
$errors = 0;
$file = Input::file('import');
$fileName = $file->getClientOriginalName();
$destinationPath = app_path()."/storage/files/";
$file->move($destinationPath, $fileName);
$course = json_decode(File::get($destinationPath.$fileName));
if(!File::isDirectory($destinationPath.$course->code)){
File::makeDirectory($destinationPath.$course->code,0777,true,true);
//message back directory created
}
foreach($course->file as $file){
if(FileManger->processfile($file)){
//message back $file->name imported
}else{
//message back error importing $file->name
}
}
return "import complete";
So now.. How do i get the comment areas to be messaged back to the user while this processes. not after.
You should use Ajax to post the data to the php page without refreshing. The below code will display "Loading" until the ajax call is complete. You could use a gif or something instead. It's more difficult to do a progress bar / percentage complete but you could look at this answer as a reference. PHP Ajax Upload Progress Bar
$.ajax({
url: "domain.com/url",
type: "POST",
data: data,
cache: false,
beforeSend: function() {
$('#response').html("Loading");
},
success: function(data) {
$('#response').html(data);
}
}
You can still use a jquery progressbar. Write the progress of the processing out to the UI and calculate some form of percentage based on the progress through the processing. That of course assumes there is more than one step to the processing of course...! A progress bar that goes from 0 to 100% in one step isn't terribly useful.

Problem with moving file and saving file data blank

I have some problem here..
I use upload from on index.php and i use jquery (ajax) to save any information to mysql. I have 3 file index.php, savedata.php, jsSave.js
But when i use $_REQUEST file from savedata.php and result is blank response also in mysql table, i replace $_REQUEST and use $_FILES and have same result.
What i already try and use is code like below...
Index.php
<form class="myform" action="<?php $_SERVER['PHP_SELF'];?>" method="POST" name="myform" id="myform" enctype="multipart/form-data" style="width:350px;">
<li>
<label>Item Picture</label>
<div class="fileUpload btn btn-primary">
<span>Choose Image..</span>
<input type="file" name="cItemPicture" class="cItemPicture" id="cItemPicture"/>
</div>
<input type="hidden" name="cPic" id="cPic"/>
</li>
<li>
<img border="0" src="images/loading_transparent.gif" width="20" height="20" id="imgLoad">
&nbsp<button class="button_blue" id="butTblSave" type="submit" style="width: 81px; height: 33px">SAVE</button>
</li>
and for savedata.php file script is
<?php
if($_REQUEST)
{
***$cItemPicture=$_FILES["cItemPicture"]["name"];***
$sql="INSERT INTO tblData(item_image) VALUES ('$cItemPicture')";
$result=mysql_query($sql) or die('Cannot Connect To SQL Server, Please contact your administrator');
move_uploaded_file($_FILES["cItemPicture"]["tmp_name"],
"upload/" . $_FILES["cItemPicture"]["name"]);
}
?>
last file which work as AJAX using jQuery file is jsSave.js
$(document).ready(function() {
$('#imgLoad').hide();
$('#msgConfirm').hide();
$('#tblAvailabilityResult').hide();
});
$(function() {
$("#butTblSave").click(function() {
$.ajax({
type: 'POST',
url: 'saveData.php',
data: $('form').serialize(),
beforeSend: function() {
$("imgLoad").show();
},
complete: function() {
$("imgLoad").hide();
},
cache: false,
success: function () {
$("#cItemPicture").val('');
$('#imgLoad').hide();
$('#butTblSave').attr("disabled", false);
$('#msgConfirm').fadeIn(500).delay(5000).fadeOut(1000);
$("#msgConfirm").html(' Add New Item Success.');
}
});
return false;
}
});
});
Do i miss something? when press SAVE button ajax reponse blank and saved data into mysql item_image also blank, also and no file moved into upload folder.
Any idea for this problem? Many thanks about this.
Thank you
try preventing the default submission of the form.
Because the form is submitting to SELF (index.php)
$("#butTblSave").click(function(event) {
event.preventDefault();
...

jQuery and php file upload

I do not understand, and google does not give me the answer. I want to upload a file and the results show in the div without page relode, but I can not get it!!!!
html:
<form method="post" action="process/pic2.php" enctype="multipart/form-data" id="userpic">
<p>Izvēlies bildi: <input type="file" name="img_to_upload" /><input type="submit" name="upload" value="Augšupielādēt" /></p>
</form>
jquery:
jQuery(function(){
jQuery('#userpic').submit(function(){
jQuery.ajax({
type: 'POST',
enctype: 'multipart/form-data',
url: jQuery('#userpic').attr('action'),
data: jQuery('#userpic').serialize(),
success: function(data){
if(data){
jQuery('#picinfo').html(data);
}else{
jQuery('#uerpic').fadeOut(500);
jQuery('#picinfo').html('<center><img src="img/loader.gif" /></center>');
window.location = 'index.php';
}
}
});
return false;
});
});
and my php:
if(isset($_FILES['img_to_upload']['name']) && !empty($_FILES['img_to_upload']['name'])){
echo 'Done!';
}else{
echo 'Error!';
}
all the time showing the "error" text..
P.S. Sorry for bad English.
Normally, to do a form-submission, and stay on the same page, you'll have to prevent the default form action with Javascript, something like this:
$("#userpic").submit(function(event) {
event.preventDefault();
...
});
But, uploading an image via Ajax is pretty tricky--see:
uploading files with jquery $.ajax and php

why my ajax mootools method keeps showing me an Error alert?

I am trying to make a simple upload file system, and this is my code , I hope you can help me, help very appreciated
init.php
<form method="post" action="" enctype="multipart/form-data">
<label for="file">Upload a file</label>
<input type="file" name="file" id="fileArchivo" />
<input type="submit" name="submit" id="btnUpload" value="Upload file" />
</form>
Ajax mootools method
window.addEvent("domready",function(){
cargarIndex();
});
function loadIndex()
{
var Request = new Request({
method: 'POST',
url: '../CONTROLLER/init.php',
onRequest: function() {},
onSuccess: function(text, xmlrespuesta){
document.getElementById('archive').innerHTML= texto;
$('btnUpload').addEvent('click',function(){uploadFile()});
},
onFailure: function(){alert('Error!');}
}).send();
}
function uploadFile(){
//$('btnUpload').addEvent('click', function(){
alert('in');
archivo = $('fileArchivo').value;
alert(archivo);
var nuevoRequest = new Request({
method: 'POST',
data: 'archivo='+archivo,
url: '../CONTROLLER/controllerSave.php',
onRequest: function() {$('subirarchivo2').innerHTML="Cargando...";},
onSuccess: function(texto, xmlrespuesta) {$('subirarchivo2').set('html',texto);},
onFailure: function(){alert('Error!');}
}).send();
//});
}
Firebug says that uncaught exception:
[Exception... "prompt aborted by user" nsresult: "0x80040111
(NS_ERROR_NOT_AVAILABLE)" location: "JS frame ::
resource://gre/components/nsPrompter.js :: openTabPrompt :: line 468"
data: no]
But I dont get the answers, I already search but nothing, the Error alert is in the onFailure in the uploadFile.
can't use ajax like so to upload files.
http://mootools.net/forge/p/form_upload by core member Arian
http://mootools.net/forge/p/uploadmanager by Thiery Bela
Both provide sensible solutions via HTML5 interfaces with a flash uploader fallback / degradation for older browsers.

Categories