Ajax request is not working

3

I'm having trouble making a request via ajax. The idea is that when checking out the email field a check will be done in the database if there is an equal registered email, but if I use the "dataType: 'json'" it does not work. It only works with "dataType: 'html'". Thanks if anyone can tell me why.

index.php:

<!DOCTYPE html>
<html>
<head>
    <title>Consulta de Email</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type='text/javascript' src="jquery-1.11.1.min.js"></script>
    <script type='text/javascript' src='email.js'></script>
</head>
<body>
   <form id="form1" class="form1" method="post">
        <label>email:</label><br />
            <input type="text" name="email" id="email"/>

            <br /><br />

        <label>senha:</label><br />
            <input type="text" name="senha" id="senha"/>

            <br /><br />

        <input type="submit" value="Salvar Dados" />

    </form>
</body>
</html>

email.js:

$(document).ready( function() {
   $('#email').blur(function(){
           $.ajax({
                url : 'consultar_email.php',
                type : 'POST',
                data: 'email=' + $('#email').val(),
                dataType: 'json',
                success: function(data){
                    if(data.cadastrado == true){
                        alert("email já cadastrado");
                    }
                    else{
                        alert("email não cadastrado");
                    }
                }
           });
           return false;    
   })
});

consult_email.php

<?php
include_once("Classes/dadosDoBanco.php");
$cliente = new DadosCliente();

$email = $_POST['email'];

$sql = "SELECT * FROM cliente"; 
$totalReg = $cliente->totalRegistros($sql);

for($i=0;$i<$totalReg;$i++)
{
    $cliente->verDados($sql, $i);
    $email2 = $cliente->getEmail();

    if($email == $email2)
    {
        $dados['cadastrado'] = true;
    }
    else
    {
        $dados['cadastrado'] = false;
    }
}

echo json_encode($dados);
?>
    
asked by anonymous 23.10.2014 / 01:10

3 answers

3

Dude, the code only works when you hit dataType as html because in your php you're returning html instead of json, I'll explain ...

However, in your php you are returning one:

echo json_encode($dados);

You have not set a Header, if you open your browser's inspector and see http-response-header of your request, you will see that it is returning a content-type: text/html

In order to fix this problem, before its return in php , you should set the header as json, like this:

header('Content-type: application/json');
echo json_encode($dados);
    
23.10.2014 / 17:02
3

The problem is not when sending the data to the server, as jQuery sends the data by default with the application/x-www-form-urlencoded mimeType, which is correct for the POST method.

The dataType is used by jQuery to determine how to handle the result of the request. In your case json should work. Since you have not posted the error that is occurring it is hard to say why.

I'd like to point out that jQuery is wrongly identifying the return type of the request when you put json . Try to set Content-Type in PHP to application/json , since jQuery uses this information to find out what kind of return.

    
23.10.2014 / 03:31
0

As long as you define a value for dataType, the chosen type should be used both for the value sent by ajax in the "date" field and for the value returned by php, which in your case is json.

Try to do this:

$.ajax({
     url : 'consultar_email.php',
     type : 'POST',
     data: {"email":$('#email').val()}, //Alterado como JSON
     dataType: 'json',
     success: function(data){
        if(data.cadastrado == true){
           alert("email já cadastrado");
        }
        else{
           alert("email não cadastrado");
        }
     }
});

Note: Do not forget to return a PHP JSON

    
24.10.2014 / 16:10