AJAX request is running before the click

2

js is along with html

<!DOCTYPE html>
<html lang="pt-br">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<form id="form">
		<input type="text" name="login" id="login">
		<input type="pass" name="senha" id="senha">
		<input type="submit" name="btn"  id="btn" value="Enviar" >
	</form>
	<h1 id="erro"></h1>
	<script>

		var form = document.querySelector("#form");
		var btn = document.querySelector("#btn");
		var erro = document.querySelector("#erro");
		

		form.addEventListener("click", function(e){
			e.preventDefault();

			if(btn.value == "enviando"){
				return;
			}


			btn.value = "enviando";

			var xhttp = new XMLHttpRequest();
			  xhttp.onreadystatechange = function(){
			    if (this.readyState == 4 && this.status == 200){
			     erro.innerHTML = this.responseText;
			    }
			  };
			  xhttp.open("GET", "registrar.php", true);
			  xhttp.send();
		});
	

	</script>
</body>
</html>
    
asked by anonymous 17.12.2017 / 18:56

2 answers

1

This is happening because the action is being done by clicking on the form (or inside it).

The correct thing is to apply the action when you click the button.

<!DOCTYPE html>
<html lang="pt-br">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<form id="form">
		<input type="text" name="login" id="login">
		<input type="pass" name="senha" id="senha">
		<input type="submit" name="btn"  id="btn" value="Enviar" >
	</form>
	<h1 id="erro"></h1>
	<script>

		var form = document.querySelector("#form");
		var btn = document.querySelector("#btn");
		var erro = document.querySelector("#erro");
		

		btn.addEventListener("click", function(e){
			e.preventDefault();

			btn.value = "Enviando..."

			var xhttp = new XMLHttpRequest();
			  xhttp.onreadystatechange = function(){
			    if (this.readyState == 4 && this.status == 200){
			     erro.innerHTML = this.responseText;
			    }

          //Retorna o valor para "Enviar" após o término da requisição.              
          btn.value = "Enviar";
        };
			  xhttp.open("GET", "registrar.php", true);
			  xhttp.send();
		});
	

	</script>
</body>
</html>
    
17.12.2017 / 19:08
0

In addition I would do the treatments in the fields (masks) as in the example below:

(function ($, window, document, undefined) {
'use strict';

var $form = $('#contact-form');

$form.submit(function (e) {
    // remove the error class
    $('.form-group').removeClass('has-error');
    $('.help-block').remove();

    // get the form data
    var formData = {
        'name' : $('input[name="form-name"]').val(),
        'email' : $('input[name="form-email"]').val(),
        'subject' : $('input[name="form-subject"]').val(),
        'phone' : $('input[name="form-phone"]').val(),
        'message' : $('textarea[name="form-message"]').val()
    };

    // process the form
    $.ajax({
        type : 'POST',
        url  : 'process.php',
        data : formData,
        dataType : 'json',
        encode : true
    }).done(function (data) {
        // handle errors
        if (!data.success) {
            if (data.errors.name) {
                $('#name-field').addClass('has-error');
                $('#name-field').find('.col-lg-10').append('<span class="help-block">' + data.errors.name + '</span>');
            }

            if (data.errors.email) {
                $('#email-field').addClass('has-error');
                $('#email-field').find('.col-lg-10').append('<span class="help-block">' + data.errors.email + '</span>');
            }

            if (data.errors.subject) {
                $('#subject-field').addClass('has-error');
                $('#subject-field').find('.col-lg-10').append('<span class="help-block">' + data.errors.subject + '</span>');
            }

            if (data.errors.subject) {
                $('#phone-field').addClass('has-error');
                $('#phone-field').find('.col-lg-10').append('<span class="help-block">' + data.errors.phone + '</span>');
            }

            if (data.errors.message) {
                $('#message-field').addClass('has-error');
                $('#message-field').find('.col-lg-10').append('<span class="help-block">' + data.errors.message + '</span>');
            }
        } else {
            // display success message
            $form.html('<div class="alert alert-success">' + data.message + '</div>');
        }
    }).fail(function (data) {
        // for debug
        console.log(data)
    });

    e.preventDefault();
});
}(jQuery, window, document));
    
17.12.2017 / 19:33