Request ajax is not working

Asked

Viewed 6,237 times

4

I’m having trouble making a request via ajax. The idea is that when leaving the email field a check is made in the database whether or not there is a registered email equal, but if I use "dataType: 'json'" it does not work. Fuciona only with "dataType: 'html'". I’d appreciate it if someone could 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;    
   })
});

consultar_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);
?>
  • 2

    On the date line: 'email=' + $('#email'). val(). Change to date: {'email': $('#email'). val()}

  • @touchmx the way it was working, what’s giving problem is dataType: 'json', I just switched to dataType: 'html' and it worked right, would tell me the reason?

  • If you give a alert(data.cadastrado) what is the return?

  • the problem is that it does not get to go through the $.ajax part, and does not call the other file.

  • 1

    Your code does not appear to be an error. On your page consultar_email.php let alone echo json_encode( array('cadastrado' => false) ); to see if there are any errors escaping in PHP before returning json.

  • does not present, I have tested this part without calling it through ajax, and it works as should

  • @Vinicius has already tested data: {email: $('#email').val(), instead of data: 'email=' + $('#email').val(), as has been suggested here?

  • @Sergio yes, I’ve tried it, but this way it doesn’t work

Show 3 more comments

5 answers

4


Dude, the code only works when you arrow the dataType as html because in your php you are returning html instead of json, I’ll explain...

no matter how much in your php you are returning a:

echo json_encode($dados);

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

To fix this problem, before your return on php, you should set the header to json, like this :

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

4

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

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

I would guess that jQuery is misidentifying the type of request return when you place json. Try to set the Content-Type in PHP to application/json, because jQuery uses that information to find out what kind of return.

  • I made the code equal to this and had the msm problem, he doesn’t even make the ajax request

  • But what’s wrong? Nothing appears on the Chrome console?

  • makes no mistake

  • The problem is javascript then. If you put an Alert before $.ajax, something appears?

  • appears, but after that no

  • Some error is occurring within $.ajax of Jquery. Use the error option to identify the problem. I suggest you debug via Chrome Developer Tools.

  • I’ll try, thank you!

Show 2 more comments

1

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

Try to do it this way:

$.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

-1

I don’t know if this is your case either but I had a similar problem when I changed the version of PHP in Wamp to 7.2, usually I use PHP5.6 or PHP 7.1, one day I switched to 7.4 to do some testing on a new project and I didn’t pass $.ajax at all, when I remembered that I had changed the PHP version I went back to PHP 7.1 and started working normal again.

-3

Vinicius, I don’t know if you solved your problem after a long time. Try to define variables by placing a conditional if(isset($_POST)) OR if(isset($_GET) without giving the name

Browser other questions tagged

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