I am trying to do a update
without having to refresh the page. But I am trying to learn and understand how to use AJAX
. At the moment I did this, it doesn't work and I don't know how to finish it.
test.php file
<script src="https://kit.fontawesome.com/cbec68f37d.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
$("#change").keyup(function(){
var parametros="change="+$(this).val()
$.ajax({
data: parametros,
url: 'update.php',
type: 'GET',
beforeSend: function () {},
success: function (response) {
$(".salida").html(response);
},
error:function(){
alert("error")
}
});
})
})
</script>
<div class="container w-75 p-5">
<h3 class="mb-4">Activar y desactivar</h3>
<?php
$list = $conn->query("SELECT * FROM proyectos");
while ($fila = $list->fetch()) {
if($fila['pestado'] == '0') {
?>
<p>
Activo <span class="text-primary" id="change"><a href="#"><i class="fas fa-toggle-on"></i></a></span>
</p>
<?php } else { ?>
<p>
Inactivo <span class="text-muted"><i class="fas fa-toggle-off"></i></span>
</p>
<?php } } ?>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</body>
</html>
update.php file
<?php
require_once 'connect.php';
$code = $_GET['@'];
$sql = "UPDATE proyectos SET pestado = '1' WHERE idp = '".$code."'";
$stmt = $conn->prepare($sql);
$stmt->execute();
//echo 'Bien!';
?>
In Activo <span class="text-primary" id="change"><a href="#"><i class="fas fa-toggle-on"></i></a></span>
add the id="change"
, and I know that something is missing that would go in href="#"
, but I don't know what it is due to lack of knowledge.
I would like you to help me understand how to use this because I don't understand it, I mean I don't know how it works AJAX
with Jquery
although my idea is to use only JavaScript
.
Thank you in advance.
Here I have the detailed explanation for exercise and problem posed.
First I am going to start with the corrections to know the reason why it is not working:
1) Active checks are being created with an identifier id=”change” which should not be done, because an id is unique for each tag, HTML 5 rule
2) The event
keyup()
for JQuery is used to listen for the keyboard to release the key. (recommended to useclick()
Change to:3) Change the JQuery event selector to listen to all assets using class type:
Change for:
4) Put the comma at the end of the blocks
})
Change for:
5) It is recommended to place the load of the libraries before the code to be executed so that the sequence of instructions can be interpreted.
6) To update the record, you need to place a record identifier that identifies who the item belongs to, which can be placed in a custom attribute in the label. Example: idp
7) The update idp value is not being passed correctly in the file , therefore the SQL cannot know which record to update to.
$code = $_GET['@'];
Now
$code = $_GET['idp'];
8) A response must be sent when the update is executed in the update.php file, this response can be used as an echo output that will be read by AJAX later.
echo 'Active idp' . $code;
9) This code is useless because the method is used
val()
to obtain value from an input tag and not from a span, it is not passing the parameters correctly to AJAX.10) The post method will be used to pass the data via AJAX, it is safer and more information can be sent in the future.
11) The data that will be sent by Ajax is as follows:
12) The tag “.salida” does not exist to show the result of the code you have to create it.
13) Remove this library payload and use google's JQuery CDN. (it is incomplete and does not run AJAX)
Change to this:
14) Change the method to receive the data in the update.php file
for this other
15) Comment echo syntax for successful connection in file: connet.php
// echo "Connected successfully";
EXPLANATION OF THE CODE IS ALREADY WORKING WITH AJAX:
1) FILE: connect.php
A connection to the database was created through the PDO method, which is object-oriented.
The values are declared in the respective connection variables.
The is used
try { } catch
to capture the connection error in case of failure.The connection is established by creating an instance of the PDO object with the name of $conn .
The parameters of the error exception mode are configured
2) FILE: update.php
This file is a simple routine to update records.
Here the connection is loaded only once
The value of the variable name “idp” is received through a POST method.
We do the record update syntax and the idp value is passed to search for the specific record and the value of the pest field is weighted = 1
We prepare the connection to execute the SQL command and proceed to its execution.
We send a response on the screen to update the record which consists of "Active" + idp number
CODE EXPLANATION:
3) FILE: update.php
The libraries are loaded at the beginning to be able to execute their instructions.
With this instruction it forces to finish the load of the page to execute the jquery or javascript code
Listening for the right mouse button click event for the .chanse class
We capture the value of the corresponding attribute with the label that has the class "change" which is the
We build the structure to pass the data through AJAX which uses the syntax:
Here the variable name will be idp and its value will be obtained by the idp variable that received the value of the attribute with the same name.
2) To change the state of the button we change its attribute by removing the class and then placing a new class. In this case, the button is the grandchild of the label, so two levels of children() are done.
3) Now we execute the AJAX code : passing the corresponding parameters:
Data : (is the data that the other file will receive to work with)
url: (is the path and name of the file)
type: Se usa el método POST por ser mas seguro y practico.
beforeSend: function () {}
Esta funcion se ejecuta antes de realizar la petición de AJAX, es util para aviso para el usuario o validaciones.
success: function (response) {}
Aquí se ha ejecutado satisfactoriamente el AJAX y se recibe la respuesta del archivo a través de la variable responde, en este caso será recibido 'Activo idp'.
Mostrarmos el contenido de la salida a la etiqueta con clase “salida”
Se usa para borrar el contenido de la etiqueta de clase “salida” despues de 2000 ms
En caso de fallo en la comunicación con AJAX se ejecuta este bloque de codigo.
CUERPO DEL ARCHIVO
Se carga una sola vez la conexión.
Se hace la consulta de SQL para todos los registros.
Usamos el while para hacer un recorrido de todos los registro uno a uno, tomando los datos a través de la variable $fila.
Aquí se ha agregado un atributo propio llamado idp el cual va a contener el id que corresponde con ese registro y sirve para referenciarlo cuando se realice el evento del click.
En caso de que pestado tenga otro valor coloca el estado del botón en Inactivo.
Salida que será llevada con el reporte de AJAX
AJUNTO LOS ARCHIVOS:
Archivo connect.php
///////////////////////////////////////////////////////////////////////////// Archivo update.php
/////////////////////////////////////////////////////////////////// Archivo actualizar.php
Imagenes de pantallas Ejecutando el programa:
Imagen de la Tabla de base de datos:
Imagen despues de Correr el Programa:
Resultado y Cambio en la Tabla:
Estrutura de la tabla con la cual se probo el codigo:
I hope to be helpful
This example is functional. I comment each step and leave console.log so you can uncomment and see each response from the server as variables. Just create the database as I leave you written then copy and paste.
As I mentioned before, the idea is to see the information that you are going to update since it would not make sense. The example consists of displaying existing information, printing it for editing, and updating when sending it. Any questions I'm attentive broda :) Create the database. Use mysql!! and ready.
BD: champions
TABLA: equipo
HTML: playerview.html
JQ/AJAX: players.js
PHP QUERIES The data that was requested and sent to the backend.
CONNECTION TO THE DB:bd.php
PHP: players.php (overview of existing data)
PHP: queryUpdate.php (displays the data in the inputs)
PHP: update.php (Updates data once submitted)
CSS: style.css
Parece que quieres una explicacion o flujo de como hacerlo, entoces mira, lo que puedes hacer es obtener el nodo donde fue clickeado, ¿para qué? lo modificaras antes de hacer la peticion o despues de ella, necesitas dicho nodo para unicamente modificar este.
.span
puede seth
,div
o al que le ponesclase
a todos tus registro eid
para que las pierdas al recorrer la lista.si desdea modificar despues de la funcion
puedes mandar mas para
esta es respuesta del servidor, si no tienes, puedes no ponerlo
quiza lo necesitas para una notificacion
JQuery
se ejecuta la peticion internamente, asi nunca se actulizaráo mejor puedes usar esta libreria