jQuery .text() does not appear in html, but in console.log - javascript

I have this line of code
$('.bartext').text(percentComplete + "%");
In the html it renders like
<p class="bartext text" style="font-size: 14.020371290794092px;"></p>
But the console.log of
console.log($('.bartext').text(percentComplete + "%"));
says
[p.bartext text, prevObject: x.fn.x.init[1], context: document, selector: ".bartext", jquery: "1.10.2", constructor: function…]
With outerHTML of
"<p class="bartext text" style="font-size: 14.020371290794092px;">100%</p>"
And outerText of
"100%"
EDIT: The whole part
$.ajax({
xhr: function()
{
var XHR = new window.XMLHttpRequest();
XHR.addEventListener('progress', function(evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
console.log(percentComplete);
$('.bar').css('width', (percentComplete * 2));
$('.bartext').text(percentComplete + "%");
}
}, false);
return XHR;
},
type: 'GET',
url: page,
data: {ajax : 1},
success: function(data) {
$('.content').empty().append(data);
}
});
What is going on?
Thank you!!!
:D

use $('.bartext').html(percentComplete + "%");
Are you shure, that percentComplete has a value
?

Related

Generate PDF from another page with JSPDF

I have a button in my page to generate PDF I use JSPDF to perform the task, my problem is that I have to retrieve the content in other pages ... I retrieve the html in string format and I do not Know how to handle it....
any ideas
Thank you
jQuery(document).ready(function () {
var inner_content1;
var page_title = "ExternalPage";
$.ajax({
url: "https://site.sharepoint.com/sites/sites/site/_api/web/Lists/getbytitle('Pages')/items?$filter=Title eq '" + page_title +"'",
type: "GET",
headers: {
"ACCEPT": "application/json;odata=verbose"
},
success: function (data) {
if (data.d.results[0]) {
inner_content1 = data.d.results [0].HtmlContenu;
str = "<div id='someID'>" + inner_content1 + "<div/>";
//alert(inner_content.replace(/(<([^>]+)>) /ig,""));
html = $.parseHTML( str ),
nodeNames = [];
//var $newDiv = $("<div/>") // creates a div element
//.attr("id", "someID"); // adds the id
//$(html).append($newDiv);
jQuery(document).ready(function () {
var doc = new jsPDF();
var specialElementHandlers = {
'#someID': function (element, renderer) {
return true;
}
};
$('#cmd').click(function () {
doc.fromHTML($("#someID").get(0), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
doc.save('sample-file.pdf');
});
});
}
},
error: function(){ //Error }
}});
});

how to run the following function jquery with a button?

The truth is that very little jquery, and I have the following jquery code with django and what it does is this.
to select the file:
<input id="chunked_upload" type="file" name="the_file">
the following jquery code is automatically executed
<script type="text/javascript">
var md5 = "",
csrf = $("input[name='csrfmiddlewaretoken']")[0].value,
form_data = [{"name": "csrfmiddlewaretoken", "value": csrf}];
function calculate_md5(file, chunk_size) {
var slice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
chunks = chunks = Math.ceil(file.size / chunk_size),
current_chunk = 0,
spark = new SparkMD5.ArrayBuffer();
function onload(e) {
spark.append(e.target.result); // append chunk
current_chunk++;
if (current_chunk < chunks) {
read_next_chunk();
} else {
md5 = spark.end();
}
};
function read_next_chunk() {
var reader = new FileReader();
reader.onload = onload;
var start = current_chunk * chunk_size,
end = Math.min(start + chunk_size, file.size);
reader.readAsArrayBuffer(slice.call(file, start, end));
};
read_next_chunk();
}
$("#chunked_upload").fileupload({
url: "{% url 'api_chunked_upload' %}",
dataType: "json",
maxChunkSize: 100000, // Chunks of 100 kB
formData: form_data,
add: function(e, data) { // Called before starting upload
$("#messages").empty();
// If this is the second file you're uploading we need to remove the
// old upload_id and just keep the csrftoken (which is always first).
form_data.splice(1);
calculate_md5(data.files[0], 100000); // Again, chunks of 100 kB
data.submit();
},
chunkdone: function (e, data) { // Called after uploading each chunk
if (form_data.length < 2) {
form_data.push(
{"name": "upload_id", "value": data.result.upload_id}
);
}
$("#messages").append($('<p>').text(JSON.stringify(data.result)));
var progress = parseInt(data.loaded / data.total * 100.0, 10);
/*$("#progress").text(Array(progress).join("=") + "> " + progress + "%");*/
$('#progress .progress-bar').css('width',progress + '%');
$('#progress .progress-bar').css('aria-valuenow',progress + '%');
},
done: function (e, data) { // Called when the file has completely uploaded
$.ajax({
type: "POST",
url: "{% url 'api_chunked_upload_complete' %}",
data: {
csrfmiddlewaretoken: csrf,
upload_id: data.result.upload_id,
md5: md5
},
dataType: "json",
success: function(data) {
$("#messages").append($('<p>').text(JSON.stringify(data)));
}
});
},
});
</script>
this code upload the file into several pieces with a progress bar. The problem is that I want the code to run only if I click a button to load and not how.
I tried as follows:
<input id="chunked_upload" type="file" name="the_file">
<button id="enviar">Enviar</button>
<script type="text/javascript">
var md5 = "",
csrf = $("input[name='csrfmiddlewaretoken']")[0].value,
form_data = [{"name": "csrfmiddlewaretoken", "value": csrf}];
function calculate_md5(file, chunk_size) {
var slice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
chunks = chunks = Math.ceil(file.size / chunk_size),
current_chunk = 0,
spark = new SparkMD5.ArrayBuffer();
function onload(e) {
spark.append(e.target.result); // append chunk
current_chunk++;
if (current_chunk < chunks) {
read_next_chunk();
} else {
md5 = spark.end();
}
};
function read_next_chunk() {
var reader = new FileReader();
reader.onload = onload;
var start = current_chunk * chunk_size,
end = Math.min(start + chunk_size, file.size);
reader.readAsArrayBuffer(slice.call(file, start, end));
};
read_next_chunk();
}
$('button#enviar').click(function(){
$("#chunked_upload").fileupload({
url: "{% url 'api_chunked_upload' %}",
dataType: "json",
maxChunkSize: 100000, // Chunks of 100 kB
formData: form_data,
add: function(e, data) { // Called before starting upload
$("#messages").empty();
// If this is the second file you're uploading we need to remove the
// old upload_id and just keep the csrftoken (which is always first).
form_data.splice(1);
calculate_md5(data.files[0], 100000); // Again, chunks of 100 kB
data.submit();
},
chunkdone: function (e, data) { // Called after uploading each chunk
if (form_data.length < 2) {
form_data.push(
{"name": "upload_id", "value": data.result.upload_id}
);
}
$("#messages").append($('<p>').text(JSON.stringify(data.result)));
var progress = parseInt(data.loaded / data.total * 100.0, 10);
/*$("#progress").text(Array(progress).join("=") + "> " + progress + "%");*/
$('#progress .progress-bar').css('width',progress + '%');
$('#progress .progress-bar').css('aria-valuenow',progress + '%');
},
done: function (e, data) { // Called when the file has completely uploaded
$.ajax({
type: "POST",
url: "{% url 'api_chunked_upload_complete' %}",
data: {
csrfmiddlewaretoken: csrf,
upload_id: data.result.upload_id,
md5: md5
},
dataType: "json",
success: function(data) {
$("#messages").append($('<p>').text(JSON.stringify(data)));
}
});
},
});
})
The problem I have to do with this method is that:
I must first click and then I select the file.
and should be reversed where must first select the file and then click to work.
need councils how to do it please
Create a Button into your template and replace:
data.submit();
by:
$("#SubmitButtonid").off('click').on('click', function () {
data.submit();
});

Rails Flash Notice Via Ajax after completed method

I want to have a flash notice sent back to my view via ajax when my controller successfully completed an uploaded file. However I don't know exactly how to handle the response from the server. What I have below is what I believe is very close to what I want but it's not quite working. Any help would be greatly appreciated. Thank you!
My Controller
def import
begin
Thread.new do
Order.import(params[:file])
ActiveRecord::Base.connection.close
end
rescue
redirect_to root_url, notice: "Invalid CSV file format."
end
format.js { flash.now[:notice] = "Here is my flash notice" }
end
My Ajax Javascript
$(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
},
complete: function(xhr) {
status.html(xhr); //I think I need to change this but not sure what to
}
});
});
def import
begin
Thread.new do
Order.import(params[:file])
ActiveRecord::Base.connection.close
end
rescue
redirect_to root_url, notice: "Invalid CSV file format."
end
#notice = "Here is my flash notice"
end
$(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
},
complete: function(response) {
// replace the response in the div which displays notice
status.html(response)
}
});
});

Wordpress AJAX Call can't access variables from different function

I am having issues with the scope of javascript. I cannot access these variables I define in a function.
All of the variables inside of the document.onload cannot be accessed by the uploadVideo function.
<script type="text/javascript">
document.onload = function() {
q = JQuery;
video_form = q("#wb_bc_video_form");
video_ulid = q("#wb_bc_video_ulid");
file_input = q("#wb_bc_file_input");
video_file = file_input.files[0];
video_size = q("#wp_bc_video_size");
video_time = q("#wp_bc_video_time");
};
function uploadVideo(fileFormField) {
var formdata = new FormData();
formdata.append("video", video_file);
q.ajax(
{
type: "POST",
url: ajaxurl,
beforeSend: function(xhr) {
start = new Date().getTime();
xhr.upload.addEventListener('progress', function(e) {
var loaded = e.loaded / 1048576;
var total = e.total / 1048576;
video_size.innerHTML = loaded.toPrecision(4) + "(MB / " + total.toPrecision(4) + "MB) ";
video_time.innerHTML = (new Date().getTime() - startTime) / 1000 + " Seconds";
if (Math.round(loaded) === Math.round(total)) {
node(video_form, "p", "Processing video... please wait.");
}
}, false);
}
}
).done(function(txt) {
console.log(txt);
}).fail(function(xhr, txt) {
console.log(txt);
}).always(function(xhr, txt) {
console.log(txt);
});
}
</script>

JavaScript 'save as' popup

I am working on one project and I am using JavaScript code to get a screenshot of the website.
The screenshot is working fine and is rendered nicely on the page.
What I want to do is instead of displaying it on the page, I want to show the 'save as' popup window with the screenshot.
Here is the current code which displays the image on the page:
<script type="text/javascript">
var date = new Date();
var message,
timeoutTimer,
timer;
var proxyUrl = "http://html2canvas.appspot.com";
function addRow(table,field,val){
var tr = $('<tr />').appendTo( $(table));
tr.append($('<td />').css('font-weight','bold').text(field)).append($('<td />').text(val));
}
function throwMessage(msg,duration){
window.clearTimeout(timeoutTimer);
timeoutTimer = window.setTimeout(function(){
message.fadeOut(function(){
message.remove();
});
},duration || 2000);
$(message).remove();
message = $('<div />').html(msg).css({
margin:0,
padding:10,
background: "#000",
opacity:0.7,
position:"fixed",
top:10,
right:10,
fontFamily: 'Tahoma' ,
color:'#fff',
fontSize:12,
borderRadius:12,
width:'auto',
height:'auto',
textAlign:'center',
textDecoration:'none'
}).hide().fadeIn().appendTo('body');
}
$(function(){
$('ul li a').click(function(e){
e.preventDefault();
$('#url').val(this.href);
$('button').click();
})
var iframe,d;
$('input[type="button"]').click(function(){
$(iframe.contentWindow).unbind('load');
$(iframe).contents().find('body').html2canvas({
canvasHeight: d.body.scrollHeight,
canvasWidth: d.body.scrollWidth,
logging:true
});
});
$('button').click(function(){
$(this).prop('disabled',true);
var url = $('#url').val();
$('#content').append($('<img />').attr('src','loading.gif').css('margin-top',40));
var urlParts = document.createElement('a');
urlParts.href = url;
$.ajax({
data: {
xhr2:false,
url:urlParts.href
},
url: proxyUrl,
dataType: "jsonp",
success: function(html){
iframe = document.createElement('iframe');
$(iframe).css({
'visibility':'hidden'
}).width($(window).width()).height($(window).height());
$('#content').append(iframe);
d = iframe.contentWindow.document;
d.open();
$(iframe.contentWindow).load(function(){
timer = date.getTime();
$(iframe).contents().find('body').html2canvas({
canvasHeight: d.body.scrollHeight,
canvasWidth: d.body.scrollWidth,
logging:true,
proxyUrl: proxyUrl,
logger:function(msg){
$('#logger').val(function(e,i){
return i+"\n"+msg;
});
},
ready: function(renderer) {
$('button').prop('disabled',false);
$("#content").empty();
var finishTime = new Date();
var table = $('<table />');
$('#content')
.append('<h2>Screenshot</h2>')
.append(renderer.canvas)
.append('<h3>Details</h3>')
.append(table);
addRow(table,"Creation time",((finishTime.getTime()-timer)/1000) + " seconds");
addRow(table,"Total draws", renderer.numDraws);
addRow(table,"Context stacks", renderer.contextStacks.length);
addRow(table,"Loaded images", renderer.images.length/2);
addRow(table,"Performed z-index reorder", renderer.needReorder);
addRow(table,"Used rangeBounds", renderer.support.rangeBounds);
throwMessage('Screenshot created in '+ ((finishTime.getTime()-timer)/1000) + " seconds<br />Total of "+renderer.numDraws+" draws performed",4000);
}
});
});
$('base').attr('href',urlParts.protocol+"//"+urlParts.hostname+"/");
html = html.replace("<head>","<head><base href='"+urlParts.protocol+"//"+urlParts.hostname+"/' />");
if ($("#disablejs").prop('checked')){
html = html.replace(/\<script/gi,"<!--<script");
html = html.replace(/\<\/script\>/gi,"<\/script>-->");
}
// console.log(html);
d.write(html);
d.close();
}
}); });
});
</script>
For that you can use canvas2image.
I guess you could put in your ready function:
ready: function(renderer) {
....
Canvas2Image.saveAsPNG(renderer.canvas);

Categories