📜 ⬆️ ⬇️

Sequential saving of settings using AJAX and jQuery queues

Good afternoon, colleagues!

In one of the projects I needed to save the settings selected by the user (made in the form of checkboxes). Since it was assumed that the settings will change infrequently - I decided to transfer the settings not all at once, but as a sequence of changes. Implementation details under the cut.

I'll start with the formulation of the problem. There is an object that is a set of contact information. The user chooses how to save it, after which the server converts the object into the desired form. But the user may want to save not all the information, but only the part of interest. To do this, he needs to provide a choice - what to save.

You can simply save asynchronous AJAX requests, but in this case there may not be a very pleasant situation when another change went to the server - and somewhere along the way it was stuck, and the user is already trying to save the contact. As a result, he will not get exactly what he expected. The question arises - how to make the changes to be kept strictly in order. For this, I decided to use the queues available in jQuery.
')
Queues in jQuery are used to implement animations and effects, but no one bothers to use them simply to consistently perform the necessary actions. As a result, I got something like this code:

function ajaxQueue(func){ $(document).queue("ajax",func); if($(document).queue("ajax").length == 1) $(document).dequeue("ajax"); } $(".contact input:checkbox") .change(function(){ var $_ = $(this), checked = $_.is(":checked"), $_.attr("disabled","disabled"); ajaxQueue(function(){ $.post("/ajax/check_elem", {name: $_.attr("id"), value: checked}) .error(function(){ $_.val((!checked)?"on":"off"); }) .complete(function() { $_.removeAttr("disabled"); $(document).dequeue("ajax"); }); }); }); 


When switching the checkbox to the queue, a new step is put - the function of sending the change to the server. If the queue was empty, the function is immediately launched for execution (dequeue in the ajaxQueue function). After executing the AJAX request present in the function, the next step is extracted from the queue and executed.

The request to save the contact is also queued and executed after all changes have completed.

 function doAction(link){ $.get(link, function(data){ $('body').append(data); }, 'html'); } $("a.saveButton") .click(function(){ ajaxQueue(doAction($(this).attr("href"))); }); 


PS: In the process of writing this article, I came to the conclusion that it is still easier to transfer all the states of checkboxes in bulk before saving contact (this is a question of why it is useful to write articles :)), but perhaps the scheme I described is useful to someone other tasks.

Source: https://habr.com/ru/post/147432/


All Articles