When there is a progress indicator - ajax

At the server side, response a string after 5 seconds.
There will be a progress indicator for the first 5 seconds, if use the following codes:
function Comet(){
$.getJSON('http://192.168.1.111:3000/c?callback=?', {}, function(response){
toDiv(response);
setTimeout('Comet()', 1000);
});
}
function toDiv(content){
$('#content').append(content + '<br>');
}
$(document).ready(function() {
Comet();
});
But there will be no progress indicator if using the codes:
function Comet(){
$.getJSON('http://192.168.1.111:3000/c?callback=?', {}, function(response){
toDiv(response);
setTimeout('Comet()', 1000);
});
}
function toDiv(content){
$('#content').append(content + '<br>');
}
$(document).ready(function() {
setTimeout('Comet()', 1000);
});
Why?

Related

how to impletement a progressbar which shows me the uploading % with xhr function

let formData2 = new FormData();
formData2.append('_token', vm.response._token);
formData2.append('file', vm.response.content[i].path);
formData2.append('type', vm.response.content[i].type);
$.ajax({
async: false,
url: "page/file/create/upload/"+vm.response.topic_id,
type: "POST",
data: formData2,
cache: false,
dataType: 'json', // what to expect back from the PHP script
contentType: false,
processData: false,
xhr: function() {
var xhr = new XMLHttpRequest();
console.log(xhr);
xhr.open('POST', this.url, false);
if (xhr.open) {
console.log("xhr port open");
}
if (xhr.upload) {
xhr.upload.addEventListener('progress', this.onProgress);
console.log("xhr.upload");
}
return xhr;
// console.log(xhr);
},
success: function (title) {
console.log(" file upload in controller recieves: "+title);
},
})
}
point : 1 > this is a function written in "methods" in a vue page (file uploading practice project with laravel v5.5 + vue 1.0)
point : 2 > from my controller file is uploaded smoothly , has no issue with that.
point :3 > now i want to impletement a progressbar which shows me the uploading %
have tried xhr:function but do not know to fetch the uploading %...
now my xhr function is look like this.. if i get the value of percentage. i will bind that with my progressbar value. but i can not get any upload %
xhr: function() {
var xhr = jQuery.ajaxSettings.xhr();
console.log(xhr);
xhr.open('POST', this.url, false);
if (xhr.open) {
console.log("xhr port open");
}
if (xhr.upload) {
var percentage = 0;
xhr.upload.addEventListener('progress', function(e) {
if(e.lengthComputable) {
percentage = e.loaded/e.total;
percentage = parseInt(percentage * 100);
// Do what ever you want after here
console.log("percentage:"+percentage);
}
}, false);
}
return xhr;
// console.log(xhr);
},
You can try this code below, it works in my side:
xhr : function() {
var xhr = jQuery.ajaxSettings.xhr();
if(xhr.upload) {
if(xhr instanceof window.XMLHttpRequest) {
var percentage = 0;
xhr.upload.addEventListener('progress', function(e) {
if(e.lengthComputable) {
percentage = e.loaded/e.total;
percentage = parseInt(percentage * 100);
// Do what ever you want after here
}
}, false);
}
}
return xhr;
}
Basically, I was using xhr = jQuery.ajaxSettings.xhr() and xhr.upload.addEventListener progress to compute its progress percentage.
Hope this works.
Finally it's working for me. happy me :)
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
console.log("% :" + percentComplete );
$('.myprogress').text(percentComplete + '%');
$('.myprogress').css('width', percentComplete + '%');
}
}, false);
return xhr;
},

How do I fadeIn() table rows with 500ms interval

The below code fetches a piece of html containing a set number of rows. Some of these rows are of class newentry. ( class="newentry" )
I was expecting my code to display them with 1000m delay, but they all appear simultaneously. Why is the setTimeout not waiting between each call to each rows fadeIn()?
$.ajax({
url: "#{Live.live(event.mnemonic)}",
success: function(data) {
var wait =0;
$("#results").html(data);
wait =500;
$(".newentry").each(function(){
setTimeout(function() { $('#'+this.id).fadeIn(); }, wait);
wait += 1000;
});
}
setTimeout('tick()', 1700-wait);
}
});
Try this
$(".newentry").hide();
$.ajax({
url: "#{Live.live(event.mnemonic)}",
success: function(data) {
$("#results").html(data);
i=500;
$('.newentry').each(function(){
setTimeout(function(){delayedShow($(this))},i);
i=i+500;
});
{
}
});
function delayedShow(obj) { obj.fadeIn(); }

Jasmine calling function with ajax returned value

I want to test the "addGroup" function using Jasmine. I get the following error:
Error: Expected spy modifyMyHtml to have been called.at null.
I don't know what is the best way to test the addGroup function. Please HELP.....
var myRecord = {
addGroup: function(groupNumber) {
$.when(myRecord.getHtml())
.done(function(returnedHtml){
myRecord.modifyMyHtml(returnedHtml);
});
},
getHtml: function() {
return $.ajax({url: "myHtmlFile.html", dataType: "html" });
},
// adds options and events to my returned HTML
modifyMyHtml: function(returnedHtml) {
$('#outerDiv').html(returnedHtml);
var myOptions = myRecord.getOptions();
$('#optionsField').append(myOptions);
myRecord.bindEventsToDiv();
},
}
====JASMINE TEST
describe("Configure Record page", function() {
var fixture;
jasmine.getFixtures().fixturesPath = "/test/" ;
jasmine.getFixtures().load("myHtmlFile.html");
fixture = $("#jasmine-fixtures").html();
describe("addGroup", function(){
beforeEach(function() {
var groupNumber = 0;
spyOn(myRecord, "getHtml").andCallFake(function(){
return $.Deferred().promise();
});
spyOn(myRecord, "modifyMyHtml");
myRecord.addGroup(groupNumber);
});
it("Should call getHtml", function() {
expect(myRecord.getHtml).toHaveBeenCalled();
});
it("Should call modifyMyHtml", function() {
expect(myRecord.modifyMyHtml).toHaveBeenCalled(); ==>FAILS
});
});
});
You have to resolve the promise before you return em in your andCallFake.
spyOn(myRecord, "getHtml").andCallFake(function(){
return $.Deferred().resolve ().promise();
});
Btw. you should not test that the function on the object you wanna test are called, but that the html in the DOM are set with the right html
it("Should call modifyMyHtml", function() {
spyOn(myRecord, "getHtml").andCallFake(function(){
return $.Deferred().resolveWith(null, 'returnedHtml').promise();
});
expect($('#outerDiv').html).toEqual('returnedHtml')
});

What is the effect using jquery ajax with auto request?

I have auto request using jquery ajax, I am using this function for detection new chat message & notification case. Sometimes I am thinking again what is the effect if client auto request without finish,
I am worried my server is down because i think this is like DDOS HTTP Throttling.
This is my code
$(function(){
initChat();
});
/*
* initialize chat system
*/
function initChat() {
setTimeout("notifChat()" ,2000);
}
function notifChat() {
$.ajax({
url: '/url',
type:"GET",
data: {id:$("#id").val()},
success:function (data,msg) {
//to do success
}
});
setTimeout("notifChat()" ,2000);
}
My question is
Is possible to down server or make server hung up ?
If it is not better idea any somethink suggestion ?
Note: This is not production ready code, I have not tested it.
A couple weekness of this code:
It does not handle the two http connection limit
strengths:
it can tell if the server return an error (as in server error 404,403,402....)
var failed_requests = 0;
var max = 15;
$(function(){
initChat();
});
/*
* initialize chat system
*/
function initChat()
{
setTimeout(
function()
{
notifChat();
}, 2000)
}
function notifChat() {
$.ajax({
url: '/url',
type:"GET",
data: {id:$("#id").val()},
success:function (data,msg)
{
//to do success
},
complete: function()
{
// either call the function again, or do whatever else you want.
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
failed_requests = failed_requests + 1;
if(failed_requests < max)
{
setTimeout(
function()
{
notifChat();
}, 2000)
}
else
{
alert('We messed up');
}
}
});
}

Get the variable of a json request outside the function (jquery)

I feel pretty stupid asking this but how can I get the variable crdnts outside the function
$(function() {
var coordinates = {
LoadDefault: function() {
$.getJSON('http://api.wipmania.com/jsonp?callback=?', '', function(json) {
var crdnts = json.latitude + "," + json.longitude;
//alert(crdnts);//this works
return crdnts;
});
}
};
alert(coordinates.LoadDefault());//I would like to get the crdnts variable here.
});
or
http://jsfiddle.net/stofke/Lv3YD/
javascript ajax is asynchronous. so you need to use callbacks:
$(function() {
var coordinates = {
LoadDefault: function() {
$.getJSON('http://api.wipmania.com/jsonp?callback=?', '', function(json) {
var crdnts = json.latitude + "," + json.longitude;
call_alert(crdnts); //callback
});
}
};
function call_alert(cr){
alert(cr);
}
coordinates.LoadDefault();
});
You can't. Your Ajax call is asynchronous, so you cannot predict when will it return.
The only thing you can do is doing something with it in the success callback, or set your Ajax to be synchronous if it is a choice (in this case all JS execution will wait until the request is finished).
For example, you can call a function when the Ajax call successfully finished:
$(function() {
var coordinates = {
LoadDefault: function() {
$.getJSON('http://api.wipmania.com/jsonp?callback=?', '', function(json) {
var crdnts = json.latitude + "," + json.longitude;
callSomething(crdnts);
});
}
};
function callSomething(x) {
alert(x);
}
});

Resources