How to use AJAX in a form?

0

Good afternoon,

I think the title is badly expressed, I'll edit it when I think of a more precise question.

Basically I explain my problem:

I have a web page with an information request form. The action of the form is redirected to the same page where this code is:

require_once("../CBSPlatform/assets/classes/class.sistema.php");
require_once("../CBSPlatform/assets/classes/class.solicitudinfo.php");
require_once("../CBSPlatform/assets/functions.php");
require_once("assets/core.php");

$solicitud = new SolicitudInfo;

if (isset($_POST['solicitudinfo'])) {

    $centro = secure($_POST['centro']);
    $curso = secure($_POST['curso']);
    $nombre = ucwords(strtolower(secure($_POST['nombre'])));
    $apellido = ucwords(strtolower(secure($_POST['apellidos'])));
    $fechanacimiento = secure($_POST['fechanacimiento']);
    $poblacion = ucwords(strtolower(secure($_POST['pueblo'])));
    $codpostal = secure($_POST['codpostal']);
    $nombretutor = ucwords(strtolower(secure($_POST['nombretutor'])));
    $apellidostutor = ucwords(strtolower(secure($_POST['apellidostutor'])));
    $email = strtolower(secure($_POST['email']));
    $movil = secure($_POST['movil']);
    $conocen = secure($_POST['conocen']);
    $observaciones = ucfirst(strtolower(secure($_POST['observaciones'])));
    $dia = date("d") . "/" . date("m") . "/" . date("Y");
    $hora = date("G") . ":" . date("i") . ":" . date("s");

    $solicitud->addSolicitud($dia, $hora, $centro, $curso, $nombre, $apellido, $fechanacimiento, $poblacion, $codpostal, $nombretutor, $apellidostutor, $email, $movil, $conocen, $observaciones);

    if($solicitud == true) {
        echo "ggez";

    } else {
        echo "";
    }
    $_POST = array();
};

The class.solicitudinfo has this code:

public function addSolicitud($dia, $hora, $centro, $curso, $nombre, $apellido, $fechanacimiento, $poblacion, $codpostal, $nombretutor, $apellidostutor, $email, $movil, $conocen, $observaciones) {

        $sql = $this->db->prepare("INSERT INTO webla_solicitudinfo (DiaSolicitud, HoraSolicitud, Centro, CursoEscolar, Nombre, Apellidos, FechaNacimiento, 
        Poblacion, CodPostal, NombreTutor, ApellidosTutor, EmailContacto, MovilContacto, ComoConocen, Observaciones) VALUES (:dia, :hora, :centro, :cursoescolar, 
        :nombre, :apellidos, :fechanacimiento, :poblacion, :codpostal, :nombretutor, :apellidostutor, :emailcontacto, :movilcontacto, :comoconocen, :observaciones)");
        $sql->execute(array(':dia'=>$dia,':hora'=>$hora,':centro'=>$centro,':cursoescolar'=>$curso,':nombre'=>$nombre,':apellidos'=>$apellido,
                            ':fechanacimiento'=>$fechanacimiento,':poblacion'=>$poblacion,':codpostal'=>$codpostal,':nombretutor'=>$nombretutor,
                            ':apellidostutor'=>$apellidostutor,':emailcontacto'=>$email,':movilcontacto'=>$movil,':comoconocen'=>$conocen,
                            ':observaciones'=>$observaciones));
        return true;

    }

I want to change everything and do it through AJAX, so that when they send the form automatically go to the database and if it has been inserted correctly, I will return an alert that I will do with the sweetalert plugin confirming that the request has been made correctly.

The problem with what I have done so far (It works correctly) is that if you reload the page once you have sent the form, it is sent again since the data of $ _POST is not deleted. Besides that if someone explained to me how to do it with ajax, I could understand the use of AJAX and be able to use it in the other forms and applications I am doing.

Could someone give me a cable and explain how to do it or tell me a page that explains how to do it?

Greetings.

    
asked by Charlie Clewer 21.09.2017 в 19:52
source

2 answers

1

It is important that you add the jQuery library , without it, it does not work, and sometimes they are small clumsiness that makes one crazy.

If you send your form using a <input type="submit" /> you must replace it with a button .

To get the answer AJAX , we will get it in our box <div id="resultado-mi-formulario"></div>

A possible example:

Form

<html>
<head>
    <!-- Importante la libería jQuery. -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>    
    <!-- AJAX. -->
    <script type="text/javascript">         
        $(document).ready(function() {              
            $(document).on('submit', '#mi_formulario', function() {   
                //Obtenemos datos.          
                var data = $(this).serialize();

                $.ajax({            
                    type : 'POST',
                    url  : 'archivoPHP.php',
                    data : data,
                    success :  function(data) {                 
                        $("#resultado-mi-formulario").html(data).fadeIn();
                    },
                    complete: function(){
                       setTimeout(function() {
                            $("#resultado-mi-formulario").fadeOut();
                       }, 15000);    
                    }
                });         
                return false;           
            });        
        });//End document

    </script>
</head>
<body>
    <form id="mi_formulario" method="POST">
       <input type="text" name="identificador1" />
       <!-- etc... -->
       <button type="submit">Guardar cambios</button>
    </form>
    <div id="resultado-mi-formulario"><!-- Respuesta AJAX --></div>
</body>
</html>

filePHP.php

You still have your code PHP , the only thing you should change is this line if (isset($_POST['solicitudinfo'])) { per if (isset($_POST)) {

Second response

delete.js

$(document).ready(function() {
     //Boton eliminar.
     $(".eliminar").click(function(e) {

         e.preventDefault();
         //Variable con el valor del boton.
         var id = $(this).attr('data-id');   

          //Comprobar alerta ID en pantalla.
         //alert(id);

         //Ajax.
         $.post('eliminar.php', {
            Id:id
         },function(supr) {
            if (supr=='0') {          
               location.href="index.php";
            }
         }); 
    });
});

index.php (Delete button)

In the attribute data-id you must add the id to eliminate with PHP , in my example I put it manually in 1 .

<html>
<head>
   <!-- Importante la libería jQuery. -->
   <script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> 
   <!-- Añado eliminar.js -->  
   <script type="text/javascript" src="eliminar.js"></script>
</head>
<body>
   <a class="eliminar" data-id="1">Eliminar</a>
</body>
</html>

delete.php

<?php
    if (isset($_POST['Id']) {

        //Obtienes el Id desde el boton.
        $id = $_POST['Id'];

        //Continuas con tu código, creas tu sentencia para eliminar la solicitud mediante su ID.

        //Respuesta ajax, va redirigirnos al index o donde une quiera.
        echo "0";

    }

?>
    
answered by 21.09.2017 / 21:08
source
0

Your problem is clear, but I tell you what I understand by the doubts so correct me. I understand that you want to use AJAX to send your form asynchronously. If this is the case, you must capture the submit event of your form and make the request by AJAX. You can do the following:

<form name="form" id="form-ajax" method="post">
   //aquí van tus campos
   <button type="submit">Guardar</button>
</form>

Note that I did not place the action on the form because with JQuery we can capture when the submit is triggered and make the request. There is another way to call a javascript function and make the request but I leave this example that is quite complete:

<form name="form" id="form-ajax" method="post">
   //aquí van tus campos
   <button type="submit">Guardar</button>
</form>

<script>
  $document.ready(fucntion(){
    $('#form-ajax).validate({
      rules: {
       centro: 'required',
       curso: 'required'
       //aquí agregarías las reglas de validación para los campos que desees
     },
     messages: {
       centro: {
         required: 'Campo Obligatorio'
        },
        PI_BSTNK: {
          required: 'Campo Obligatorio'
        }
     },
     errorElement: 'div', //aquí le dices que elemento contendrá el error
    errorPlacement: function (error, element) {
     //aquí agregas la funcionalidad para mostrar el mensaje de error
    },
    submitHandler: function (form) {
      //Si el formulario pasa las validaciones realizas la petición
       var formData = {
            'centro': $('input[name=centro]').val(),
            'curso': $('input[name=curso]').val()
            //aquí guardas todos los valores de los campos del formulario
          };
      $.ajax({
          type: 'POST',
          url: 'archivo.php' //este es el archivo que contiene tu código php
          data: formData,
          dataType: 'json',
          success: function (data) {
           //aquí vendrá la respuesta del archivo php
           if (data) {
             alert("Formulario enviado correctamente");
           }
          },
          error: function (error) {
           //Aquí capturas el error si existe
           alert(error);
          }
    });
  });
</script>

To do this you should in your php file return a json. You can read about the function json_encode , it will be much easier for you to return all the information in this format.

    
answered by 21.09.2017 в 20:24