How to select prepended element - php

i have a upload form that uses the new multiple attribute and i made an ajax upload form to make things more user friendly. My problem is im trying to update percentages for all of these files that are being uploaded and appended to a div, instead of one percentage being updated all of them get updated from the last file. Here is some code.
$('#File').change(function(event) {
for(I = 0; I < this.files.length; I++)
{
var Name = this.files[I].name;
var Size = this.files[I].size;
var Type = this.files[I].type;
$('#UploadContent').prepend('<div class="UploadLabel" style="width:60%;">'+Name+'</div><div class="UploadLabel UploadPercent" style="width:10%;">0%</div><div class="UploadLabel" style="width:15%;">N/A</div><div class="UploadLabel" style="width:15%;">'+Type+'</div>');
var Data = new FormData();
Data.append('File[]', this.files[I]);
var Request = new XMLHttpRequest();
Request.upload.addEventListener('progress', function(event){
if(event.lengthComputable)
{
var Percent = event.loaded / event.total;
var Progress = $('#UploadContent').find('.UploadPercent');
$(Progress).text(Math.round(Percent * 100) + '%');
}
});
Request.upload.addEventListener('load', function(event) {
});
Request.open('POST', '/Home/Upload/Upload.php');
Request.setRequestHeader('Chache-Control', 'no-cache');
Request.send(Data);
$('#UploadModal').fadeIn('fast');
}
});
now as you can see in the progress listener my
var progress = $('#UploadContent').find('.UploadPercent');
how would i select the file that is supposed to be updated correctly. If someone can find a comepletely different method to change the percent that would be great too! - Thanks!

When you're prepending, add a new, specific class (yes, you could use an id, but I'd just stick to class) to the .UploadPercent element:
$('#UploadContent').prepend('<div class="UploadLabel" style="width:60%;">'+Name+'</div><div class="UploadLabel UploadPercent UploadTarget' + I + '" style="width:10%;">0%</div><div class="UploadLabel" style="width:15%;">N/A</div><div class="UploadLabel" style="width:15%;">'+Type+'</div>');
// LOOK HERE----------------------------------------------------------------------------------------------------------------------^ HERE
And when you're targeting, use this:
var progress = $('#UploadContent').find('.UploadTarget' + I);
Because you need the value of I to be accurate based on where you are in the loop, you need to use a closure as well. So your code will end up looking like:
$('#File').change(function(event) {
for(I = 0; I < this.files.length; I++) {
(function (I) {
// Your current code inside the for loop
})(I);
}
});
While the example from above is definitely an option, it probably makes more sent to just store a reference to the newly inserted element and not have to deal with a new class and I, and then use it later.
Here is the final code I'd use:
http://jsfiddle.net/MeL7L/2/
$("#File").on("change", function (event) {
for (var i = 0; i < this.files.length; i++) {
(function (curFile, i) {
var Name = curFile.files[i].name;
var Size = curFile.files[i].size;
var Type = curFile.files[i].type;
var newEl = "";
newEl += '<div class="UploadLabel" style="width:60%;">' + Name + '</div>';
newEl += '<div class="UploadLabel UploadPercent" style="width:10%;">0%</div>';
newEl += '<div class="UploadLabel" style="width:15%;">N/A</div>';
newEl += '<div class="UploadLabel" style="width:15%;">' + Type + '</div>';
newEl = $(newEl);
$("#UploadContent").prepend(newEl);
var Data = new FormData();
Data.append("File[]", curFile.files[i]);
var Request = new XMLHttpRequest();
Request.upload.addEventListener("progress", function (event){
if (event.lengthComputable) {
var Percent = event.loaded / event.total;
var Progress = newEl.find(".UploadPercent");
Progress.text(Math.round(Percent * 100) + "%");
}
});
Request.upload.addEventListener("load", function(event) {});
Request.open("POST", "/Home/Upload/Upload.php");
Request.setRequestHeader("Cache-Control", "no-cache");
Request.send(Data);
$("#UploadModal").fadeIn("fast");
})(this, i);
}
});

Related

How to add extra space to div using Jquery?

I am working on the sticky menu and highlight menu based on div id in WordPress. I have completed code well but I got a problem.
I have a sticky header when I click menu item in side sticky menu title going back to header title not visible.
I want result like this.'
How can I solve this?
My Jquery Code
jQuery(function($) {
/**
* This part causes smooth scrolling using scrollto.js
* We target all a tags inside the nav, and apply the scrollto.js to it.
*/
$("#nav a").click(function(evn){
evn.preventDefault();
$('html,body').scrollTo(this.hash, this.hash);
});
var aChildren = jQuery("#nav li").children(); // find the a children of the list items
var aArray = []; // create the empty aArray
for (var i=0; i < aChildren.length; i++) {
var aChild = aChildren[i];
var ahref = jQuery(aChild).attr('href');
console.log(ahref);
aArray.push(ahref);
} // this for loop fills the aArray with attribute href values
$(window).scroll(function(){
var windowPos = $(window).scrollTop()+70; // get the offset of the window from the top of page
console.log('Window Position:'+windowPos);
var windowHeight = $(window).height(); // get the height of the window
var docHeight = $(document).height();
for (var i=0; i < aArray.length; i++) {
var theID = aArray[i];
//console.log(theID);
var divPos = $(theID).offset().top-150; // get the offset of the div from the top of page
console.log('Div Position:'+divPos);
var divHeight = $(theID).height(); // get the height of the div in question
if (windowPos >= divPos && windowPos < (divPos + divHeight)) {
$("a[href='" + theID + "']").addClass("nav-active");
} else {
$("a[href='" + theID + "']").removeClass("nav-active");
}
}
if(windowPos + windowHeight == docHeight) {
if (!$("#nav li:last-child a").hasClass("nav-active")) {
var navActiveCurrent = $(".nav-active").attr("href");
$("a[href='" + navActiveCurrent + "']").removeClass("nav-active");
$("#nav li:last-child a").addClass("nav-active");
}
}
});
});
You need to offset the height of the heading when you jump to an anchored section.
Are you using the jQuery scrollTo plugin? If you can do something like:
$("#nav a").click(function(evn){
evn.preventDefault();
$('html,body').scrollTo(this.hash, 800, {offset: {top:-80, left:0} });
});
Options for scrollTo found here: http://demos.flesler.com/jquery/scrollTo/

I want to make this similar HTML structure in jQuery function dynamically and append to html tag id="images"

I am uploading images and want to show separate progress bar for each image.
This kind of similar structure I want to create dynamically in jQuery. Here I m trying to create img element uploaded by input file and want to create html container classname 'preview' and put into already created #images tag by using jQuery. Will you please anyone fix it? so frustrated and thanks in advance to all intelligent brains here.
<div id="images"> // already exist
<div class="preview" id="rand">
<img src="background/balance.jpg" id="rand"/>
<div class="progressbar" id="rand">
</div> // this is the preview container to create and put by dynamically in jQuery function
</div>
this is my jQuery function.
function handleFile(files) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
var fileReader=new FileReader();
var rand = Math.floor((Math.random()*100000)+3); /* this is created for assign id attribute to div and img tag to differentiate each other */
var imageElem=document.createElement("img");
imageElem.id=rand;
var div = document.createElement('div');
div.className = 'preview';
div.id = rand;
var progress = document.createElement('div');
progress.className='progressbar';
progress.id=rand;
fileReader.onload = (function(img)
{
return function(e)
{
img.src = e.target.result;
};
}) (imageElem);
/* here I am trying to create that structure */
document.getElementById("images").appendChild(imageElem); /* and need to append here */
fileReader.readAsDataURL(file);
// document.getElementById("areatext").style.display = "none";
document.getElementById("submit1").style.display = "block";
document.getElementById("submit2").style.display = "block";
uploadFile(file,rand);
}
}
function uploadFile(file,rand) {
var xhr = new Array();
xhr[rand] = new XMLHttpRequest();
var formData = new FormData();
formData.append('myFile[]',file);
xhr[rand].upload.addEventListener("progress", function(e) {
if (e.lengthComputable) {
$(".progressbar[id='"+rand+"']").css("width",(e.loaded / e.total) * 100 + "%");
}
}, false);
xhr[rand].open("POST", "drop.php");
xhr[rand].overrideMimeType('text/plain; charset=x-user-defined-binary');
xhr[rand].send(formData);
}

Parsing json with Jquery no loops

Hello I am trying to parse a .json file.. it only has 1 set of data I don't think the $.each is the best approach but it's all I can find....
Here is my code:
<script type="text/javascript">
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
var url = 'http://f.cl.ly/items/1L2k221B183J1e1G411j/200.json';
/* <![CDATA[ */
$(document).ready(function(){
$.getJSON(url, function(data){
$.each(data.test, function(i,test){
content = '<h1><p class="p1"><span class="s1">' + test.name + '</span></p></h1><table class="table table-bordered"><tbody><tr><td>Section:</td><td>Chemistry</td></tr><tr><td>Synonyms:</td><td>Mg Level</td></tr><tr><td>Container:</td><td>' + test.container + '</td></tr><tr><td>Reference Ranges:</td><td>' + test.reference + '</td></tr><tr><td>Availability:</td><td>' + test.availability + '</td></tr><tr><td>Special Handling:</td><td>' + test.specialHandling + '</td></tr><tr><td>Additional Comments:</td><td>' + test.additionalComments + '/td></tr></tbody></table>';
$(content).appendTo("#main");
$("#main").fadeIn( );
});
});
});
/* ]]> */
</script>
The result kinda works... the table is there but the code loops 3 times and displays "undefined" for all veribles.
Any help would be great!
Just use the result data without a loop. If data.test is not an array, you can access the object properties directly.
something like :
<script type="text/javascript">
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
var url = 'http://f.cl.ly/items/1L2k221B183J1e1G411j/200.json';
/* <![CDATA[ */
$(document).ready(function(){
$.getJSON(url, function(data){
content = '<h1><p class="p1"><span class="s1">' + data.test.name + '</span></p></h1><table class="table table-bordered"><tbody><tr><td>Section:</td><td>Chemistry</td></tr><tr><td>Synonyms:</td><td>Mg Level</td></tr><tr><td>Container:</td><td>' + data.test.container + '</td></tr><tr><td>Reference Ranges:</td><td>' + data.test.reference + '</td></tr><tr><td>Availability:</td><td>' + data.test.availability + '</td></tr><tr><td>Special Handling:</td><td>' + data.test.specialHandling + '</td></tr><tr><td>Additional Comments:</td><td>' + data.test.additionalComments + '/td></tr></tbody></table>';
$(content).appendTo("#main");
$("#main").fadeIn( );
});
});
/* ]]> */
</script>
Try this:
<script type="text/javascript">
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
var url = 'http://f.cl.ly/items/1L2k221B183J1e1G411j/200.json';
/* <![CDATA[ */
$.getJSON(url, function(data)
{
for(var i in data.test)
{
var obj = data.test[i];
var content = '<h1><p class="p1"><span class="s1">' + obj.name + '</span></p></h1><table class="table table-bordered"><tbody><tr><td>Section:</td><td>Chemistry</td></tr><tr><td>Synonyms:</td><td>Mg Level</td></tr><tr><td>Container:</td><td>' + test.container + '</td></tr><tr><td>Reference Ranges:</td><td>' + obj.reference + '</td></tr><tr><td>Availability:</td><td>' + obj.availability + '</td></tr><tr><td>Special Handling:</td><td>' + obj.specialHandling + '</td></tr><tr><td>Additional Comments:</td><td>' + obj.additionalComments + '/td></tr></tbody></table>';
$(content).appendTo("#main");
$("#main").fadeIn( );
}
});
/* ]]> */
</script>
$.each(Object or Array, iterator) is probably what you should use. The real issue is that data.test has to be an Object or an Array, not an Object property that's not an Object or an Array.

i am getting ajax response slow

i am using the following code for pass and get data through ajax.
function passdata(id)
{
var top = document.getElementById("tname").value;
var first = document.getElementById("fname").value;
var font_top = document.getElementById("font_top").value;
var font_first = document.getElementById("font_first").value;
var image_top = document.getElementById("image_top").value;
var image_first = document.getElementById("image_first").value;
var poststr = "id=" + id +
"&top=" + top +
"&first=" + first +
"&font_top=" + font_top +
"&font_first=" + font_first +
"&image_top=" + image_top +
"&image_first=" + image_first +
"&actype=getevent";
var reqAddCart = new Subsys_JsHttpRequest_Js();
reqAddCart.onreadystatechange = function() {
if (reqAddCart.readyState == 4) {
if (reqAddCart.responseJS) {
document.location.href = reqAddCart.responseJS.ajax_redirect;
return;
}
else {
//alert(reqAddCart.responseText);
//showModal('abc');
document.getElementById('data_content').innerHTML = reqAddCart.responseText;
result = (reqAddCart.responseText||'');
var brokenresult=result.split("#");
}
}
}
var senddata = new Object();
var url = 'product.php?'+poststr;
//alert(url);
reqAddCart.caching = false;
reqAddCart.open( 'GET', url, true);
reqAddCart.send( senddata );
return false;
}
i am using the passdata function to pass the data in product page.this function works but i am getting response very slow.
The time taken for an AJAX request to complete is affected by network latency and connection speed on both the server and client, as well as execution time of the script on the server.
I would expect AJAX requests made locally when testing to return a lot faster as it removes the need for transmitting data over the internet.

Google Map - Take coordinates

I have google map on my site(php,apache,mysql).
here is code:
<script type="text/javascript">
function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
var point = new GLatLng(<? $default_ll ?>,<? $default_spn ?>);
map.setCenter(point, 15);
map.setUIToDefault();
map.setMapType(G_NORMAL_MAP);
var marker = new GMarker(point);
map.addOverlay(marker);
}
}
window.onload = initialize;
window.onunload = GUnload;
</script>
<div id="map_canvas" style="width:500px;height:300px;"></div>
I want to make button(outside of map div), so when user chose hes coords and clicks this button. Current location he is watching rightnow will be put in to database. Well for simplicity can you show how to assign current: ll to $new_ll and spn to $new_spn
The GMap2 map object has these methods:
var center = map.getCenter(); // returns GLatLng of center point of map
var span = map.getBounds(); // returns GLatLngBounds of current map view
Using these simply you could have a button like this:
<input type="button" onclick="javascript:alert(map.getCenter())" value="Show Coordinates"/>
More realistically, you'll define a function to be called by the button's onclick:
function showCenterAndSpan()
{
var center = map.getCenter();
var span = map.getBounds();
var ne = span.getNorthEast();
var sw = span.getSouthWest();
var coordStr = "lat=" + center.lat() + "&lng=" + center.lng() +
"&n=" + ne.lat() + "&e=" + ne.lng() + "&s=" + sw.lat() + "&w=" + sw.lng();
alert(coordStr); // Or, post this string to the server to save into the database
}

Categories