View data via ajax/jquery from the database

Asked

Viewed 560 times

-1

I need to display the data related to users who are in a table in the database, but this data does not receive an input (input in the login form), are not filled. I just want to select the values, and display them on the html page, on the user account page, after the login is validated. I’m using localStorage but I can’t return the values correctly. Because I can’t use . val() in these values, as it would require an input, and these data must be ''captured'' through the user name. I am using Cordova so I can not use php directly in the HTML page, there are requests

All help is welcome!

SELECT `saldo`, `lucro` FROM users WHERE `nomecompleto` = '$nomecompleto';

the balance returns nothing on the html page, and the profit returns Undefined.

follow the ajax/jquery code:

login js.




$(document).ready(function()

        {
            // call api to handle with registration.

            var url = "/log_users.php";

            $(".btn").btn().on("change", function()

            {
                var nomecompleto = $.trim($("#nomecompleto").val());
                var cpf= $.trim($("#cpf").val());
                var password= $.trim($("#password").val());
                var saldo = $(this).val();
                var lucro = $(this).val();

                $("#status").text("Autenticando acesso.");


                var loginString = "nomecompleto="+nomecompleto+"&cpf="+cpf+"&password="+password+"&login=";

                $.ajax(

                {
                    type: "POST", 
                    crossDomain: true, 
                    cache: false,
                    url: url,
                    datatype: 'jsonp',
                    crossDomain: true,
                    data: loginString,
                    success: function(data){
                        if(data == "success") {
                            $("#status").html("Olá" +nomecompleto);
                            localStorage.loginstatus = "true";
                            localStorage.nomecompleto = nomecompleto;
                            localStorage.saldo = saldo; //aqui está o erro...
                            localStorage.lucro = lucro; // e aqui..
                            window.location.href = "welcome.html?id=" +nomecompleto;
                        }
                        else if(data == "error")
                        {
                            $("#status").text("A requisição de login falhou. Tente novamente mais tarde.");
                            alert("A requisição de login falhou. Tente novamente mais tarde." +status);
                            localStorage.loginstatus = "false";
                            window.location.href = "login.html";


                        }
                    }
                });
            });

        $("#nome1").html(localStorage.nomecompleto);
        $("#saldo1").html(localStorage.saldo);
        $("#lucro1").html(localStorage.lucro);

        });

log_users.php

<?php

    include "config.php";

    header("Access-Control-Allow-Origin: *");

    header("Access-Control-Allow-Origin", "Origin, X-Requested-With, Content-Type, Accept");
    header('Content-Type: application/javascript');

    session_start();

    if($_SERVER['REQUEST_METHOD'] == 'POST') {

    $con = mysqli_connect("$server","$user","$pass","$database") or die("connection error");


    $nomecompleto = $_POST['nomecompleto'];
    $cpf = $_POST['cpf'];
    $password = $_POST['password'];
    $saldo = $_GET['saldo'];
    $lucro = $_GET['lucro'];

    if(isset($_POST['register']))

    {   
        $register = mysqli_num_rows(mysqli_query($con, "SELECT * FROM `users` WHERE `email`='$email'"));

        if($register == 0)

        {
            $insert = mysqli_query($con,"INSERT INTO `users` (`email`,`password`) VALUES ('$email','$password')");

            if($insert)
                echo "success";

            else
                echo "error";
        }

        else if($register != 0)

            echo "exist";
    }

    else if(isset($_POST['login']))

    {
        //$login = mysqli_num_rows(mysqli_query($con, "SELECT * FROM `users` WHERE `email`='$email' AND`password`='$password'"));

        $login = mysqli_num_rows(mysqli_query($con, "SELECT `nomecompleto`, `cpf`, `password` FROM `users` WHERE `nomecompleto`='$nomecompleto' AND `cpf`='$cpf' AND `password`= '$password'"));
        $saldo =  mysqli_num_rows(mysqli_query($con, "SELECT `saldo`, `lucro` FROM `users` WHERE `nomecompleto` = '$nomecompleto'"));
        if($login != 0  && $saldo != 0)

            echo "success";

    }    else

            echo "error";

    }

    mysqli_close($con);


?>

html account.

<!DOCTYPE html>

<html lang="pt-br">

<head>

    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>


    <title>Bem vindo à sua conta</title>

    <style>
 body {
     margin: 0;
     padding: 0;
 }



 #background
{
     left: 0px;
     top: 0px;
     position: relative;
     margin-left: auto;
     margin-right: auto;
     width: 100%;
     height: auto;
     overflow: hidden;
     z-index:0;
     background-color: #707070;
    }


</style>

</head>

<div id="background">
<body>

    <header style="text-align: center; background-color: white; height: 80px;">
        <img style="height: 76px; width: 52px; margin-left: -20px; margin-right: 0; left: 26px; float: left; position: relative; top: 2px;" src="logo.png">

<h1>OLÁ

    <div id="nome1">
    </div></h1>
    </header>

    <main style="text-align: center;">

  <article>


     <img style="height: 800px; width: auto;" align="left" src="Retngulo3.png">

     <img style="height: 800px; width: auto;"  align="right" src="Retngulo3.png">

     </article>


     <br><br><br><br><br><br><br><br />
     <p style="color: white; text-align: center; font-size: 14px;">SEU SALDO ATUAL É DE: </p><div style="text-align:center; font-size: 14px; border: 3px solid white; width: 213px; height: 38px; border-radius: 14px; background-color:#707070; display: inline-block;" id="saldo1"><br /></div>

     <br><br><br><br>
     <p style="color: white; text-align: center; font-size: 14px;">COM LUCRABILIDADE DE: </p><div style="text-align: center; display: inline-block; background: url(Elipse1copiar.png); height: 302px; width: 302px; color: white;" id="lucro1"></div>


        <br><br>

    <a href="simular.html" style="margin-left: -20px; left: 30px;float: left; text-decoration: none; width: 120px; color: white; font-size: 14px; display: inline-block; top: 2px;">SIMULAR</a>
     <a href="retirar.html" style="display: inline-block; margin-right: 0; float: right; width: 100px; color: white; font-size: 14px;  top: 2px;">SOLICITAR</a>




    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
   <!-- <script>
    $(document).ready(function(){

        var saldo = $("#saldo").val();
        $.ajax({

            type: "get",crossDomain: true, cache: false,
            dataType: "json",
            url: '/display_info_users.php',
            data: "saldo=" + saldo,
            success: function(data){

                $("#saldo1").html(data.saldo);
            }
        })
    });
</script>-->
    <script type="text/javascript" src="login.js"></script>
    </main>
</div>
</body>
</html>

login.html

<!DOCTYPE html>

<html lang="pt-br">

<head>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" type="text/css"
                    href="sherlockstyle.css"/>

    <title>Login Usuários</title>

</head>

<body>

    <div class="header">
        <img style="height: 80px; width: 40px;" align="left" src="logo.png">
        <h2>Faça o login</h2>
    </div>

    <main id="form" class="btn">

    <div class="input-group">
    <label>Nome completo: </label>

     <input id="nomecompleto" name="nomecompleto" type="text" placeholder="Nome completo..." /> <br/>
    </div>

    <div class="input-group">

    <label>CPF/CNPJ: </label>



    <input id="cpf" type="cpf" name="cpf" placeholder="CPF/CNPJ" /> <br/>
    </div>

    <div class="input-group">

    <label>Senha: </label>



    <input id="password" type="password" name="password" placeholder="Senha..." /> <br/>
    </div>

    <div class="input-group">
    <button id="loginButton" class="btn">Login</button>

    <br>
    </div>
    <div class="input-group">
    <!--<button id="registerButton" class="btn">Registrar</button>-->
    <br>

    <hr>  </div>Status: <p style="text-align: center; color: #3c763d;" id="status"></p></hr>

</main>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

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

     <!--   $(document).ready(function()

        {
            // call api to handle with registration.

            var url = "/log_users.php";

            $("#loginButton").click(function()

            {
                var email= $.trim($("#email").val());
                var password= $.trim($("#password").val());

                $("#status").text("Autenticando acesso.");


                var loginString ="email="+email+"&password="+password+"&login=";

                $.ajax(

                {
                    type: "POST",crossDomain: true, cache: false,
                    url: url,
                    datatype: 'jsonp',
                    crossDomain: true,
                    data: loginString,
                    success: function(data){
                        if(data == "success") {
                            $("#status").html("hello" +email);
                            localStorage.loginstatus = "true";
                            localStorage.email=email;
                            window.location.href = "welcome.html?id=" +email;
                        }
                        else if(data == "error")
                        {
                            $("#status").text("A requisição de login falhou. Tente novamente mais tarde.");
                            alert("A requisição de login falhou. Tente novamente mais tarde." +status);
                            localStorage.loginstatus = "false";
                             window.location.href = "login.html";
                        }
                    }
                });
            });

            $("#registerButton").click(function()

            {
                var email= $.trim($("#email").val());
                var password= $.trim($("#password").val());

                $("#status").text("Configurando conta.");
                var dataString="email="+email+"&password="+password+"&register=";

                $.ajax({
                    type: "POST",crossDomain: true, cache: false,
                    url: url,
                    data: dataString,
                    success: function(data)

                    {
                        if(data == "success")

                            //email.reset();
                           // password.reset();
                            $("#status").html("Cadastro realizado! Usuário registrado no banco de dados.");

                        else if( data == "exist")
                            $("#status").text("Essas credenciais já estão cadastradas no banco de dados. Verifique.");

                        else if(data == "error")
                            $("#status").text("Registro falhou. Tente novamente mais tarde.");
                    }
                });
            });
        });

    </script>-->

</body>
</html>

1 answer

0


The return of ajax post is what you 'printa' on the screen in PHP, for example:

$login = mysqli_num_rows(mysqli_query($con, "SELECT `nomecompleto`, `cpf`, `password` FROM `users` WHERE `nomecompleto`='$nomecompleto' AND `cpf`='$cpf' AND `password`= '$password'"));
$saldo =  mysqli_num_rows(mysqli_query($con, "SELECT `saldo`, `lucro` FROM `users` WHERE `nomecompleto` = '$nomecompleto'"));
if($login != 0  && $saldo != 0)    
   echo "success";
}else {  
   echo "error";    
}

In this snippet you are sending "Success" or "error". These values are what you use in the date object in Jquery.

To pass the values you need to include these values in the return, JSON is a path, first you pass the result to array then print the JSON on the screen for return.

        $saldoSql =  mysqli_num_rows(mysqli_query($con, "SELECT `saldo`, `lucro` FROM `users` WHERE `nomecompleto` = '$nomecompleto'"));

$emparray = array(); //cria o array
if($login != 0  && $saldo != 0) {
   $emparray['resultado'] = "success"; //na resposta você usa este index para  conferir o resultado

   //preenche o array com os resultados
   //entendi que só existe um linha de saldo, se tiver mais use um 'while'
   $emparray['saldo'] = mysqli_fetch_assoc($saldoSql))
} else {
   $emparray['resultado'] = "error"; //na resposta você usa este index para  conferir o resultado
}

echo json_encode($emparray); //print na tela o JSON

In Jquery, you pass Json to object inside ajax Success:

var obj = jQuery.parseJSON( data ); //passa o retorno para objeto
//agora o resultado está no objeto
if(obj.resultado == "success") {
     $("#status").html("Olá" +nomecompleto);
     localStorage.loginstatus = "true";
     localStorage.nomecompleto = nomecompleto; /
     localStorage.saldo = obj.saldo.saldo; //como passamos o resultado para o bjeto saldo usamos desta forma, 'saldo' é o nome da coluna do banco /pelo que entendi 
     localStorage.lucro = obj.saldo.lucro; // e por ai vai
     window.location.href = "welcome.html?id=" + nomecompleto;
   }
   else if(obj.resultado == "error")
   {
      $("#status").text("A requisição de login falhou. Tente novamente mais tarde.");
      alert("A requisição de login falhou. Tente novamente mais tarde." +status);
      localStorage.loginstatus = "false";
      window.location.href = "login.html";
   }

only include in your code.

  • Thank you very much! Cleared the ideas. But is returning undefined, only the name that is displayed correctly. You wouldn’t have to change the data ajax? Since the parameters are passed only from the form, I did not include the saldo and the lucro... I tried using . serialize() but did not return any of the values.

  • checks whether the columns in the bank are the same, and whether the balance really is an object, or array, type balance[0], balance[1] etc.

  • Yes, yes. The names in the columns are the same. And they are arrays, as well as every $_POST method, right? code $nomecompleto = $_POST['nomecompleto'];&#xA; $cpf = $_POST['cpf'];&#xA; $password = $_POST['password'];&#xA; $saldo = $_POST['saldo'];&#xA; $lucro = $_POST['lucro']; Would you not have to include that header: header('Content-Type: application/json'); instead of header('Content-Type: application/javascript'); I saw on the php website, in the first comment: https://www.php.net/manual/en/function.json-encode.php Thanks in advance!

  • And in the part of the parameters for the date, there is a need to include the saldoand the lucro? var saldo = $(this).saldo;&#xA; var lucro = $(this).lucro; Analyzing other codes, I did not notice the inclusion of values that are not filled in the form...

  • Along those lines $emparray['saldo'] = mysqli_fetch_assoc($saldoSql)) you include the search result in the list, test php and see if query is returning, something else does console.log(data) in the browser console it will print the response structure, see if the results are somewhere.

  • All right. Thanks, brother! Hug

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.