What is the correct way to perform a data insertion with AJAX. I have seen several tutorials, but they are very different and somewhat confusing.
Some use this code
xmlhttp=new XMLHttpRequest();
and another no. Some declare variables for each input they wish to enter, others simply use the id of the form.
And I do not know which is the most efficient way to register.
I have the following form (something simple that I want to start with):
formulario.php
<form id="formulario" action="" method="POST">
<div class="form-group">
<label for="idnombre">Nombre:</label>
<input type="text" class="form-control" id="idnombre" name="namenombre" placeholder="Ingresar Nombre">
</div>
<div class="form-group">
<label for="idapellido">Apellido:</label>
<input type="text" class="form-control" id="idapellido" name="nameapellido" placeholder="Ingresar Apellido">
</div>
<div class="form-group">
<label for="idedad">Edad:</label>
<input type="text" class="form-control" id="idedad" name="nameedad" placeholder="Ingresar Edad">
</div>
<button type="submit" id="button" class="btn btn-default">Registrar</button>
</form>
insert.php
<?php
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "demo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$nombre = $_POST['namenombre'];
$apellido = $_POST['nameapellido'];
$edad = $_POST['nameedad'];
$sql = "INSERT INTO persona (nombre, apellido, edad) VALUES ('$nombre', '$apellido', '$edad')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
In addition to displaying a bootstrap alert:
<div class="alert alert-success">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<strong>Success!</strong> This alert box could indicate a successful or positive action.
</div>
How could I do it? Thanks in advance.