Ajax does not return the date of requests

Asked

Viewed 611 times

2

I perform a query with ajax on a php page, the problem is that even asking to return data, the ajax 'date' does not return anything, I give an Alert in the 'date' and it returns me a blank alert, JS code below:

$(function(){

    $(".logando").click(function(event){
        event.preventDefault();

        if($("#email").val() == "" || $("#senha").val() == "") {
            $(".obrigatorio").slideDown(500).css("display","block");
        }
        else {

            var emailUsuario =  $("#email").val();
            var senhaUsuario =  $("#senha").val();

            $.ajax({
                type: "POST",
                url:  "../../controller/Logar_Cadastrar.inc.php",
                data: {email: emailUsuario, senha: senhaUsuario},
                contentType: "application/json; charset=utf-8",
                dataType: "json",

                beforeSend: function() {
                    $(".obrigatorio").slideDown(100).html("Carregando");
                },

                success: function(data) {
                    alert(data);
                }
            })
        }
    })

})

Login block code HTML page:

<form action="../../controller/Logar_Cadastrar.inc.php" method="post">
      <input type="text" name="email" required placeholder="Digite seu e-mail..." id="email"><br>
      <input type="password" name="senha" required placeholder="Digite sua senha..." id="senha"><br>
      <input type="hidden" name="logar">
      <input type="submit" value="Logar-se" class="logando"><br>
</form>

Code of the PHP page:

<?php

require_once('../model/Logar_Cadastrar.class.php');
$logarCadastrar = new Logar;

//Função para logar
if(isset($_POST['logar'])):
    $email = trim(strip_tags($_POST['email']));
    $senha = trim(strip_tags($_POST['senha']));

    $verificar = $logarCadastrar->Consulta("SELECT * FROM CS_usuarios WHERE email = ? AND senha = ?","ss","{$email}","{$senha}");
    if($verificar >= 1):
        // return "Encontrado";
        echo "Encontrado";
    else:
        // return "Não encontrado";
        echo "Não encontrado";
    endif;
endif;
  • 1

    Ask your HTML code and PHP. It is impossible to answer without full code

  • All right, I edited.

  • 3

    Apparently the if(isset($_POST['logar'])) is not being satisfied, so the code within the if will not be executed. A possible solution is to take this if(isset($_POST['logar'])) or switch to a variable logar in ajax: data: {email: emailUsuario, senha: senhaUsuario, logar:sim}

  • Still no return, I’ve even changed the url but it still doesn’t work

  • 1

    The dataType: "json" tells jQuery that your PHP will return JSON. But you are not returning JSON.

  • can give me an example of how to proceed ?

  • Tries with dataType: "html" and see if the php response comes.

  • 1

    Following the @bfavaretto line, keep your Javascript code as is and in PHP you replace the "Echos" by: echo json_encode(['retorno' => 'Encontrado']) and echo json_encode(['retorno' => 'Não Encontrado']) - The solution is for PHP 5.4 or sup. If your PHP is lower, you have to put array() instead of brackets.

  • But first of all you must pass a "log in" parameter in your ajax or remove that IF, as evaluated @Amandalima. The way it is does not pass the IF.

  • Guys thank you very much, I got thanks to the help of all of you, I needed to use the if as Amanda told me, and I had to follow the tip of bfavaretto and otherwise I used json_encode as Marco recommended me, now everything is working perfectly, it was good that I got a good experience with it.

Show 5 more comments

2 answers

0

Your ajax is waiting for a return of the JSON type, in PHP do the following:

echo json_encode("Aqui o que deseja retornar");

0


In order for you to receive the date in json it is necessary that you return a JSON from PHP for it to arrive in your Ajax Success method, so much so that if you run the ajax error function, you will receive an error message:

$.ajax({ type: "POST",
            url:  "../../controller/Logar_Cadastrar.inc.php",
            data: {email: emailUsuario, senha: senhaUsuario},
            contentType: "application/json; charset=utf-8",
            dataType: "json",

            beforeSend: function() {
                $(".obrigatorio").slideDown(100).html("Carregando");
            },

            success: function(data) {
                alert(data);
            }, error: function(data){ console.log(data); });

In order for your code to work, add json_encode to your line that is printing Found. As follows:

require_once('../model/Logar_Cadastrar.class.php');
$logarCadastrar = new Logar;

//Função para logar
if(isset($_POST['logar'])):
   $email = trim(strip_tags($_POST['email']));
   $senha = trim(strip_tags($_POST['senha']));
   $verificar = $logarCadastrar->Consulta("SELECT * FROM CS_usuarios WHERE email = ? AND senha = ?","ss","{$email}","{$senha}");
   if($verificar >= 1):
       // return "Encontrado";
       print_r(json_encode("Encontrado"));
   else:
       // return "Não encontrado";
       print_r(json_encode("Não encontrado"));
   endif;
  endif;

Browser other questions tagged

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