jQuery wait for .each to finish and run ajax call - javascript

I have the following code:
var allChecks = [];
$('input[type=text]').each(function () {
var key = $(this).attr("id");
allChecks[key] = [];
}).promise()
.done(function () {
$('input[type=checkbox]').each(function () {
if (this.checked) {
var ref = $(this).attr('id');
$('.' + ref).each(function () {
allChecks[ref].push({
amount: $("#" + ref).text()
});
});
} else {
allChecks[ref].push({
amount: 0.00
});
}
}).promise()
.done(function () {
$.ajax({
cache: false,
type: 'POST',
data: {
allChecks: allChecks
},
url: '/process',
beforeSend: function () {
console.log("Processing your checks please wait...");
},
success: function (response) {
console.log(response);
},
error: function () {
console.log("Error");
}
});
});
});
My Ajax call runs but I see no data passed as parameters, like if the array allChecks is empty. As JavaScript runs synchronously, I'm expecting that whatever I place after each() will not run until each() is complete, so the Ajax call should run fine and nor give me no data passed as if the array allChecks is empty. Any help or solution on this would be appreciated. Thanks.

Related

Ajax is not aborting when stop button is clicked

I have this code, and when the stop button is clicked, I need to stop the ajax, but for some reason ajax is not aborting.
var started = false;
$(document).ready(function () {
$('#start').click(function () {
var count = $("#names").val();
var line = count.split("\n");
started = true;
line.forEach(function(value, index) {
setTimeout(
var ajaxCall = $.ajax({
url: url,
type: 'GET',
data: someData,
success: function(result) {
//some works here
}
});
$('#stop').click(function () {
ajaxCall.abort(); //abort Ajax
$('#check').attr('disabled', false);
$('#stop').attr('disabled', 'disabled');
})
}, 2000 * index);
});
});
});

How to execute a function to update a json source

I have a Leaflet map that show some weather data from a Json source. I have already a function that update the data every x minutes by a setInterval function.
setTimeout(function () {
refreshId = setInterval(function () {
$.ajax({
method: 'get',
dataType: 'text',
url: 'myURLfile.json',
success: function (data) {
if (data) {
markers = [];
var withoutMarkers = data.slice(10);
markers = JSON.parse(withoutMarkers);
//console.log(markers);
replaceMarkers(currentFactor);
}
},
error: function (err) {
console.error('there is not date for today.', err)
}
})
}, 300000);
},10000)
}
What I would to do now is assign this funtion to a button to execute the refresh fuction manually.
Something like
L.easyButton( 'fas fa-cloud-sun-rain', function(){
myfunction()
}, 'Refresh', {
position: 'topright'
})
But I don't understand what I have to call exactely to do it.
Factor your fetch code out of setInterval and use your newly made function both in setInterval and your button definition.
Something like
function fetchData() {
$.ajax({
method: 'get',
dataType: 'text',
url: 'myURLfile.json',
success: function (data) {
if (data) {
markers = [];
var withoutMarkers = data.slice(10);
markers = JSON.parse(withoutMarkers);
//console.log(markers);
replaceMarkers(currentFactor);
}
},
error: function (err) {
console.error('there is not date for today.', err)
}
});
}
// setup your interval
setInterval(fetchData, 300000);
// setup your button
L.easyButton( 'fas fa-cloud-sun-rain', fetchData, 'Condizioni', {
position: 'topright'
})

Why do the ajax requests fire multiple times

I have a form inside a modal that either saves a memo when one button is clicked or deletes it when another is clicked. The items get saved/deleted but the request count multiplies with each click. I'm getting 4 of the same request etc. How do i stop this. do i have to unbind something?
$('#modal').on('show.bs.modal', function (e) {
var origin = $(e.relatedTarget);
var memoId = origin.attr('data-id');
$('#modal').click(function(event){
if($(event.target).hasClass('memo-save')) {
event.preventDefault();
var memoText = $(event.target).parent().parent().find('textarea').val();
var memo = {
memo: memoText,
id: memoId
}
$.ajax({
type: "POST",
url: '/memos/add-memo?memo=' +memo+'&id=' + memoId,
data: memo,
success: function (result) {
$(event.target).toggleClass('active').html('Memo Saved');
}
});
} else if($(event.target).hasClass('memo-delete')) {
event.preventDefault();
var memoText = "";
var memo = {
id: memoId
}
$.ajax({
type: "POST",
url: '/memos/remove-memo?id=' + itemId,
data: memo,
success: function (result) {
$(event.target).toggleClass('active').html('Memo Deleted');
}
});
}
});
});
you can move the $('#modal').click outside the $('#modal').on('show.bs.modal' that way it will not re-add the listener each time the modal is shown

How to make a loading bar on single table when they make a request data?

$(document).ready(function () {
setInterval(function () {
$('#RoomBlock').children('div').each(function () {
ShowRoom($(this).attr('id'));
});
}, 10000);
function ShowRoom(id) {
$.ajax({
type: "POST",
url: "/localhost/GetData/" + id
success: function (response) {
if (response != null) {
$('#' + id).empty();
$('#' + id).append(response);
} else {
alert("null");
}
},
error: function (response) {
alert("error!");
}
});
})
i have 5 table and they always fetch data from server for several time, success times for every table is different, i want to put some loading bar on every table when they make a request. is there any way to do that with javascript ?
the one that make confuse is how to know that the first table is make a request and still while the other one was done.
try something like below
$(document).ready(function () {
setInterval(function () {
$('#RoomBlock').children('div').each(function () {
ShowRoom($(this).attr('id'));
});
}, 10000);
function ShowRoom(id) {
/* Add some loader here (bar or image)*/
var loaderHtml = "<div id='loader_'+id>_____Add your loader code here_____</div>";
$('#' + id).append(loaderHtml);
$.ajax({
type: "POST",
async: false,
url: "/localhost/GetData/" + id
success: function (response) {
if (response != null) {
$('#' + id).empty();
$('#loader_'+ id).remove();
$('#' + id).append(response);
} else {
alert("null");
$('#loader_'+ id).remove();
}
},
error: function (response) {
alert("error!");
}
});
})

Call view by dropdownlist value

i'm having a html.dropdownlist where ochange event is speified. i need to call a controller action method using ajax or javascript function and returns view based on the filter value
I try someting like following which is not working,why?
<script type="text/javascript">
$(function() {
$('#Projcbo1').change(function () {
// fetch the newly selected value
var selectedValue = $(Projcbo1).val();
// send it as an AJAX request to some controller action
$.post('#Url.Action("ProjCBOItemSelected")', { value: selectedValue }, function (result) { $("#resultContainer").html(result); });
});
});
</script>
You can use the following to achieve that.
<script>
$(function() {
$('#ddl').change(function () {
$.ajax({
url: '#Url.Action("actionname", "controllername")',
type: 'GET',
dataType: 'html',
data: {Id: $(this).val() },
success: function (result) {
$('#div_to_load_the_content').html(result);
},
error: function (error) {
},
});
});
});
</script>
Let me know if it helps.

Categories

Resources