SOF users: today I have another challenge for you:
I have this piece of code, a part of jquery Uploader. Each file uploaded uses this code, where I create correct answer if file was uploaded ok or not.
When a file is uploaded ok, I put a delete button (cannot use form tag here). I want to add a fadeout effect.
EDIT: now all the interesting code.
<script>
var conexion;
var numarch = 0;
var idactual = 0;
function crearXMLHttpRequest(){
var xmlHttp=null;
if (window.ActiveXObject)
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
else
if (window.XMLHttpRequest)
xmlHttp = new XMLHttpRequest();
return xmlHttp;
}
function borrar_archivo(iddiv, ruta, header){
conexion=crearXMLHttpRequest();
idactual = iddiv;
conexion.onreadystatechange = procesarEventos;
conexion.open(header, ruta, true);
conexion.send(null);
}
function procesarEventos(){
var detalles = document.getElementById(idactual);
if(conexion.readyState == 4){
var resultado = conexion.responseText;
if(resultado.indexOf("true")!=-1){
nomArchivo = conexion.responseText.split(":",1);
nombreArchivo = nomArchivo[0].substring(1);
detalles.innerHTML = "<p style='float: left; clear:left; color: #66CC00; font-size:12px;'>"+nombreArchivo+" ha sido borrado.";
}
else{
detalles.innerHTML = "<p style='float: left; clear:left; font-size:12px;' class='text-danger'>Ha habido un error al borrar el archivo.</p>";
}
}
else{
detalles.innerHTML = "<p style='float: left; clear:left; font-size:12px;'>Cargando...</p>";
}
setInterval(function(){
$("#"+idactual).fadeOut(1000);
},1500);
}
$(function(){
$('#fileupload').fileupload({
dataType: 'json',
done: function (e, data){
$.each(data.result.files, function (index, file) {
numarch++;
$('<div id="archivo_'+numarch+'" />').appendTo('#files');
if (file.error){
$('<img style="width: 16px; float: left; clear:left; margin-right: 10px;" src="img/x.png" title="Error" alt="Error"/>').appendTo('#archivo_'+numarch);
$('<p style="float: left; font-size:12px;" class="text-danger"/>').text(file.error).appendTo('#archivo_'+numarch);
}
else{
var newFileDiv = $("<img style='width: 16px; float: left; clear:left; margin-right: 10px;' src='img/v.png' title='Archivo subido OK' alt='Archivo subido OK'/><p style='float: left; color: #66CC00; font-size:12px;'>"+file.name+"</p><div style='float :left; height: 5px;margin-left: 25px;' class='btn btn-danger delete' onclick=borrar_archivo('archivo_"+numarch+"','"+file.deleteUrl+"','"+file.deleteType+"')><i style='top: -5px;left: -5px;' class='glyphicon glyphicon-trash'></i><span style='top: -6px;position: relative;'>Borrar</span></div>");
$('#archivo_'+numarch).append(newFileDiv);
}
});
},
progressall: function (e, data){
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').html(progress + '%');
$('#progress .progress-bar').css('width',progress + '%');
}
});
});
</script>
I just founded that I can "delete" one item ok. but when I use multiple buttons to delete a lot of items, the function breaks, only deleting last elements I clicked...
I want to do this fadeout effect asynchronous.(that is the reason for the setInterval instead setTimeout)...
But nothing works for me. Now I am little lost about this.
Any help, please?
EDIT 2:
Now, trying I find how to delete 2 or more items, but the fadeout() effect only works on first one:
function borrar_archivo(iddiv, ruta, header){
conexion=crearXMLHttpRequest();
idactual = iddiv;
conexion.onreadystatechange = procesarEventos;
conexion.open(header, ruta, true);
conexion.send(null);
setInterval(function(){
$("#"+idactual).fadeOut(1000);
},1500);
setInterval(function(){
$("#"+idactual).remove();
},1000);
}
Any idea why this happend? and how to solve it?
So let's say you have a delete button:
$deletebutton.on('click', function (e) {
$(e.currentTarget).fadeOut();
});
Recommended: console.log(e) - you can find many other items in there you can access that may be helpful
But what if you dont want to remove the item you clicked on?
change .fadeOut to...
$itemtoremove.fadeOut();
Ok, until a lot of research, I founded the solution:
When you have a bunch of elements with a Delete button, all buttons calls to the same function: this is a problem when you work with timers, because when you are in "the waiting time" and you re-execute that timers, the inner action of the timer can be stopped(overwrited before has been sended).
The solution I found is this: put the wait time lesser than the fadeout time, not allowing the inner function to be stopped. Why this works? I don't know, but you can overclick the buttons and all the inner functions work.
I paste here my code. If you need more code to understand it, write it: idactual is the id name of the div to be faded out. numarc is the number used to identify each div: (e.g.: idactual = archivo_1 , numarch = 1)
setInterval(function(){
$("#"+idactual).fadeOut(1500, function(){
var i=0;
for(i=1;i>numarc;i++){
elemento=$(document).getElementById("archivo_"+i);
texto = elemento.innerHTML;
if(texto.indexOf("borrado")!=-1){
elemento.remove();
}
}
});
},100);
Related
I want my CSS animations for the elements in my header.php to continue smoothly on different pages.
So if I had a 200 second looped animation and 80 seconds in I clicked on the about us page the animation would still be 80 seconds in on page load?
Is this even possible and if so, how? Thanks.
You can do it if it's some sort of keyframes animation like:
CSS
#keyframes colorchange {
0% {background: red;}
50% {background: green;}
100% {background: yellow;}
}
div {
width: 100px;
height: 100px;
background: red;
-webkit-animation: colorchange 5s linear infinite;
animation: colorchange 5s linear infinite;
-moz-animation: colorchange 5s linear infinite;
}
JS
$(document).ready(function(){
var animationTime=0;
var intId = setInterval(function(){
animationTime++;
},1000);
var postTime = function(link){
$.ajax({
type: 'POST',
url: link,
data: {'variable': animationTime},
});
}
$('a').click(function(){
window.onbeforeunload = postTime($(this).attr('href'));
})
})
PHP
$myval = $_POST['variable'];
echo "$('div').css('animation-delay', '-".$myval."s')"
You can use negative animation delay to start animation from some point, but in any way, this method is not perfect, but worth a try.
P.S But better use AJAX for page reload in such cases :)
Quick rough thought
time = 200000;
var distance = 300;
window.currentTime = 0;
$('#element').animate({ left: distance },
{
duration: time,
step: function(now, fx) {
window.currentTime = Math.round((now*time)/distance);
}
});
$('a').on("click", function(e){
e.preventDefault();
window.location.href = "http://yoururl.com/?startingPoint=" + (time - window.currentTime);
});
then in each file do something like
if($_GET['startingPoint']){
echo 'time = '.$_GET['startingPoint'];
}
else{
echo 'time = 200000';
}
in place of the javascript time variable, i apologize if theres bugs in this, literally just pulled this out of my butt, but the concept is there, and no ajax needed.
Hi I need set value of PHP variable to "1" if clients screen resolution is more then 1200px (I check only width) and set value of this variable to "2" if client have screen smaller then 1200px.
To check clients width of screen I use JQuery function "$( window ).outerWidth(true)". If PHP can check clients resolution then I don´t need wrote this question, but PHP not allow this and for that I search for solution of this problem.
=> How can I write script which allow change PHP variable before client load page? I mean I need AJAX, but I don´t know how used it.
Sorry for this maybe simply question. Can someone help me?
This might help ,
var width = $(window).width();
var height = $(window).height();
var screenTimer = null;
function Screen (){
$(window).resize(function() {
height = $(window).height();
width = $(window).width();
getScreen ();
});
function getScreen (){
return { 'height' : getHeight (), 'width': getWidth () };
}
screenTimer = setInterval ( getScreen (), 50 );
}
function getHeight (){
console.log ( 'height: ' + height);
$('#height').text(height);
return height;
}
function getWidth (){
console.log ( 'width: ' + width);
$('#width').text(width);
return width;
}
Screen ();
put this code in php along with script tag and set your variable.
Impossible I get it... Finally a write this:
index.php:
<script type="text/javascript">
$(document).ready(function() {
var sirka_monitoru = $( window ).outerWidth();
if ( sirka_monitoru < 1200 ){
$.post("soubor1.php", { nejaka: "1111" }, function (msg)
{
$('.some_name').html(msg);
});
}
else{
$.post("soubor2.php", { nejaka: "2222" }, function (msg)
{
$('.some_name').html(msg);
});
}
}); //END $(document).ready()
</script>
<div class="some_name"></div>
soubor1.php (1st file to include) file soubor2.php is similar to soubr1.php
<?php
echo "Value: " . $_POST["nejaka"];
?>
<div style="width: 100%; float: left; background-color: green; height: 100px;">
soubor1
</div>
=> When I load page then check width of users screen and after that I can load different PHP files and send him some important variables to solved my problem from question.
=> I accept my answer and solved this queston and close it
So I'm having a little issue. I am working on a site and this is the first I have used ajax to post to to a page. I have a form with a submit button and a link on it. When the submit button is pressed everything works but users should be able to click the link to by pass a page but I still need some information posted to that page so I googled ho to post with out a submit button and ajax came up so I figured I'd give it a shot. It seems to not be working. Here is the code that I am using.
$('#chkEndAccDate').click(function(evt){
alert("before ajax");
var totalcost = $('#total_cost').val();
$.ajax({
type: "POST",
url: "http://sandbox.phareconsulting.com/complete_order.php",
`enter code here`data: {cost : totalCost}
});
alert("after ajax");
});
This code also doesn't work when i try it
$(document).on('click','#chkEndAccDate',function(){
cost = $('#total_cost').val();
$.post("http://www.sandbox.phareconsulting.com/complete_order.php",
{cost: cost},function(d){
alert("post");
});
});
In the php file right now I am simply doing print_r($_POST); but the post array is empty. Can some one please help me out. I think that some of us just don't understand ajax correctly. I thought I did but I am not able to get it to work.
Thank you.
This should be proper syntax:
data: "{'cost':'" + cost+ "'}"
Use this
data:{cost: cost}
for sending the data.
Use this code:
$(document).on('click','#chkEndAccDate',function(){
cost = $('#total_cost').val();
$.post("http://sandbox.phareconsulting.com/complete_order.php",
{cost: cost},function(d){
});
});
s.d and Thiefmaster have already written the correct syntax, however, it may be a good idea to change the name of your variable so as to avoid confusion.
var totalCost = $('#total_cost').val();
Then use:
data: {cost : totalCost}
Its a good idea to use the jQuery Form Plugin to send ajax forms this will by itself grab the data and send it to the form action url.
This plugin also gives you functions that control the sending process . This is an example :
var bar = $('#progressBar');
var percent = $('#percent');
var status = $('#status');
$('#form-id').ajaxForm({
beforeSend: function() {
//validate the data
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
// draw a progress bar during ajax request
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
},
complete: function(xhr) {
bar.width("100%");
percent.html("100%");
}
});
Html for the progress bar :
<div id="progress">
<div id="bar"></div >
<div id="percent">0%</div >
</div>
css :
#progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
#bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
#percent { position:absolute; display:inline-block; top:3px; left:48%; }
I use the following jquery code to load a page...
$(function() {
$('#stats').load('statsto.php');
var visibleInterval = 60000;
var invisibleInterval = 120000;
$(function() {
setTimer();
$(document).bind('visibilitychange'), function() {
clearTimeout(timer);
setTimer();
};
});
function displayStats() {
$('#stats').load('statsto.php');
$.ajaxSetup({ cache: false });
}
function setTimer() {
timer = setInterval(displayStats, (document.hidden) ? invisibleInterval : visibleInterval);
}
});
and here is the style from statsto.php...
body {
font-family: Verdana;
font-size: 7px;
color: #FFFFFF;
background-color: #000000;
background-image: url("grad.png");
}
But the background image is not showing in internet explorer. I have tried using background: black url("grad.png"); but that also doesn't work. I have also tried including the style in the same page as the JQuery code, but still no luck.
Hmm.. Your issue may be with the .load() function itself (in Internet Explorer). I seem to remember encountering an issue with that a while back...
Try this
$.get('statso.php', function() {
$('#stats').html();
});
is there any jQuery plugin to create something like the live feed from the Twitter Main Page , using PHP, which is getting the data from a MySQL database?
How has to be the PHP file?
Thanks.
You really don't need a plugin for this, you could easily create something similar yourself using jQuery to make AJAX calls to a PHP MySQL feed
Create a script to make reoccurring AJAX calls using setTimeout() and then add the new found results to the feed container using .prepend()
HTML
<html>
<head><title>Tweets</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<style>
#tweets {
width: 500px;
font-family: Helvetica, Arial, sans-serif;
}
#tweets li {
background-color: #E5EECC;
margin: 2px;
list-style-type: none;
}
.author {
font-weight: bold
}
.date {
font-size: 10px;
}
</style>
<script>
jQuery(document).ready(function() {
setInterval("showNewTweets()", 1000);
});
function showNewTweets() {
$.getJSON("feed.php", null, function(data) {
if (data != null) {
$("#tweets").prepend($("<li><span class=\"author\">" + data.author + "</span> " + data.tweet + "<br /><span class=\"date\">" + data.date + "</span></li>").fadeIn("slow"));
}
});
}
</script>
</head>
<body>
<ul id="tweets"></ul>
</body>
</html>
PHP
<?php
echo json_encode(array( "author" => "someone",
"tweet" => "The time is: " . time(),
"date" => date('l jS \of F Y h:i:s A')));
?>
setInterval() would be more adequate, since you want a check at regular intervals.
Then, there is a jquery comet plugin that explores the implementation of the "push" technology. Check it out here.
var frequency = 5000, // number of milliseconds between updates.
updater = function() {
jQuery.ajax({
url: 'http://twitter.com/example/something.html',
success: function(data) {
// update your page based upon the value of data, e.g.:
jQuery('ul#feed').append('<li>' + data + '</li>');
}
});
},
interval = setInterval(updater, frequency);
<script>
$(document).ready(function(){
var frequency = 10000; // 10 seconds = 10000
var updater = function() {
$.ajax({
url: 'mesaj.html', // data source html php
cache: false,
success: function(data) {
$("#message").html(data); // div id
}
});
};
interval = setInterval(updater, frequency);
});
</script>
example
<div id="message">{ do not write }</div>