I have a system that allows an admin to add managers to a campaign from a table. The table looks something along the lines of
<tr>
<td>Checkbox</td>
<td>Last name, First name</td>
<td>Employee Id #</td>
</tr>
Currently, when the "Add Manager" button is hit, I pass the manager's id and a "checked" value using this function
<script>
function addMgrs(){
dict = {}
$('#potentialReviewers tr').each(function() {
var userPid = $(this).find('td').eq(2).text()
var addMgrBox = $(this).find('.addMgrBox').attr('value')
if (addMgrBox == 'checked') {
dict[userPid] = addMgrBox }
// Create the Post request, pass the csrf_token in the header of the request
$.ajax({
url: '/campaign-view/' + '{{ campaign.id }}' + "/",
type: 'POST',
headers: {'X-CSRFtoken': '{{ csrf_token }}'},
data: dict,
dataType: 'json'
})
})
}
</script>
What this does is iterate through the table, build the JSON response and pass it back to the Django view to do the backend processing. My problem is this, for each row it sends a POST request and that drastically increases the time it takes for the process to complete. I'd like it to build the entire dictionary prior to sending the response, but just can't wrap my head around how to do that. Any help would be appreciated.
Alright, so as n1md7 pointed out in the comments, I simply needed to move the AJAX request outside of the loop. Here is what the code block looks like now:
<script>
function addMgrs(){
dict = {}
$('#potentialReviewers tr').each(function() {
var userPid = $(this).find('td').eq(2).text()
var addMgrBox = $(this).find('.addMgrBox').attr('value')
if (addMgrBox == 'checked') {
dict[userPid] = addMgrBox }
})
// Create the Post request, pass the csrf_token in the header of the request
$.ajax({
url: '/campaign-view/' + '{{ campaign.id }}' + "/",
type: 'POST',
headers: {'X-CSRFtoken': '{{ csrf_token }}'},
data: dict,
dataType: 'json'
})
}
</script>
As you can see, I now close the loop prior to making the request and it went from a 4+ minute process to almost instantaneous. Thank you n1md7