Answer the question
In order to leave comments, you need to log in
Best way to avoid duplicating code for modifying an AJAX form when submitting it (preventing input, preventing hitting the submit button...)?
Hello. Can you please tell me the best way to avoid duplicating code for modifying an AJAX form on submit and undoing those changes after submit.
I have a lot of AJAX forms. When sending such a form, you need to make a ban on re-sending, on entering characters, etc. - until a response from the server arrives. What am I doing now. I wrote a function where the submitted form is passed. It searches for a button to send and puts a block, adds a class to the form (so that it cannot be sent in other ways), and puts a block on the input fields. After the response arrives from the server, another function is called, the inverse of this one - to cancel the lock, remove the class, etc. But it turns out that in each function for submitting an AJAX form, I have to duplicate two lines - for calling the blocking function and for calling the unblocking function. And I, as I already wrote, have a lot of AJAX forms. Yes, and this approach looks somewhat primitive.
Is it possible to write this circuit better? For example, all similar AJAX forms have a certain class. On submitting a form with this class, a handler is hung up, in which its fields and the possibility of sending are blocked. Next, the function is called, in fact, sending to the server and receiving a response from the server using the information that came in (AJAX function. Which depends on which form is sent. For example, the data-func attribute with the name of the function for the form being sent).
Here's how to make waiting for a response from the server? Basically, it's waiting for AJAX to execute.
Answer the question
In order to leave comments, you need to log in
$(form).submit(function(){
var that = $(this);
var url = that .attr('action');
var method = that .attr('method');
$.ajax({
type: method,
url: url,
data: that .serialize(),
beforesend: function(){
that.attr('disabled','true');
},
success: function(){
},
complete: function(){
that.attr('disabled','false');
}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question