Insert data with AJAX

1

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">&times;</a>
    <strong>Success!</strong> This alert box could indicate a successful or positive action.
  </div>

How could I do it? Thanks in advance.

    
asked by Raphael 14.07.2016 в 22:00
source

3 answers

2

What you should use is jQuery to take the form data using the serialize function.

For example:

<form name="miformulario" id="myfor">
  <input type="text" name="elemento1">
  <input type="text" name="elemento2">
  <input type="text" name="elemento3">
  <select name="options">
    <option value="1">choise 1</option>
    <option value="2">choise 2</option>
    <option value="3">choise 3</option>
  </select>
</form>

<script type="text/javascript">
  $('#myform').on('submit', function(e)) {
  e.preventDefault(); // Evitas que haga el submit por default

  var datosFormulario = $(this).serialize();

  $.ajax({
    type: "POST",
    url: "insertar.php",
    data: datosFormulario,
    success: function(data) {
    }
  });
  });
</script>

Y desde el php utilizas la función parse_str para convertir los datos a un array que puedas manejar.

<?php
$params = array();
parse_str($_GET, $params);

echo $params['elemento1'];
echo $params['elemento2'];

?>
    
answered by 14.07.2016 / 22:51
source
1

With this script it's more facial, try it:

function agregaRegistro(){
    var url = 'insertar.php';
    $.ajax({
        type:'POST',
        url:url,
        data:$('#formpost').serialize(),
        success: function(registro){
            $('#formulario')[0].reset();
            $("#cargando").html(data);
        }
    });
    return false;
}

Your form stays like this:

<form id="formulario" action="" onsubmit="return agregaRegistro();" 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>
    
answered by 18.03.2017 в 21:21
1

ajax (); is a function of jquery and jquery is a framework developed in javascript.

  • In order for it to work you need a library, so to speak, it is jaquery.js and there are different versions.
  • As it is in the front-end it helps to send information from a form to a programming language back-end like php and java.
  • Unlike the traditional way you can send or all the information of your form or sections.

example:

   $.ajax({  
                url:"/agregarUsuario.php", //direccion de tu php o java(Utiliza servlets)
                type:'POST', // metodo POST es equivalente a <form method="POST" >
                data:{ParametroIDombre:$("#namenombre").val()},//parametros que resiviras en el php en metodo post $_POST["ParametroIDombre"] <-- obtienes de acuerdo a como lo declaraste en el data no con el name del form
                success: function( resp ) {
                        alert(resp);
//por medios de el atributo id="" puedes pintar información en tu html
 //o puedes crear otras funciones o tomar decisiones  cuando la respuesta fue OK                    

                },
                error:function(error){
                    console.error(error);
                }
            });

        }

I hope you can use the information I provide you can see more details of ajax at: link

    
answered by 30.11.2017 в 03:59