Ajax post request

0

I am new in JS and I am confused in this, post request by AJAX , I would like to know if my comments are ok and if I am correct because I am confused enough, a post request opens and you are pass 3 arguments, string containing the url to which the request is made, you pass data that are my values of my form thanks to serialize() and saved in data, is it mandatory? You have to give them these two things so that later I can return, no? I will return success which is a function I pass any parameter, in this case data correspond to data? (information that you fill in in the fields in the form of string ). So then I can do datos.saludo and it will give me what I need that is the answer, is that so? Does anyone know any site with a good explanation of what I'm looking for? A thousand thanks

$("form").on("submit", function( event ) { // Porque es on('submit') ???

alert( $( this ).serialize() ) // Crea una string de los elementos del formulario(form object)

event.preventDefault(); // evitar lo que pasaría por default así puedo enviar po ajax ???

// 1. open ajax request post (url im requesting / data from form(serializing) / datos que le pasare)
$.post({
  //2. STRING que contenga la url a la que se hace la petición => JSON => {"saludo":"\u00a1Hola !, vengo desde el servidor.","teléfono":"Tu tel\u00e9fono es el ","horario":"No te llamaremos si no es en horario de ","apunte":"\u00a1Una pena que tengas tan poca satisfacci\u00f3n!"}
  url:'http://cosasdigitales.com/documentacion/validarFormulario.php',
  //3. OBJETO puro o STRING que es enviado al servidor para la peticion(campoNombre=fran&campoTelefono=61999&horario=ma%C3%B1anas&satisfaccion=10&politica=on)
  data: $(this).serialize(),
  //4. FUNCIÓN que retorna la información, la respuesta de ajax (le paso lo que sea, datos sera mi objeto y saludo mi propiedad => datos.saludo), 'success' = KEYWORD!
  //RESPUESTA => ¡Hola fran!, vengo desde el servidor.<br>Tu teléfono es el 61999<br>No te llamaremos si no es en horario de mañanas<br>¡Una pena que tengas tan poca satisfacción!
  success: function(datos) {
    let texto = datos.saludo + '<br>' + datos.telefono + '<br>' + datos.horario + '<br>' + datos.apunte;
    msg(texto, 1);
    console.log(texto);
  }
});
});


function msg(mensajes, tiempo) {

  $('#mensaje').html(mensajes);

  $('#alertas').addClass('visibles');

  setTimeout( function(){
    $('#alertas').removeClass('visibles');
  },tiempo * 1000);
}
        body {
            background: #F2F3EB;
            font-family: 'PT Sans', Arial, sans-serif;
        }
        h1 {
            color: #474544;
            font-size: 32px;
            font-weight: 700;
            letter-spacing: 7px;
            text-align: center;
            text-transform: uppercase;
        }
        h4 {
            margin: 36px 0 10px;
            letter-spacing: 1px;
            font-weight: lighter;
        }
        h4:first-of-type {
            margin: 0 0 10px;
        }
        .underline {
            border-bottom: solid 2px #474544;
            margin: 0 auto 10px;
            width: 80px;
        }
        form {
            overflow: hidden;
        }
        fieldset {
            width: calc(48% - 9px);
            float: left;
            border: 1px solid #eee;
            padding: 5px 20px;
            margin: 0 12px;
            overflow: hidden;
        }
        main {
            border: solid 3px #474544;
            max-width: 768px;
            margin: 60px auto;
            position: relative;
        }
        main *,
        main *:before,
        main *:after {
            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            box-sizing: border-box;
        }
        select {
            width: 100%;
            border: 2px solid #555;
            padding: 10px;
            background: transparent;
        }
        input[type=text],
        input[type=submit],
        input[type=password],
        input[type=range],
        textarea {
            background: none;
            border: none;
            border-bottom: solid 2px #474544;
            color: #474544;
            font-size: 1.000em;
            font-weight: 400;
            letter-spacing: 1px;
            margin: 0em 0 1.875em 0;
            padding: 0 0 0.875em 0;
            text-transform: none;
            width: 100%;
            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            -ms-box-sizing: border-box;
            -o-box-sizing: border-box;
            box-sizing: border-box;
            -webkit-transition: all 0.3s;
            -moz-transition: all 0.3s;
            -ms-transition: all 0.3s;
            -o-transition: all 0.3s;
            transition: all 0.3s;
        }
        input[type=text],
        input[type=submit],
        input[type=password],
        input[type=range],
        textarea {
            -webkit-transition: all .6s ease-in-out;
            -moz-transition: all .6s ease-in-out;
            transition: all .6s ease-in-out;
        }
        input[type=text]:active,
        input[type=text]:focus,
        input[type=password]:active,
        input[type=password]:focus,
        textarea:active,
        textarea:focus {
            outline: none;
            padding: 1em 0 1em 0;
        }
        input[type=range] {
            border: none;
            margin-top: 10px
        }
        textarea {
            height: 85px;
        }
        input[type=submit] {
            background-color: #474544;
            border-top: 2px solid #F2F3EB;
            border-bottom: 2px solid #F2F3EB;
            color: #F2F3EB;
            cursor: pointer;
            font-size: 1.4em;
            padding: 10px 18px;
            margin-top: 25px
        }
        input[type=submit]:hover {
            background-color: #F2F3EB;
            border-top: 2px solid #474544;
            border-bottom: 2px solid #474544;
            color: #474544;
        }
        label {
            color: #555;
            display: block;
            font-size: 14px;
        }
        fieldset:nth-child(6) label {
            width: 50%;
            float: left;
            padding: 5px;
            display: block;
        }
        form > span {
            text-align: center;
            font-size: 52px;
            display: block;
            margin-bottom: 39px;
            font-weight: 00;
            border-bottom: 2px dashed #555;
            padding-bottom: 29px;
        }

        form > label {
            text-align: center;
            float: left;
            width: 100%;
            margin: 20px 0 0px;
        }
        .error {
            border-bottom: 2px dashed red !important;
        }
        #alertas {
            background: grey;
            position: fixed;
            top: 100px;
            right: 0;
            transition: all .5s;
            transform: translateX(100%);
        }
        #alertas.visibles{
            transform: translateX(0);
        }
        #mensaje {
    padding: 12px 10px;
    border: 2px dashed #F2F3EB;
    margin: 10px 35px;
    color: #F2F3EB;
    text-align: center;
    width: 400px;
    font-size: 14px;
}
<!DOCTYPE html>
<html lang="es">

<head>
	<title>Formulario Javascript</title>
	<meta charset="UTF8"/>
	<link rel="stylesheet" type="text/css" href="css/style.css">
</head>

<body>
	<main>
		<div>
			<form action="gestor.php" method="POST">

				<h1>&bull; ¿Hablamos? &bull;</h1>
				<div class="underline"></div>
				<span>&#9743;</span>

				<fieldset>

					<label>Nombre:
						<input type="text" id="campoNombre" name="campoNombre">
					</label>
					<label>Teléfono:
						<input type="text" id="campoTelefono" name="campoTelefono">
					</label>

				</fieldset>

				<fieldset>

					<h4>Horario de contacto</h4>
					<label>
						<input type="radio" name="horario" value="mañanas">Mañanas
					</label>
					<label>
						<input type="radio" name="horario" value="tardes">Tardes
					</label>
					<label>
						<input type="radio" name="horario" value="indiferente">Indiferente
					</label>

					<h4>Nivel de satisfacción con la aplicación</h4>
					<input type="range" min="0" max="100" value="0" id="satisfaccion" name="satisfaccion">

				</fieldset>

				<label>
					<input type="checkbox" id="politica" name="politica"> Acepto la política de datos
				</label>

				<input type="submit" value="Enviar con AJAX">

				<p class="respuesta"></p>

			</form>
		</div>
		<div id="alertas">
			<p id="mensaje">Enviar con AJAX</p>
		</div>
	</main>

	<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
	<script type="text/javascript" src="js/scripts.js"></script>

</body>
</html>
    
asked by francisco dwq 20.12.2017 в 21:11
source

2 answers

0

to make a request with ajax, it is as follows:

//se utiliza $.ajax(), a la cual se le pasa un objeto {}, con la información
$.ajax({
    type:"POST", // la variable type guarda el tipo de la peticion GET,POST,..
    url:"http://ruta", //url guarda la ruta hacia donde se hace la peticion
    data:{nombre:"pepe",edad:10}, // data recive un objeto con la informacion que se enviara al servidor
    success:function(datos){ //success es una funcion que se utiliza si el servidor retorna informacion
         console.log(datos.promedio)
     },
    dataType: dataType // El tipo de datos esperados del servidor. Valor predeterminado: Intelligent Guess (xml, json, script, text, html).
})
  • The variable data is optional to use, it may be the case that you agas a request to the server, and do not send data, but if you recive or not.
  • The function% co_of equal% may not use it, it is optional, the case would be that you make a request to the server where you send data, but do not receive information about it.

more information: link

    
answered by 20.12.2017 в 21:39
0

We will explain post according to the jQuery documentation:

  

Description: upload data from the server using an HTTP request   POST.

These are the parameters, explained, that a POST request may have:

  
  • url

         

    Type: String

         

    A string that contains the URL to which the request is sent.

  •   
  • data

         

    Type: PlainObject or String

         

    A simple object or string that is sent to the server with the request.

  •   
  • success

         

    Type: Function (PlainObject data, String textStatus, jqXHR jqXHR)

         

    A callback function that executes if the request   Is successful. Mandatory if dataType is provided, but may be   null in that case.

  •   
  • dataType

         

    Type: String

         

    The type of data expected from the server.

         

    Default value: Intelligent Guess (xml, json, script, text,   html).

  •   

post in the jQuery documentation

Observations

Since jQuery 3, success is considered obsolete. It is recommended to use done .

Example of a request

HTML (form)

    <form action="archivo.php" method="post" id="idFormulario">
        <div>
            <label for="name">Name:</label>
            <input type="text" id="name" name="user_name">
        </div>
        <div>
            <label for="mail">E-mail:</label>
            <input type="email" id="mail" name="user_mail">
        </div>
        <div>
            <label for="msg">Message:</label>
            <textarea id="msg" name="user_message"></textarea>
        </div>
    </form>

jQuery / Javascript

        var frm=$( "#idFormulario" ); //Identificamos el formulario por su id
        var datos = frm.serialize();  //Serializamos sus datos

        //Preparamos la petición Ajax
        var request = $.ajax({
            url: frm.prop("action"),    //Leerá la url en la etiqueta action del formulario (archivo.php)
            method: frm.prop('method'), //Leerá el método en etiqueta method del formulario
            data: datos,                //Variable serializada más arriba 
            dataType: "json"            //puede ser de otro tipo
        });

        //Este bloque se ejecutará si no hay error en la petición
        request.done(function(respuesta) {
            console.log(respuesta);
            console.log(respuesta.foo); //foo es una propiedad (clave), del json que devuelve el servidor
            //Tratamos a respuesta según sea el tipo  y la estructura               
        });

        //Este bloque se ejecuta si hay un error
        request.fail(function(jqXHR, textStatus) {
            alert("Hubo un error: " + textStatus);
        });

PHP (file.php)

The server responds with a JSON object, which is handled in the done of the Ajax request:

<?php

    $arrRespuesta = array(
        "foo" => "valor de bar",
        "bar" => "valor de foo",
    );

    echo json_encode($arrRespuesta);

?>
    
answered by 20.12.2017 в 21:30