var Ajax = { send: function(object) { var xhr = new XMLHttpRequest(); xhr.open(object.method, object.url, true); xhr.send(object.data); xhr.onreadystatechange = function() { if (xhr.status != 200) object.error(xhr.responseText); else object.success(xhr.responseText); } } }; window.onload = function() { // grab all forms with 'ajax_form' class var forms = document.querySelectorAll('form.ajax_form'); for (var i = 0; i < forms.length; i++) { forms[i].onsubmit = function(event) { // listener event.preventDefault(); var inputs = this.querySelectorAll('input.active'), query = '', form = this; for (var z = 0; z < inputs.length; z++) query += inputs[z].getAttribute('name') + '=' + inputs[z].value + '&'; query = query.slice(0, -1); console.log('listener launchd'); Ajax.send({ method: this.getAttribute('method'), url: this.getAttribute('url'), data: query, success: function(responce) { window['form_' + form.id]['success'](responce); }, error: function(responce) { window['form_' + form.id]['error'](responce); } }); } } }; form_WriteMe = { success: function(text) { alert('Спасибо за обращение!'); }, error: function(text) { console.log('error handled'); } }; 
 <form id="WriteMe" class="ajax_form" url="/ajax/letter" method="POST"> <input name='test' class="active" value="1"> <input type="submit" value="Отправить"> </form> 

on localhost alert () is repeated twice. There is no sandbox (. Perhaps, the problem is in the jske itself, so I would be wildly grateful for the code review of any nature. // yes, this is still a "bydlokod." Tell me how to do better :) console screen

  • which code is executed twice? - Grundy
  • @Grundy, success methods || error.in particular alert () - Vyacheslav Potseluyko
  • one
    Only alert is executed twice? or completely the entire form submission handler? - Grundy
  • @Grundy, only alert () - Vyacheslav Potseluyko
  • one

1 answer 1

 xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (xhr.status != 200) { object.error(xhr.responseText); } else object.success(xhr.responseText); } } 

The problem was in the function above. Required was to check the status of the request. Namely, readystatechange was called several times - when changing xhr.readyState . That is why it is necessary to check whether the request has been completed (status 4)

Thank you so much @Grundy