Load data in an input from ajax with php and mysql when loading the page?

0

How about, someone could tell me how to load the data of a query in some text boxes from PHP with ajax when loading the html page to add the results in the input. This is what I have until now.

<?php
include '../conexion.php';
$query = "SELECT
  usuarios.usuario,
  usuarios.contrasenia,
  datos_personales.nombre,
  datos_personales.apellido_p,
  datos_personales.apellido_m,
  datos_personales.edad,
  datos_personales.correo,
  datos_personales.telefono,
  datos_personales.celular,
  direcciones.calle,
  direcciones.no_exterior,
  direcciones.no_interior,
  direcciones.colonia,
  direcciones.municipio,
  direcciones.estado,
  direcciones.codigo_postal
  FROM
  usuarios
  INNER JOIN datos_personales ON usuarios.id = datos_personales.usuarios_id
  INNER JOIN direcciones ON datos_personales.id = direcciones.datos_personales_id WHERE usuarios.id = '1'";

  $resultado = $conexion->query($query);

  $datos = new stdClass();

  if($resultado->num_rows > 0){

    $fila = $resultado->fetch_array();

    $datos->usuario = $fila['usuario'];
    $datos->contra = $fila['contrasenia'];
    $datos->nombre = $fila['nombre'];
    $datos->apellido_p = $fila['apellido_p'];
    $datos->apellido_m = $fila['apellido_m'];
    $datos->edad = $fila['edad'];
    $datos->correo = $fila['correo'];
    $datos->telefono = $fila['telefono'];
    $datos->celular = $fila['celular'];
    $datos->calle = $fila['calle'];
    $datos->no_exterior = $fila['no_exterior'];
    $datos->no_interior = $fila['no_interior'];
    $datos->colonia = $fila['colonia'];
    $datos->municipio = $fila['municipio'];
    $datos->estado = $fila['estado'];
    $datos->codigo_postal = $fila['codigo_postal'];

  }


  echo json_encode($datos);

  $conexion->close();

 ?>

$(document).ready(function() {
  $.ajax({
      url: 'cargarDatos.php',
      type: 'POST',
      dataType: 'json',
      data:{id:$('#cambiar').val()}
  }).done(function(respuesta){
    $('#txtUsuario').val(respuesta.usuario);
    $('#txtContra').val(respuesta.contra);
    $('#txtNombre').val(respuesta.nombre);
    $('#txtApellidoP').val(respuesta.apellido_p);
    $('#txtApellidoM').val(respuesta.apellido_m);
    $('#txtEdad').val(respuesta.edad);
    $('#txtCorreo').val(respuesta.correo);
    $('#txtTelefono').val(respuesta.telefono);
    $('#txtCelular').val(respuesta.celular);
    $('#txtCalle').val(respuesta.calle);
    $('#txtNoExterior').val(respuesta.no_exterior);
    $('#txtNoInterior').val(respuesta.no_interior);
    $('#txtColonia').val(respuesta.colonia);
    $('#txtMunicipio').val(respuesta.municipio);
    $('#txtEstado').val(respuesta.estado);
    $('#txtCodigoPostal').val(respuesta.codigo_postal);
  });
});
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="estilos.css">
  <link rel="stylesheet" href="../F/jquery.min.js">
  <link rel="icon" type="image/jpg" href="../recursos/favicon.jpg">
  <title>Document</title>
</head>
<body>
  <br>
  <form action="">
    <h2 class="head">Actualizar datos</h2>
      <div class="contenedorSesion">
        <label for="txtUsuario" class="etiquetas">Usuario:</label>
          <input type="text" name="txtUsuario" id="txtUsuario" value="" required>
        <label for="txtContra" class="etiquetas">Contrase&ntildea:</label>
          <input type="text" name="txtContra" id="txtContra" value="" required>
        </div>
        <div class="contenedorDatos">
          <label for="txtNombre" class="etiquetas">Nombre</label>
            <input type="text" name="txtNombre" id="txtNombre" value="" required>
         <label for="txtApellidoP" class="etiquetas">Apellido paterno:</label>
              <input type="text" name="txtApellidoP" id="txtApellidoP" value="" required>
         <label for="txtApellidoM" class="etiquetas">Apellido materno:</label>
              <input type="text" name="txtApellidoM" id="txtApellidoM" value="" required>
         <label for="txtEdad" class="etiquetas">Edad:</label>
              <input type="text" name="txtEdad" id="txtEdad" value="" required>
         <label for="txtCorreo" class="etiquetas">Correo:</label>
              <input type="text" name="txtCorreo" id="txtCorreo" value="" required>
         <label for="txtTelefono" class="etiquetas">Telefono:</label>
              <input type="text" name="txtTelefono" id="txtTelefono" value="" required>
         <label for="txtCelular" class="etiquetas">Celular:</label>
              <input type="text" name="txtCelular" id="txtCelular" value="" required>
        </div>
        <div class="contenedorDireccion">
         <label for="txtCalle" class="etiquetas">Calle</label>
              <input type="text" name="txtCalle" id="txtCalle" value="" required>
         <label for="txtNoExterior" class="etiquetas">No. Exterior:</label>
              <input type="text" name="txtNoExterior" id="txtNoExterior" value="" required>
         <label for="txtNoInterior" class="etiquetas">No. Interior:</label>
              <input type="text" name="txtNoInterior" id="txtNoInterior" value="" required>
         <label for="txtColonia" class="etiquetas">Colonia:</label>
              <input type="text" name="txtColonia" id="txtColonia" value="" required>
         <label for="txtMunicipio" class="etiquetas">Municipio:</label>
              <input type="text" name="txtMunicipio" id="txtMunicipio" value="" required>
         <label for="txtEstado" class="etiquetas">Estado:</label>
          <input type="text" name="txtEstado" id="txtEstado" value="" required>
        <label for="txtCodigoPostal" class="etiquetas">Código postal:</label>
          <input type="text" name="txtCodigoPostal" id="txtCodigoPostal" value="" required>
      </div>
      <br>
      <input type="submit" value="Guardar cambios" class="btn-enviar">
    </form>
    <script src="main.js"></script>
    <script src="jquery.min.js"></script>
</body>
</html>
    
asked by ebx 25.06.2017 в 03:26
source

1 answer

-1

You are importing the JQuery library after your Javascript file, so all common features of DOM, events, effects and AJAX of this are not yet defined when you want to use them, causing the code to break and not run. You should first import the library and then your Javascript file.

<script src="main.js"></script>
<script src="jquery.min.js"></script>

You are making the request AJAX using the POST method. You should use the GET method to get server information.

$.ajax({
      url: 'cargarDatos.php',
      type: 'GET',
      dataType: 'json',
      data: { id : $('#cambiar').val() }
})

Notes *

You are importing a Javascript script as if it were a CSS file, you should remove this line from your code:

<link rel="stylesheet" href="../F/jquery.min.js">

If you want to create an object with the result of the query, the best alternative is to use mysqli_fetch_object() instead of bringing the result as an array and creating the object manually assigned the value to the corresponding key. Important: the keys will have the same name as the columns in the table.

if($resultado->num_rows > 0){
    $datos = mysqli_fetch_object($resultado);
}

* It is not mandatory to make these changes as they do not help to solve the problem but improve the existing code.

    
answered by 26.06.2017 в 14:48