jQuery File Upload not Uploading - javascript

This PHP code works when I use HTML <input type="file">, but not when I use the jQuery file upload script at the very bottom.
I believe all .js & .css files are accounted for and working (tested)
I believe the uploadUrl: 'doc_upload.php', fileInputName: 'userfile' are correct. Don't know 'cause no errors are showing.
Using echo getcwd();, I believe I'm using correct paths
I'm only uploading a 1 kb .TXT file
I get no errors and all error reporting is on and maxed
One thing that is also not working, which I'm saying to possibly give a clue, is the upload & cancel buttons next to the file name are not showing all though clicking on them does seem to work.
Echo'ing $_POST shows me nothing on submit, but I think that's a javascript thing; not sure as I'm a beginner (3-months).
PHP page
$filename = $_FILES['userfile']['name'];
$tmpname = $_FILES['userfile']['tmpname'];
$filesize = $_FILES['userfile']['size'];
$filetype = $_FILES['userfile']['type'];
$fp = fopen($tmpname, 'r');
$content = fread($fp, filesize($tmpname));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc()) {
$filename = addslashes($filename);
}
$filename = preg_replace('/[ ]/', '~', $filename);
$document_folder = $_SESSION['users_id'];
$destfile = "../_documents/".$document_folder."/".$_FILES['userfile']['name'];
move_uploaded_file( $_FILES['userfile']['tmpname'], $destfile );
HTML page
<link type="text/css" rel="Stylesheet" href="../jqx.base.css" />
<script type="text/javascript" src="../scripts/js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="../scripts/jqwidgets/jqxcore.js"></script>
<script type="text/javascript" src="../scripts/jqwidgets/jqxbuttons.js"></script>
<script type="text/javascript" src="../scripts/jqwidgets/jqxfileupload.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#jqxFileUpload').jqxFileUpload({ width: 300, uploadUrl: 'doc_upload_jquery.php', fileInputName: 'userfile', autoUpload: true });
});
$('#jqxFileUpload').on('uploadStart', function (event) {
var fileName = event.args.file;
$('#log').prepend('Started uploading: <strong>' + fileName + '</strong><br />');
});
$('#jqxFileUpload').on('remove', function (event) {
var fileName = event.args.file;
$('#log').prepend('Removed file: <strong>' + fileName + '</strong><br />');
});
$('#jqxFileUpload').on('uploadEnd', function (event) {
var args = event.args;
var fileName = args.file;
var serverResponce = args.response;
});
</script>
</head>
<body>
<div id="jqxFileUpload">
</div>
<div id="log" style="margin-top: 20px;"></div>
<br />
</body>
</html>

mdpalow -
You probably aren't getting any errors or output because of the if statement at the top:
if (isset($_POST['submit']) && $_FILES['userfile']) {
Try putting this at the top to output all of your post variables so that you can determine what post variables are actually being sent (if any):
print_r($_POST);
I have done file uploads before but not with this specific library - my guess is that its just sending mulipart data instead of POST variables. Looking at the preview headers in the browser developer tools will also shed light as to what data is being sent.

The problem is that jQuery plugin uploads file via AJAX. In order to fix the issue please follow next steps:
Keep your HTML and PHP code in separate files.
In new PHP file remove isset($_POST['submit']) validation as there is no submission.

Related

PHP GET variable not working when page name changed with .htdacess

I just want to pass variable with JavaScript to another new PHP page. My php page name are changed through .htdaccess and are not ending with .php example [http://localhost/ahlain_new/budget_by_mi?&b_year=2022].
I have tried to search with google but unfortunate get answer
I am getting error while sending variable to new page "Notice: Undefined index: b_year in C:\xampp\htdocs\ahlain_new\views\modules\budget_by_mi.php on line 37"
My code is
.htdaccess
RewriteRule ^([\w-]+([^/]))$ index.php?rute=$1
php when any page is clicked
if (isset($_GET["rute"])) {
if (
$_GET["rute"] == "budget_by_mi"
}
include "modules/".$_GET["rute"].".php";
}else {
include "modules/404.php";
}
JavaScript to send variable
$('body').on('click','#by_mi',function openWin(){
var b_year = document.getElementById('budget_year').value;
var url = "/ahlain_new/budget_by_mi?&b_year=" + b_year;
myWindow = window.open(url);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<button class="btn btn-outline-secondary" id="by_mi" type="button" style="height: 28px">Budget BY MI CAT</button>
<!-- -------NEW Page ----- ?>
<?php
$b_year = $_GET['b_year'];
echo $b_year;
?>
Thank you in advance for your support

How to read all text files in a folder and filter display based on the suffix or prefix

I'm trying to use jQuery to read all text files in a folder and display their contents, but then, filter which should ones should be displayed based on the name of the folder.
Here's the JavaScript:
var obj = {
"01600610/9874565214_789545621.txt": "",
"01600610/9874565214_789545622.txt": "",
"01600610/9874565214_789545623.txt": ""
};
$.each( obj, function(SavedText) {
$.get(SavedText, function(data){
$('#NewMessagesHolder').prepend('<div class="MessageClass">'+ '<span class="ChatName">' + CookieName + ' ('+ time + ')</span>' + ': '+ data +'</div>')
}, 'text');
});
On this:
var obj = {
"01600610/9874565214_789545621.txt": "",
"01600610/9874565214_789545622.txt":"",
"01600610/9874565214_789545623.txt":""
};
Q1: How do I get all text files inside a folder instead of specifying the file I want?
Q2: How can I filter? For example, how can I only get files ending or starting with 789545.
When these files are on your local filesystem, you can use the HTML5 Filesystem API.
If the files are located on a server, there is no way listing them from plain (client-side) javascript (maybe except a brute-force method, which shouldn't be considered of course). Then you have to write a server script (in PHP/Node/Perl/Phython/...) which will respond to a ajax request with a file list.
If you are using a server script, you should do the filtering on the server (so the answer depends on the language).
Otherwise you should use Regular Expressions:
var search = new RegExp("789545");
for(var file in obj) {
if(search.test(file))
alert(file+": "+obj[file]);
}
This would search for files with a name containing the pattern 789545
Please create index.php file and add this content to it. Create there a folder called "files" and add your files there
<?php
function contains($haystack, $needle){
if (strpos($haystack,$needle) !== false) {
return true;
}
return false;
}
if(isset($_POST['get_files'])){
$folder = "";
$filter = "";
if(isset($_POST['folder'])){
$folder = $_POST['folder'];
}
if(isset($_POST['filter'])){
$filter = $_POST['filter'];
}
$files = array();
foreach(glob($folder.'/*.*') as $filename){
if($filter != ""){
if(contains($filename, $filter)){
$files[] = $filename;
}
}else{
$files[] = $filename;
}
}
print_r($files);
exit;
}
?>
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function getData(){
jQuery.post('index.php',{
get_files:true,
folder:"files",
filter:""
},function(data){
jQuery('#container').html(data);
});
}
</script>
</head>
<body>
<input type="button" value="Get data" onclick="getData();" />
<div id="container"></div>
</body>
</html>
You can specify different folder, and filename filter in jQuery post request call
U can use regular expressions to filter the filenames. And for getting all files in a folder, U want to run a server side script. I use perl or php, to do this kinda stuff. U can use ajax to post the request and make the server script to return the file contents.
http://perlmeme.org/faqs/file_io/directory_listing.html
This link is just an example to do what u need in perl. And u could possibly do the same with other languages too

file_get_contents error whilst using aviary

I have embedded aviary into my webpage and it is working fine but I am unable to use the file_get_contents command to grab the saved image.
the aviary code:
JS:
<!-- Load Feather code -->
<script type="text/javascript" src="http://feather.aviary.com/js/feather.js"></script>
<!-- Instantiate Feather -->
<script type='text/javascript'>
var featherEditor = new Aviary.Feather({
apiKey: '*********',
apiVersion: 3,
theme: 'light', // Check out our new 'light' and 'dark' themes!
tools: 'crop,orientation,brightness,sharpness,redeye,effects,stickers,focus,contrast,whiten,warmth,colorsplash,enhance,saturation,blemish,draw,text,frames',
appendTo: '',
onSave: function(imageID, newURL) {
var img = document.getElementById(imageID);
img.src = newURL;
},
onError: function(errorObj) {
alert(errorObj.message);
},
postUrl: 'http://example.com/featherposturl'
});
function launchEditor(id, src) {
featherEditor.launch({
image: id,
url: src
});
return false;
}
HTML:
<div id='injection_site'></div>
<img id='image1' src='photo.jpg' style="max-height:360px;" on/>
<p><input type='image' src='http://images.aviary.com/images/edit-photo.png' value='Edit photo' onclick="return launchEditor('image1', document.getElementById('image1').src);"/></p>
According to the aviary documentation I can grab the temp file that has been created on the aviary server but using this php code:
<?php
$image_data = file_get_contents($_REQUEST['url']);
file_put_contents("photo.jpg",$image_data);
?>
When I run this it errors out with this error
[24-Sep-2013 12:14:16 UTC] PHP Warning: file_get_contents() [function.file-get-contents]: Filename cannot be empty in......
Does anyone have any experience as to how I can grab the file that has been created on the aviary server and upload a copy to my server.
UPDATE
I notice a file called 'photo.jpg' is added to the server with a filesize of 0kb. I am assuming that this is from the file_put_contents("photo.jpg",$image_data); but the image data is blank as this is the error if the file_get_contents
Any ideas?
Please check that on your sever allow_url_fopen = 0
if it's value is 1 file_get_contents can't work
it that case you can use curl
Aviary posts back to a URL of your choice with a link to the file saved on their servers. So, you need to add a route on your server with the server-side code snippet above and make sure the postUrl you specify is the URL on your server that will call this code.
I had the same problem, this answer is probably a little late now, but I got around it this way. Its not the best way but it does work
In your javascript change this:
onSave: function(imageID, newURL) {
var img = document.getElementById(imageID);
img.src = newURL;
},
to This:
onSave: function(imageID, newURL) {
var img = document.getElementById(imageID);
img.src = newURL;
var old_image = $('#oldimage').val(); //this is a hidden field with the HTML LINK for the original image on your server
$.ajax({
url : 'PHP Processing page',
type : 'POST',
dataType : 'JSON',
data : {oldimage : old_image, newimage : img.src},
success : function (json) {
console.log(json);
}
});
}
HTML:
<input id="oldimage" type="hidden" value="ORIGINAL IMAGE" />
<button class="button special fit" onclick="return launchEditor('image1', 'ORIGINAL IMAGE');">Edit This Image</button>
In the PHP processing page:
$default = getenv("DOCUMENT_ROOT");
define("SITEROOT",$default."/yoursite/");
define("SITEHTMLROOT", "http//www.yoursite.com/");
$oldimage = str_replace(SITEHTMLROOT, SITEROOT, $_POST['oldimage']);
$newimage = $_POST['newimage'];
copy($newimage, $oldimage);
As long as allow_url_fopen is set to on/1 this will work
You don't need to add the
postUrl: 'http://example.com/featherposturl'
line to do it this way
As this post is very old, if you did find a good way of doing this would you share it?

CodeIgniter AJAX File Upload is not working

I have written a mechanism to upload a file using AJAX technology (pure javascript) in CodeIgniter.
Explanation:
1- I have written a script.js file which is responsible to handle AJAX/Javascript process of the upload.
2- I have written a controller in CodeIgniter which receives request from AJAX to upload the file.
3- I have written a simple HTML page
PROBLEM: When I hit the upload button, simply nothing happens! No error is shown. I think there is a problem with the transfer of data between javascript and php. Because I have used an almost similar code in regular php page and has been successful.
Here are files:
This is JAVASCRIPT
// JavaScript Document
var doUpload = function(event){
// globally used variables in this function
var progressBar = document.getElementById('progressBar');
event.preventDefault(); // prevents the default action of an element
event.stopPropagation();
// get the file-input id
var fileId = document.getElementById('file');
// this variable makes an object which accept key/value pairs which could be sent via ajax.send
var formObj = new FormData();
// append currently selected file to the dataObject
formObj.append('file', fileId.files[0]);
// this is a variable to check in the php script (controller if the codeIgniter is used)
formObj.append('error-check', true);
formObj.append('finish-check', true);
// let's make the ajax request object
var ajaxReq = new XMLHttpRequest();
// PROGRESS OF THE FILE /////////////////////////////////////////////
// now trigger a function during the progress-process of the file-upload process
ajaxReq.upload.addEventListener('progress', function(event){
console.log('this is a very good.');
// first let's get the amount of the file loaded. it is in decimals
var percent = event.loaded / event.total;
// get the name of the element that the progress-indicator is outputted there
if(event.lengthComputable) // if a file is inserted and everything is just OK for uploading
{
if(progressBar.hasChildNodes()) // cleans the div container for a new progress to display
{
progressBar.removeChild(progressBar.firsChild);
}
progressBar.appendChild(document.createTextNode('The Progress So Far: '+percent*100+' %'));
}
// END OF PROGRESS OF THE FILE /////////////////////////////////////////////
// LOAD OF THE FILE /////////////////////////////////////////////
ajaxReq.upload.addEventListener('load', function(event){
progressBar.appendChild(document.createTextNode(" Completed!"));
});
// END OF LOAD OF THE FILE /////////////////////////////////////////////
// ERROR OF THE FILE /////////////////////////////////////////////
ajaxReq.upload.addEventListener('error', function(event){
progressBar.removeChild();
progressBar.appendChild(document.createTextNode("Failed to Upload the File."));
});
// END OF THE ERROR OF THE FILE /////////////////////////////////////////////
// JSON
// OPEN THE AJAX REQUEST
ajaxReq.open('POST', 'upload/uploader');
// Set the header of the POST request
ajaxReq.setRequestHeader('Cache-Control', 'no-cache');
// send the file. remember, we shoud pass a formData object as an argument to the ajaxRequest.send();
ajaxReq.send(formObj);
});
}
window.addEventListener('load', function(event)
{
// get the submit id of the form
var submitButton = document.getElementById('submit');
submitButton.addEventListener('click', doUpload);
});
This is PHP Controller in CodeIgniter
<?php
class Upload extends CI_Controller
{
function index()
{
$this->load->view('pages/form');
}
function uploader ()
{
// define the required settings for the upload library to instanciate
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|doc|txt';
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = TRUE;
// load the upload library
$this->load->library('upload', $config);
if(!$this->upload->do_upload('file'))
{
$data['error'] = $this->upload->display_errors();
//$this->load->view('pages/form', $data);
json_encode($data['error']);
}
else
{
$data['uploaded'] = $this->upload->data();
//$this->load->view('pages/form', $data);
}
}
}
This is the HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Upload Form With Ajax</title>
<script src="<?php echo base_url(); ?>js/script.js" type='text/javascript'></script>
</head>
<body>
<div id='error' style='color: red;height: 40px; width: 200px;'>
<?php
if(!empty($error)){echo $error; }
?>
</div>
<form id='form' name='form' enctype="multipart/form-data" >
<input type='file' name='file' id='file'/>
<input type='submit' name='submit' id='submit' value='Upload File' />
</form>
<div style='height: 200px; width: 300px; color: red; padding: 10px; background-color: #CCC;' id='progressBar'></div>
</body>
</html>
In script.js move:
// OPEN THE AJAX REQUEST
ajaxReq.open('POST', 'upload/uploader');
// Set the header of the POST request
ajaxReq.setRequestHeader('Cache-Control', 'no-cache')
// send the file. remember, we shoud pass a formData object as an argument to the xhruest.send();
ajaxReq.send(formObj);
outwith the progress event listener:
ajaxReq.upload.addEventListener('progress', function(event)
{
console.log('this is a very good.');
// first let's get the amount of the file loaded. it is in decimals
var percent = event.loaded / event.total;
// get the name of the element that the progress-indicator is outputted there
if(event.lengthComputable) // if a file is inserted and everything is just OK for uploading
{
if(progressBar.hasChildNodes()) // cleans the div container for a new progress to display
{
progressBar.removeChild(progressBar.firsChild);
}
progressBar.appendChild(document.createTextNode('The Progress So Far: '+percent*100+' %'));
}
// END OF PROGRESS OF THE FILE /////////////////////////////////////////////
// LOAD OF THE FILE /////////////////////////////////////////////
ajaxReq.upload.addEventListener('load', function(event)
{
progressBar.appendChild(document.createTextNode(" Completed!"));
});
// END OF LOAD OF THE FILE /////////////////////////////////////////////
// ERROR OF THE FILE /////////////////////////////////////////////
ajaxReq.upload.addEventListener('error', function(event)
{
progressBar.removeChild();
progressBar.appendChild(document.createTextNode("Failed to Upload the File."));
});
// END OF THE ERROR OF THE FILE /////////////////////////////////////////////
// JSON
});
// OPEN THE AJAX REQUEST
ajaxReq.open('POST', 'upload/uploader');
// Set the header of the POST request
ajaxReq.setRequestHeader('Cache-Control', 'no-cache')
// send the file. remember, we shoud pass a formData object as an argument to the ajaxRequest.send();
ajaxReq.send(formObj);
There was another problem in my code the prevented the execution: I used:
ajaxReq.upload.addEventListener`
I had to omit the upload:
ajaxReq.addEventListener

Uploadify - onComplete || onAllComplete not work

I know there are already some threads with this question, but none was helpful to me.
I have an image manager and I would like to reload the page with "onComplete" event, but it not work for me.
you can see an example: http://graficnova.com/uploadifytest/imgLoader.php
Everything works successful!!, but u need press f5 key for refresh it :(.
Thx and sorry for my english!
code:
head:
<script type="text/javascript">
$(function() {
$("#fileInput").uploadify({
width : 100,
swf : 'swf/uploadify.swf',
uploader : 'php/uploadify.php',
queueID : 'imgloadList',
oncomplete : function() {
alert('hello world?'); //<- THIS NOT WORK
}
});
});
</script>
php: uploadify.php
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
//$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$targetPath = 'xxxxx/xxxx/xxxx/xxxx';
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
echo '1'; //<- return response
} else {
echo 'Invalid file type.'; //<- return response
}
}
Based on the Uploadify docs, there isn't an onComplete event, but there is an 'onUploadComplete' event:
Triggered once for each file when uploading is completed whether it was successful or returned an error. If you want to know if the upload was successful or not, it’s better to use the onUploadSuccess event or onUploadError event.
Might want to give that a try. Or check out onQueueComplete.

Categories