Refreshing the page after completing uploads in jQuery Multi file Uploader - php

I'm using jQuery Multifile uploader (https://github.com/blueimp/jQuery-File-Upload) with PHP
and I want to refresh the uploads page once all files got uploaded, I'm using basic plus UI, please tell me if is there any easy way to achieve it

Use the done and fail events along with some counters. Found these events in the options documentation.
var fileCount = 0, fails = 0, successes = 0;
$('#fileupload').fileupload({
url: 'server/php/'
}).bind('fileuploaddone', function(e, data) {
fileCount++;
successes++;
console.log('fileuploaddone');
if (fileCount === data.getNumberOfFiles()) {
console.log('all done, successes: ' + successes + ', fails: ' + fails);
// refresh page
location.reload();
}
}).bind('fileuploadfail', function(e, data) {
fileCount++;
fails++;
console.log('fileuploadfail');
if (fileCount === data.getNumberOfFiles()) {
console.log('all done, successes: ' + successes + ', fails: ' + fails);
// refresh page
location.reload();
}
});

You can use the stop event. It is equivalent to the global ajaxStop event (but for file upload requests only).
stop: function(e){
location.reload();
}

I have used this code and so far it works well.
$('#fileupload').bind('fileuploadstop', function (e) {
console.log('Uploads finished');
location.reload(); // refresh page
});

I used ryan's code, but there was a problem. The value of data.getNumberOfFiles() was decreasing as the files were uploaded while fileCount was increasing, so my upload script got interrupted at the middle of my upload where data.getNumberOfFiles() was equal to fileCount.
Here is how i tweaked ryan's script and now it's working like a charm:
var fileCount = 0, fails = 0, successes = 0;
var _totalCountOfFilesToUpload = -1;
$('#fileupload').bind('fileuploaddone', function (e, data) {
if (_totalCountOfFilesToUpload < 0) {
_totalCountOfFilesToUpload = data.getNumberOfFiles();
}
fileCount++;
successes++;
if (fileCount === _totalCountOfFilesToUpload) {
console.log('all done, successes: ' + successes + ', fails: ' + fails);
// refresh page
location.reload();
}
}).bind('fileuploadfail', function(e, data) {
fileCount++;
fails++;
if (fileCount === _totalCountOfFilesToUpload) {
console.log('all done, successes: ' + successes + ', fails: ' + fails);
// refresh page
//location.reload();
}
});
I hope this will help other people as well as! :)

Related

Ajax: Getting a Post Error when trying to use Relative Path

Struggling to get the relative path of an Ajax post request to pickup the php file. I'm not getting an error just nothing happens.
Browsed this site, but cannot find a previous answer on Ajax relative paths that I understand. Still a novice at this. Would really appreciate it, if someone could explain it in layman terms.
I'm trying to access the php file 'search/search.php' from the root file 'index.php' (this file contains the Ajax request). This worked when both files were in the same directory.
File structure below:
JQuery code snippet:
$(function() {
$('form').on("submit", function(e) {
e.preventDefault();
$('#error').text(""); // reset
var name = $.trim($("#search").val());
if (name.match(/[^a-zA-Z0-9 ]/g)) {
$('#error').text('Please enter letters and spaces only');
return false;
}
if (name === '') {
$('#error').text('Please enter some text');
return false;
}
if (name.length > 0 && name.length < 3) {
$('#error').text('Please enter more letters');
return false;
}
$.ajax({
url: 'search/search.php',
method: 'POST',
data: {
msg: name
},
dataType: 'json',
success: function(response) {
$(".content").html("")
$(".total").html("")
if(response){
var total = response.length;
$('.total') .append(total + " Results");
}
$.each(response, function() {
$.each($(this), function(i, item) {
var mycss = (item.Type == 1) ? ' style="color: #ffa449;"' : '';
$('.content').append('<div class="post"><div class="post-text"> ' + item.MessageText + ' </div><div class="post-action"><input type="button" value="Like" id="like_' + item.ID + '_' + item.UserID + '" class="like" ' + mycss + ' /><span id="likes_' + item.ID + '_' + item.UserID + '">' + item.cntLikes + '</span></div></div>');
});
});
}
});
});
});
The leading forward slash simply means “begin at the document root”, which is where index.php lives. So /search/search.php should be correct. If the server is unable to find the file, it stands to reason that there must be some url rewriting happening.
You can test by simply pointing your browser to http://localhost:8000/search/search.php. If you get a 404, you know it has nothing to do with ajax

Duplicate results Infinite scrolling API PHP

I am doing infinite ajax scrolling with php and api but my data is repeating. i don't want to load data when user is end of page(run perfectly) . What i want when user reach at certain div(check_onload) then load the data but in this case data is repeating.Here is below my code how i stop repeating data.
<div id="post-data"></div>
<div style="display:none;" class="ajax-load"></div>
<div class="check_onload"></div>
<script type="text/javascript">
///this run Perfectly
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
var token = $(".tokenId").val();
GetMoreData(token);
}
});
///Repeating or duplication the data
$(window).on('scroll',function() {
if (checkVisible($('#check_onload'))) {
var token = $(".tokenId").val();
GetMoreData(token);
} else {
}
});
function checkVisible( elm, eval ) {
eval = eval || "object visible";
var viewportHeight = $(window).height(), // Viewport Height
scrolltop = $(window).scrollTop(), // Scroll Top
y = $(elm).offset().top,
elementHeight = $(elm).height();
if (eval == "object visible") return ((y < (viewportHeight + scrolltop)) && (y > (scrolltop - elementHeight)));
if (eval == "above") return ((y < (viewportHeight + scrolltop)));
}
function GetMoreData(token){
$.ajax(
{
url: '/loadMoreData.php?token=' + token,
type: "get",
beforeSend: function()
{
$('.ajax-load').show();
}
})
.done(function(data)
{
$('.ajax-load').hide();
$("#post-data").append(data.html);
$("#tokenId").val(data.token);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('server not responding...');
});
}
</script>
You have 2 window scroll events being triggered, causing duplicates because you are requesting data from the server with the same token twice, each time the user scrolls the page. I will have to assume that removing 1 of them will fix your problem.
Without seeing your server code, this is the only solution.

Countdown start on button press

Ive got an problem. I have an button that sends an command to an perl script. For 60 seconds the page will just load and load. So i need an countdown to tell the user how much time until the perl script is finished. So i got his javascript from the web that automaticly counts down when the page loads. Is it possible to reverse this?
http://goo.gl/cYdKg
You see what happens, when you don't state your requirements correctly? Two people doing the same wrong thing (bad for us, we did not clarified before, tho).
$.fn.timedDisable = function(time, callback) {
if (time == null) {
time = 5000;
}
var seconds = Math.ceil(time / 1000);
return $(this).each(function() {
$(this).attr('disabled', 'disabled');
var disabledElem = $(this);
var originalText = this.innerHTML;
disabledElem.text( originalText + ' (' + seconds + ')');
var interval = setInterval(function() {
disabledElem.text( originalText + ' (' + --seconds + ')');
if (seconds === 0) {
disabledElem.removeAttr('disabled')
.text(originalText);
clearInterval(interval);
if (typeof callback !== 'undefined')
callback();
}
}, 1000);
});
};
$(function() {
$('#btnContinue').click(function() {
$(this).timedDisable(5000, function() {
window.alert('done');
});
});
});

jQuery notifications, first not showing

I am using AJAX extensively and my PHP based notification system was not sufficient.
I have this function:
<script>
function user_notify($string, $class){
if($class == null){
$class = 'error';
}
$('<div class="' + $class + '"><div class="notification-text">' + $string + '</div></div>').hide().appendTo('#system-notifications').fadeIn('slow');
}
function DeleteTask(SpanName, TaskId){
if (confirm("Are you sure you want to delete this task?")) {
var curDateTime = new Date(); //For IE
var status = document.getElementById('status');
var poststr = "uniqueID=" + curDateTime.getTime() ;
var SpanName = SpanName;
if(SpanName == 'project_todos_complete'){
var showCompleted = 1;
} else {
var showCompleted = 0;
}
//alert (SpanName);
makePOSTRequest('http://*****webdesigns.com/project_manager/include/ajax/global.php?action=delete_task&showCompleted=' + showCompleted + '&id=' + TaskId, poststr, SpanName);
}
if(ajax_status == 4){
user_notify('Task deleted.', 'success');
ajax_status = null;
}
}
</script>
I have a global javascript variable that holds the readyState. If 4 is a response from the server, we can assume the AJAX was successful (I know, not neccessarily the cgi/php is execute if any). So I store that, and within the function that called the AJAX post, if the readyState is 4, I call the user_notify function.
It works beautifully with one exception: the first action that should trigger a notification does not. All consecutive actions successfully generate a message. It's not a specific action that doesn't work, just the first one.
The html:
<body>
<div id="system-notifications"></div>
<div class="wrapper">...</div>
What am I missing here?
UPDATE:
I am in the process of moving legacy javascript/Ajax calls to jQuery/Ajax. Everything works except one aspect: the targeted div does not 'refresh' with the return data from the .ajax jQuery call. The notification pops up (the first time and all consecutive times), the php executes (refreshing the page verfies this), but the div does not update with the html that the PHP script generates.
$('form#addToDoForm').submit(function(){
var project_id = $('#addToDoForm input[name=project_id]');
var assigned_id = $('#addToDoForm input[name=assigned_user_id]');
var description = $('#addToDoForm textarea[name=description]');
var responsible_id = $('#addToDoForm input[name=responsible_user_id :selected]');
alert(responsible_id.val());
return false;
var due = $('#addToDoForm input[name=due]');
var result_div = 'project_todos_' + project_id;
var query_string = 'action=add_to_do&id=' + project_id;
var ajax_url = 'http://avwebdesigns.com/basecamp/include/ajax/global.php?' + query_string;
var successMessage = '<b>' + description.val() + '</b> added.';
var data =
'project_id=' + project_id.val() +
'&assigned_user_id=' + assigned_id.val() +
'&responsible_user_id=' + responsible_id.val() +
'&description=' + encodeURIComponent(description.val()) +
'&due=' + encodeURIComponent(due.val()); // encodeURIComponent()
$.ajax({
type: 'POST',
url: ajax_url,
data: data,
cache: false,
success: function(data){
$('#'+result_div).html(data); // $('#'+result_div).html(data.returnValue);
user_notify(successMessage, 'success');
},
error:function(data){
$('#'+result_div).html(data);
user_notify(failureMessage, 'error');
}
});
return false;
});
Any ideas?
You are missing the non-blocking characteristics of an AJAX call probably. I can't really tell what makePOSTRequest does, but judging from your design I assume you expect it to be synchronous where it probably is not. Due to the asynchronous nature of an AJAX call, you need to pass a callback function to the call that is called when the AJAX request completes.
What probably happens in your case is that makePOSTRequest immediately returns and because the first request hasn't finished yet, ajax_status will not be 4 yet. Then, by the time the second request is sent, your first will have completed and your global variable will have been set to 4, so this time it works and this is also the cause why it works in all subsequent attempts.
This shows another flaw in your design: it's actually a very bad idea to capture the status of an AJAX request in a global variable. These requests are potentially sent in a concurrent fashion so you would have several requests that share one and the same variable - this calls for a 'race condition'. Have a look at the examples in the Ajax section of the jQuery documentation to see how to handle this correctly with the help of a callback function.

PHP + jQuery Synchronization problem

I'm using jQuery + PHP on my website and I want to do something like this:
To simplify things I've got a page with 2 buttons () and according to which I click I want to start a script in background (php script) so I do a simple thing with jquery:
$("#button1").click(function(){
$.post("script.php", {val:"but1"}, function(result){
alert(result); // I want something with the result
});
});
$("#button2").click(function(){
$.post("script.php", {val:"but2"}, function(result){
alert(result);
});
});
and in the script.php I've got a simple if statement deciding what I should do.
In the php script I'm downloading a file and I want to create a progress bar of the file download. The php script would return me values (echo percentage; flush();) in some time interval.
And here comes the problem - when I echo those percentage values and flush it refreshes it "just in php" but the jquery waits until the script is finished anyway. Is there a way to get those values as they appear (after flush) or is there a completely other approach to this? I can't think of anything else right now, maybe I shouldn't be using jquery at all.
Thanks for the help.
You can store the progress in a text file or DB while running the script and then have another file get the result via AJAX calls.
JS/HTML
<script>
$(function() {
var id;
var timeoutLength = 1000;
$("#button1").click(function() {
$("#result").html("");
// Create unique identifier
id = (new Date().getTime()) + "-" + Math.floor(Math.random()*100);
$.get("script.php", {id: id}, function(result){
$("#result").html(result);
});
setTimeout(checkProgress, timeoutLength);
});
function checkProgress() {
$.get("script.php", {progress: true, id: id}, function(data) {
prog = parseInt(data);
// Display progress bar
if(prog < 100) {
$("#progress").css({ display: 'block', width: prog });
$("#progress").html(prog + "%");
setTimeout(checkProgress, timeoutLength);
} else {
$("#progress").css('display', 'none');
}
});
}
})
</script>
<button id="button1">Click</button>
<div id="progress" style="background: green"></div>
<div id="result"></div>
script.php
<?php
function getProgress($file) {
return (file_exists($file)) ? file_get_contents($file) : 0;
}
function setProgress($file, $progress) {
file_put_contents($file, $progress);
}
// Remove invalid characters
$id = str_replace('/[^a-zA-Z0-9\-_]/', '', $_GET['id']);
$file = "progress-" . $id . ".txt";
if(isset($_GET['progress'])) {
echo getProgress($file);
} else {
// Do something and update progress
for($i = 10; $i <= 100; $i += 10) {
// Do something
setProgress($file, $i);
sleep(1);
}
unlink($file);
echo "Result: " . rand(1, 100);
}
Edit:
Added support for multiple requests and simple progress bar.
i believe that what all you need is the pecl uploadprogress package
it is not very easy to install and its not sure it works, i have find hard to make it work under certain server configurations, but i think its a good shot
EDIT: sorry i didnt see you mention download so have a look here
Below script will work for the progress-bar.
But, what I would do is, trigger an AJAX call to start the download and trigger another AJAX call to start receiving the input (using How to show file download progress in PHP Shell Scripting?).
PHP:
<?php
echo "wget '$feedURL'\n";
$execute = "wget -O ".$filePath." '$feedURL'\n";
$systemOutput = shell_exec($execute);
$systemOutput = str_replace( "\n", "\n\t", $systemOutput);
echo "\t$systemOutput\n";
?>
GetProgress:
function getProgress(){
GDownloadUrl("getprogress.php?progress_key=<?php echo($unique_id)?>",
function(percent, responseCode) {
document.getElementById("progressinner").style.width = percent+"%";
if (percent < 100){
setTimeout("getProgress()", 100);
}
});
}
Here is nice implementation with the help PHP's APC to get a nice progress-bar during UPLOAD of a file - http://www.haughin.com/2007/10/23/php-upload-progress-with-php-52-apc/
Alternative solution:
You can store the progress of downloading file into $_SESSION array inside PHP.
Besides that, you can write a dedicated PHP to only retrieve this percentage from session. This PHP will be called from your client's AJAX. This way the proccess won't take so much resources from server to calculate or to echo the download's percentage.
Try to avoid I/O from files if you are going to handle high rates of reading/writing onto them. Session variables are less expensive to achieve this functionality.
Provided that your PHP has some way to know the progress percentage, you should do multiple requests for progress updates:
function receiveProgress(data) {
// update progres indicator here
if (parseFloat(data) < 100) {
setTimeout(checkProgress, 100);
} else {
pressedButton = '';
}
}
function checkProgress() {
$.post("script.php", {val:pressedButton}, receiveProgress);
}
var pressedButton = '';
$("#button1").click(function(){
pressedButton = 'but1';
checkProgress();
});
This will ask server for progress updates every 100ms

Categories