i am trying to make a delay in my ajax data so the loop become a little bit slower !
and here is my code
$(document).ready(function (){
$('#button').click(function(){
$('#hide').show();
var data = $('#textarea').val();
var arrayOfLines = data.split("\n");
var track = JSON.stringify(arrayOfLines);
var item = "";
var lines = $('#textarea').val().split('\n');
here is the loop
for (var i = 0; i < lines.length; i++) {
item = lines[i];
$.ajax({
type: 'GET',
url: 'cookie.php',
dataType: 'html',
data: 'data=' + item+'&cookie='+track,
success: function(msg){
$('#results').append(msg);
}
});
}
});
Using recursion, you could put in a function sendToServer and pass through the array lines, starting index 0. The function will run from 0 to lines.length. This way you won't DDOS your server :)
If you really need some kind of arbitrary delay, you can include a timeout on the sendToServer function call - in the example it is set to 5 seconds.
var sendToServer = function(lines, index){
if (index > lines.length) return; // guard condition
item = lines[index];
if (item.trim().length != 0){
$.ajax({
type: 'GET',
url: 'cookie.php',
dataType: 'html',
data: 'data=' + item+'&cookie='+track,
success: function(msg){
$('#results').append(msg);
setTimeout(
function () { sendToServer(lines, index+1); },
5000 // delay in ms
);
}
});
}
else { sendToServer(lines, index+1); }
};
sendToServer(lines, 0);
Don't send request to server in for loop. It can take down the server. Instead of what you did , you can do this :
for (var i = 0; i < lines.length; i++) {
item = lines[i];
}
$.ajax({
type: 'GET',
url: 'cookie.php',
dataType: 'html',
data: 'data=' + item+'&cookie='+track,
success: function(msg){
$('#results').append(msg);
}
});
Use like this:
var timeDelay = 5000;
setTimeout(Function, timeDelay);
Related
I want a while loop that iterates if the amount paid is greater than zero. But running the code crashes the browser.
var amount = Number($('#payment1').val());
while (amount > 0){
$.ajax({
type: "POST",
url: baseurl + "collection/getSingleAmort",
data: {'contractid':contractID},
success: function(result){
var data = jQuery.parseJSON(result);
console.log(data);
var amortizationAmount = Number(data['amortization'][i].amortization_amount);
amount = amount -amortizationAmount;
},
error: function (errorThrown){
//toastr.error('Error!', 'Operation Done');
//console.log(errorThrown);
}
});
}
function xyz(amount){
$.ajax({
type: "POST",
url: baseurl + "collection/getSingleAmort",
data: {'contractid':contractID},
success: function(result){
var data = jQuery.parseJSON(result);
console.log(data);
var amortizationAmount = Number(data['amortization'][i].amortization_amount);
amount = amount -amortizationAmount;
if(amount>0)
xyz(amount);
},
error: function (errorThrown){
//toastr.error('Error!', 'Operation Done');
//console.log(errorThrown);
}
});
}
var amount = Number($('#payment1').val());
xyz(amount);
Try something like this. Instead of looping recursion is used.
Add async:false
var amount = Number($('#payment1').val());
while (amount > 0){
$.ajax({
type: "POST",
url: baseurl + "collection/getSingleAmort",
data: {'contractid':contractID},
async:false,
success: function(result){
var data = jQuery.parseJSON(result);
console.log(data);
var amortizationAmount = Number(data['amortization'][i].amortization_amount);
amount = amount -amortizationAmount;
},
error: function (errorThrown){
//toastr.error('Error!', 'Operation Done');
//console.log(errorThrown);
}
});
}
Hi Im trying to upload a 2 file or more, my problem is my progress bar will say 100% because of the small file being uploaded first, then its going back to the percent of the large file.. My question is how can I have a same progress if i have many files being uploaded?
$('body').on('change', 'input:file.gallery_images', function(event)
{
event.preventDefault();
var data = new FormData();
data.append('id', $("#id").val());
var count = $(this)[0].files.length;
$.each($(this)[0].files, function(i, file)
{
data.append('userfile', file);
$.ajax(
{
type: "POST",
url: href+path+"/imagens/store",
data: data,
mimeType: 'multipart/form-data',
contentType: false,
cache: false,
processData: false,
dataType: "json",
xhr: function()
{
var _xhr = $.ajaxSettings.xhr();
_xhr.addEventListener('progress', function (event) { }, false);
if (_xhr.upload)
{
_xhr.upload.onprogress = function(event)
{
var percent = 0;
if (event.lengthComputable)
{
var position = event.position || event.loaded;
var total = event.totalSize || event.total;
percent = Math.ceil(position / total * 100);
}
$("#progress-bar").width(percent + '%');
};
}
return _xhr;
},
beforeSend: function()
{
$("#progress").fadeIn('slow');
$("#progress-bar").width('0%');
},
success: function(data)
{
if(data.gallery)
{
if($(".alert").length > 0)
{
$(".alert").hide('slow').remove();
$("#droppable").show('slow');
}
$('.gallery').fadeTo('300', '0.5', function () {
$(this).html($(this).html() + data.gallery).fadeTo('300', '1');
});
}
$("#progress").fadeOut('slow');
}
});
});
});
Ok, first thing I noticed is that you're adding the file to the 'data' variable inside your $.each... but that means the first POST contains the first image, the second POST contains the first and the second, and so on. I think you should this part inside your $.each:
var data = new FormData();
data.append('id', $("#id").val());
Ok, so, to solve your problem: Before sending anything, go through them and sum their size. You'll also need to store the progress for each file individually, so start it as zero:
var sumTotal = 0;
var loaded = [];
for (var i = 0, list = $(this)[0].files; i < list.length; i++) {
sumTotal += list[i].size;
loaded[i] = 0;
}
Inside your onprogress, instead of comparing the event.position with the event.totalSize, you'll store this position on your 'loaded' array, sum all your array, and then compare it to your sumTotal.
loaded[i] = event.position || event.loaded;
var sumLoaded = 0;
for (var j = 0; j < loaded.length; j++) sumLoaded += loaded[j];
percent = Math.ceil(sumLoaded * 100/sumTotal);
;)
here is my code, and i would like to only display items which has "assistance" as tag and no the other. I really don't know how can i do that.
function displayall(newid){
$.ajax({
url: "https://cubber.zendesk.com/api/v2/users/"+newid+"/tickets/requested.json",
type: 'GET',
cors: true,
dataType: 'json',
contentType:'application/json',
secure: true,
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(""));
},
success: function (data){
var sortbydate = data.tickets.sort(function(a,b){ return new Date(b.created_at)- new Date(a.created_at); });
for (i = 0; i < data.tickets.length; i++) {
var myticket = data.tickets[i];
var mydate = data.tickets[i].created_at;
var created = moment(mydate).format("MM-DD-YY");
var mytitle = data.tickets[i].subject;
var description = data.tickets[i].description;
var status = data.tickets[i].status;
var ticketid = data.tickets[i].id;
var tag = data.tickets[i].tags[0];
$("#mylist").append('<li class="row col-md-12 listing" id="newlist" value="'+ticketid+'" onclick="ticketcontent('+ticketid+","+newid+')">'+ '<span class="class_'+status+' otherClasses">' + status + '</span>'+'<div class="identifiant fixed col-md-2">'+" #"+ ticketid +'</div>'+'<div class="identifiant col-md-2">'+tag+'</div>'+'<div class="identifiant col-md-4">'+mytitle +'</div>'+'<div class="identifiant datefixed col-md-2">'+created+'</div>'+'</li>');
}
}
})
}
and if i do console.log(data.ticket[i]) this is what i get:
What you're looking for is:
var filteredTickets = data.tickets.filter(function(ticket) {
return ticket.tags.indexOf('assistance') >= 0;
});
Try using data.tickets.filter():
data.tickets = data.tickets.filter(function(ticket){
return ticket.tags[0] === 'assistance';
});
ajax i have this snippet:
$("input#search_field").keyup(function(){
var searchText = $("input#search_field").val()
if(searchText.length > 1){
$.ajax({
url: 'search.php',
data: {data: JSON.stringify(searchText)},
type: 'POST',
dataType: "json",
success: function (data) {
if(data.result == 1) {
console.log(data.error);
}
if(data.result == 0) {
console.log(data.error)
}
}
});
}
});
When data.result is = 1, than the returned data.error is an array, in my console:
["string"]
My question is how get every string in my array into a different variable so i can use it later?
Because returned array could be also:
["string","string2","string3"]
Anyone knows?? Greetings!
I split the array as folow
var string = $('#uInput').val();
var array = string.split('\n');
for($i = 0; $i < array.length; $i++){
var dateAndText = array[$i].split(',');
$('#spota').append(dateAndText[0] + '<br>');
$('#spotb').append(dateAndText[1] + '<br>');
Hope this helps.
I have written following function which takes a json data from a url.
function getWeatherDataForCities(cityArray){
var arrAllrecords = [];
var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24*60*60);
for(var i in cityArray){
for(var j=1; j<=2; j++){
var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q="+cityArray[i]+"&dt="+toDaysTimestamp;
$.ajax({
url: jsonurl,
dataType: "jsonp",
mimeType: "textPlain",
crossDomain: true,
contentType: "application/json; charset=utf-8",
success: function(data){
arrAllrecords[j]["cityName"] = data.list[0].city.name;
arrAllrecords[j]["weather"] = data.list[0].weather[0].description;
} });
toDaysTimestamp = toDaysTimestamp - (24*60*60);
}
}
return arrAllrecords; //returning arrAllrecords
}
$(document ).ready(function() {
var cityArray = new Array();
cityArray[0] = "pune";
var arrAllRecords = getWeatherDataForCities(cityArray);
//Print All records returned by getWeatherDataForCities(cityArray);
});
I have written some comments in above code.I have called getWeatherDataForCities function which returns all records from url.I have declared getWeatherDataForCities array in function.I want to add all returned records in that array.I have tried as above but nothing is getting into array.
In console showing j and arrAllrecords are undefined.
How to get all records in array from callback function?
you response will be highly appreciated
Your getWeatherDataForCities function won't return anything because ajax operations are asynchronous. You need to use a callback for that.
Modify your function to accept a callback function:
function getWeatherDataForCities(cityArray, callback){
var arrAllrecords = [];
var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24*60*60);
for(var i in cityArray){
for(var j=1; j<=2; j++){
var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q="+cityArray[i]+"&dt="+toDaysTimestamp;
$.ajax({
url: jsonurl,
dataType: "jsonp",
mimeType: "textPlain",
crossDomain: true,
contentType: "application/json; charset=utf-8",
success: function(data){
arrAllrecords[j]["cityName"] = data.list[0].city.name;
arrAllrecords[j]["weather"] = data.list[0].weather[0].description;
// call the callback here
callback(arrAllrecords);
}
});
toDaysTimestamp = toDaysTimestamp - (24*60*60);
}
}
}
And use it like this:
$(document ).ready(function() {
var cityArray = new Array();
cityArray[0] = "pune";
getWeatherDataForCities(cityArray, function(arrAllrecords) {
// Do something with your data
});
});
You are trying to use the empty array. When fetching the values it will always return you undefined.
var arrAllrecords = [];
arrAllrecords[2]; //undefined
arrAllrecords[2]["cityname"]; //undefined
Better you should use array of objects.
I don't know why you have used variable j. The below code works for me.
var arrAllrecords = [];
function getWeatherDataForCities(cityArray){
var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24*60*60);
for(var i in cityArray){
var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q="+cityArray[i]+"&dt="+toDaysTimestamp;
$.ajax({
url: jsonurl,
dataType: "jsonp",
mimeType: "textPlain",
crossDomain: true,
contentType: "application/json; charset=utf-8",
success: function(data){
arrAllrecords.push({
"cityName" : data.list[0].city.name,
"weather" : data.list[0].weather[0].description
});
if(arrAllrecords.length === cityArray.length) {
callback(arrAllrecords);
}
} });
}
}
function callback(arrAllrecords) {
console.log(arrAllrecords);
}
$(document).ready(function() {
var cityArray = new Array();
cityArray[0] = "pune";
cityArray[1] = "mumbai";
cityArray[2] = "delhi";
getWeatherDataForCities(cityArray);
});