Required no Ajax

Asked

Viewed 664 times

2

I have a code that I need that when submitted, some fields are mandatory to be filled in, type o required html only in Ajax, instead of using Alert as I am using, it uses required as in html. Follow my code below:

function d(func){
			var nome = $('#nome').val();
			var data = $('#data_oco').val();
			var tipo = $('#tipo').val(); 
			var justificativa = $('#justificativa').val();
			if(justificativa==undefined){
				justificativa="";
			}else if(justificativa=="" && tipo!="Falta"){
				alert("Por favor preencha o campo Justificativa!");
			}
			jQuery.ajax({
				method: "get",
				url: "atudel.php",
				data: { "nome": nome, "data": data, "tipo": tipo, "justificativa": justificativa, "func": func },
				success: function(data){
					alert(data);
					window.location = 'editar_ocorrencia.php';
				}
			});
		}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cabesalho_formulario">
				<h1 id="titulo">Controle Geral de Alunos <span>(Edição)</span></h1>
				<h4 id="nome_escola">EEEP Dr. José Alves da Silveira</h4>
				<div id="atualiza" class="modal fade">
					<div class="modal-dialog">
						<div class="modal-content">
							<div class="modal-header">
								<h4 class="modal-title">Atualizar/Deletar Ocorrência</h4>
							</div>
							<div class="modal-body">
								  <br class='b'><label id='just'>Justificativa: </label><br class='b'><textarea required placeholder='Digite a justificativa do aluno...' title='Seja objetivo(a).' rows='5' name = 'obs' cols='50' id='justificativa'></textarea>
				    		</div>
				    		<div class="modal-footer">
								<button type="button" class="btn btn-default" data-dismiss="modal" onclick="d('atualiza')">Atualizar</button>
								<button type="button" class="btn btn-default" data-dismiss="modal" onclick="d('deleta')">Deletar</button>
		             		</div>
		    			</div>
		    		</div>
				</div>

Instead, it looks like this, only in a way that uses jquery inside the js function:

<form method="" action="#">
<div id="cabesalho_formulario">
    				<h1 id="titulo">Controle Geral de Alunos <span>(Edição)</span></h1>
    				<h4 id="nome_escola">EEEP Dr. José Alves da Silveira</h4>
    				<div id="atualiza" class="modal fade">
    					<div class="modal-dialog">
    						<div class="modal-content">
    							<div class="modal-header">
    								<h4 class="modal-title">Atualizar/Deletar Ocorrência</h4>
    							</div>
    							<div class="modal-body">
    								  <br class='b'><label id='just'>Justificativa: </label><br class='b'><textarea required placeholder='Digite a justificativa do aluno...' title='Seja objetivo(a).' rows='5' name = 'obs' cols='50' id='justificativa'></textarea>
    				    		</div>
    				    		<div class="modal-footer">
    								<input type="submit" class="btn btn-default" data-dismiss="modal" value="Atualizar">
    								<input type="submit" class="btn btn-default" data-dismiss="modal" value="Deletar">
    		             		</div>
    		    			</div>
    		    		</div>
    				</div>
            </form>

3 answers

3


You can add a dynamic alert message above the buttons when you give the error specified in your question. If you want another type of alert, you can format the element.

First create an event to remove the alert when the "justification" field is focused:

$("#justificativa").on("focus",function(){
    $(".modal-body .msg_alerta").remove();
});

Then replace the alert with this code:

if($(".msg_alerta").length == 0){
    $(".modal-body").append('<span class="msg_alerta" style="display: block; color: #f30; margin: 10px 0;">Por favor preencha o campo Justificativa!</span>');
}
    return false;

$("#justificativa").on("focus",function(){
	$(".modal-body .msg_alerta").remove();
});

function d(func){
			var nome = $('#nome').val();
			var data = $('#data_oco').val();
			var tipo = $('#tipo').val(); 
			var justificativa = $('#justificativa').val();
			if(justificativa==undefined){
				justificativa="";
			}else if(justificativa=="" && tipo!="Falta"){
        if($(".msg_alerta").length == 0){
				$(".modal-body").append('<span class="msg_alerta" style="display: block; color: #f30; margin: 10px 0;">Por favor preencha o campo Justificativa!</span>');
        }
				return false;
			}
			jQuery.ajax({
				method: "get",
				url: "atudel.php",
				data: { "nome": nome, "data": data, "tipo": tipo, "justificativa": justificativa, "func": func },
				success: function(data){
					alert(data);
					window.location = 'editar_ocorrencia.php';
				}
			});
		}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="titulo">Controle Geral de Alunos <span>(Edição)</span></h1>
				<h4 id="nome_escola">EEEP Dr. José Alves da Silveira</h4>
				<div id="atualiza" class="modal fade">
					<div class="modal-dialog">
						<div class="modal-content">
							<div class="modal-header">
								<h4 class="modal-title">Atualizar/Deletar Ocorrência</h4>
							</div>
							<div class="modal-body">
								  <br class='b'><label id='just'>Justificativa: </label><br class='b'><textarea required placeholder='Digite a justificativa do aluno...' title='Seja objetivo(a).' rows='5' name = 'obs' cols='50' id='justificativa'></textarea>
				    		</div>
				    		<div class="modal-footer">
								<button type="button" class="btn btn-default" data-dismiss="modal" onclick="d('atualiza')">Atualizar</button>
								<button type="button" class="btn btn-default" data-dismiss="modal" onclick="d('deleta')">Deletar</button>
		             		</div>
		    			</div>
		    		</div>
				</div>

  • Okay, but if I hit several times the same button the message appears several times.

  • @Carloshenrique easy to solve. I will update.

  • @Carloshenrique I just added an IF. Abs!

  • Cool. Simple and practical solution ;)

0

Field tooltip with required attribute without a form

The attribute required is triggered when the form is submitted.

Required: This attribute specifies that the user must Fill in a value before submitting a form.

Like the field justification is not linked to a form in its first code, the error message relating to the field will not be displayed.

If your requirement is not to change the HTML, but still you need to display the messages to the required fields, you will have to implement the message on your own, using Javascript, as you will not have the native HTML5 feature without the form.

  • How can I do in Javascript?

  • An idea to use the HTML5 feature: you could create a form virtually (via Javascript) and assign the field to that form (attribute form) and submit the form. I have not tested, but in theory it should work.

0

You can use it like this...

$("#IdDoForm").submit(function(event){
  event.prefentDefault(); //previne que o formulario seja enviado sem estar devidamente preenchido com as regras de validação que você definiu do client-side
 //ADICIONE AQUI SUA FUNÇÃO AJAX.
});

I believe that this way you can define fields as required and force them to be filled!

  • That’s not what I’m looking for, I need to edit the first code I posted, for example... Without using the html tag form. Use required html when clicked on button only so it does not use Alert.

  • Well, without the form you would have to create a js function to validate your fields and not enter the ajax function if your validation function returns false...

  • This, is a function js... that then enter an Ajax function.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.