Is it correct to have the ajax script in the same html form?

0

Hi, I'm new to Ajax and I want to know if the way of working is correct. I have the ajax script in the same html or should I have it in a separate document?

    <!DOCTYPE html>
<html>
<head>
	<title>insertar datos con ajax</title>
	<script src="jquery-3.2.1.min.js"></script>
</head>
<body>
	<form id="frmajax" method="POST">
		<label>Nombre</label>
		<p></p>
		<input type="text" name="nombre" id="nombre">
		<p></p>
		<label>apellido</label>
		<p></p>
		<input type="text" name="apellido" id="apellido">
		<p></p>
		<label>Usuario</label>
		<p></p>
		<input type="text" name="usuario" id="usuario">
		<p></p>
		<label>password</label>
		<p></p>
		<input type="text" name="password" id="password">
		<p></p>
		<button id="btnguardar">Guardar datos</button>
	</form>
</body>
</html>

<script type="text/javascript">
	$(document).ready(function(){
		$('#btnguardar').click(function(){
			var datos=$('#frmajax').serialize();
			$.ajax({
				type:"POST",
				url:"insertar.php",
				data:datos,
				success:function(r){
					if(r==1){
						alert("agregado con exito");
					}else{
						alert("Fallo el server");
					}
				}
			});

			return false;
		});
	});
</script>
    
asked by Jean Luis Soto Robles 04.11.2018 в 01:39
source

2 answers

2

Friend if your code is something short there is no problem you could also load the jquery script asynchronously adding

 {<script src="jquery-3.2.1.min.js" async="async"></script> 

to load your form super fast. Remember if you insert a style sheet or a javascript inside your html and it is very long that is not recommended but for tests and small websites is super well you also save the classic problem in Google developers PageSpeed that the javascript prevents viewing.

    
answered by 04.11.2018 в 03:06
1

Not bad for tests or simple projects, but for some bigger things it is necessary that your code is separated and does not become Spaguetti (a combination of different languages code in the same file) that is why it is important to have in account some web architectures at the time of work, I attach a page with information about it I hope and serve you.

link

Greetings

    
answered by 04.11.2018 в 02:14