Meet with ajax and php

-1

I'm trying to make an app in which the clients bring me the data. The app is made in html, phonegap, and I want to try to understand a bit ajax to be able, through it, to bring the data of my php.

<?php
try {
$conn = new PDO("mysql:host=$servername;dbname=prueba", "root", "");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}

$stmt = $conn->prepare('SELECT * FROM clientes');
$stmt->execute();

while ($row = $stmt->fetch()){
    echo "Clientes: ".$row['nombre'];
}
?>

This php is hosted in a domain and I wanted to bring that data from there. I also read JSON, but I would like you to give me some guidance and learn a little more ... thanks

    
asked by 09.04.2018 в 22:09
source

2 answers

0

I'll leave you a simple example: html:

<html>

<head>

<title>Ejemplo sencillo de AJAX</title>

<script type="text/javascript" src="/js/jquery.js"></script>

<script>
function realizaProceso(valorCaja1, valorCaja2){
        var parametros = {
                "valorCaja1" : valorCaja1,
                "valorCaja2" : valorCaja2
        };
        $.ajax({
                data:  parametros,
                url:   'ejemplo_ajax_proceso.php',
                type:  'post',
                beforeSend: function () {
                        $("#resultado").html("Procesando, espere por favor...");
                },
                success:  function (response) {
                        $("#resultado").html(response);
                }
        });
}
</script>

</head>

<body>

Introduce valor 1

<input type="text" name="caja_texto" id="valor1" value="0"/> 


Introduce valor 2

<input type="text" name="caja_texto" id="valor2" value="0"/>

Realiza suma

<input type="button" href="javascript:;" onclick="realizaProceso($('#valor1').val(), $('#valor2').val());return false;" value="Calcula"/>

<br/>

Resultado: <span id="resultado">0</span>

</body>

</html>

php file (example_ajax_proceso.php):

<?php 
$resultado = $_POST['valorCaja1'] + $_POST['valorCaja2']; 
echo $resultado;
?>

in this simple example you see as from the html send via ajax in a function llamanda (realizarProceso) two parameters (valueCaja1, valueCaja2) these receive our php file (example_ajax_proceso.php) this php receives by means of the post method I do a simple sum of these two values and lsto return the result, you can adapt to your needs ie return queries to the database among others ... luck !! EXAMPLE STEP BY STEP

    
answered by 09.04.2018 / 22:23
source
0

To respond with a json from the data in your database, you can use:

$stmt = $conn->prepare('SELECT * FROM clientes');
$stmt->execute();
$rows = array();

while($r = mysqli_fetch_assoc($stmt)) {
    $rows[] = $r;
}
print json_encode($rows);

With this you get a json formed in the following way:

    {'atributo1TablaClientes':'valorAtributo',
     'atributo2TablaClientes':'valorAtributo',...}

in your case: {'name': 'José', ...}.

That's on the server side. Now, to make a call with ajax to request that json result, you can use JQuery . For example:

$.ajax({
    async:false
    type: "GET",
    // Formato de datos que se espera en la respuesta
    dataType: "json",
    // URL a la que se enviará la solicitud Ajax
    url: "script.php",
})
 .done(function( response ) {

         console.log( "JSON recibido: " + response );

 })
 .fail(function( jqXHR, textStatus, errorThrown ) {
     if ( console && console.log ) {
         console.log( "Error: " +  textStatus);
     }
});

This way you are making a call asynchronously to the server requesting the file 'script.php' (your php file). The processing of the call by the server consists of consulting the database, obtaining the result, giving it a json format and finally returning that json. Then you receive it in the client ( reponse of the function in .done ) and show it by console or you do a process of that data.

    
answered by 09.04.2018 в 22:33