No Return Json to Ajax

Asked

Viewed 555 times

0

I don’t get Json feedback in Ajax. Any idea what it might be?

Ajax.js

$.ajax({
type: 'POST',
dataType: 'json',
url: "crud/insere.php",
data: dados,
success: function(data) {

    var objeto = JSON.parse(data);
    alert(objeto.id);

 }
 });
 return false;

php insert.

$nome = $_POST['nome'];
$telefone1 = $_POST['telefone1'];
$operadora1 = $_POST['operadora1'];
$telefone2 = $_POST['telefone2'];
$operadora2 = $_POST['operadora2'];
$email = $_POST['email'];
$cidade = $_POST['idCidade'];
$observacao = $_POST['obs'];
$dataCadastro = date('Y-m-d H:i:s');

if(empty($cidade)){
   $cidade = '0';
}

 $select = "INSERT INTO Cliente(nome, telefone1, telefone2, operadora1,   operadora2, 
       email, idCidade, observacao, dataCadastro) 
       VALUES ('$nome', '$telefone1', '$telefone2', '$operadora1',     '$operadora2', '$email', '$cidade','$observacao', '$dataCadastro')";
 $conexao = conexao();           
 $PDO=$conexao->prepare($select);
 $PDO->execute();

 $select = "SELECT id FROM Cliente WHERE email='$email'";
 $PDO=$conexao->prepare($select);
 $PDO->execute();
 $obj = $PDO -> fetch(PDO::FETCH_OBJ);

 $arr = array('id' => $obj->id);
 echo json_encode($arr);insira o código aqui

Complete Code

inserir a descrição da imagem aqui

  • Is the record being entered in the database? Is PHP showing an error? Is the Javascript "data" variable being filled in with the form data correctly? We need more details to help. A good tool for testing Apis is POSTMAN, plugin for Google Chrome. In it you simulate the HTTP call (Ajax) and view the return of the server.

  • The records are recording in the bank, the console does not present any error. I believe it is filling right, you can check on the image of the full source. Some other idea?

  • Just looking at the code I could not think of anything. What I suggest is to install POSTMAN and simulate the call. You can even debug the code in the process.

  • It seems that the POSTMAN plugin address is out, do not load here.

3 answers

0

In this situation just look at what the ajax request is returning. On the page that makes the request go to inspect elements, network (network) and see what is happening with your request (will vary from browser to browser). So you will see if the error is in the request, server, or client.

0

Just one more detail. When you enter dataType: 'json', the callback Success parameter is already a json object, i.e., JSON.parse is unnecessary and can generate an Exception in some cases.

Your JS code can be like this:

$.ajax({
type: 'POST',
dataType: 'json',
url: "crud/insere.php",
data: dados,
success: function(data) {
    alert('funcao success');
    alert(data.id);
 }

});

In your PHP file is indispensable include the json header:

<?PHP
$data = /** seus dados **/;
header('Content-Type: application/json');
echo json_encode($data);

Another important thing is that json_encode() only works with data in UTF-8. That is, if your php file or data in the database is in ISO-8859-1, you need to make a utf8_encode() in each of the strings.

0


Looking at the code quickly I saw something that if it is present in the code that you are running may actually be the cause. It is the last line:

echo json_encode($arr);insira o código aqui

delete after the ;

if this is not present in the code do so:

Change the code for this:

alert('antes ajax'); //ou console.log, como preferir
$.ajax({
    type: 'POST',
    dataType: 'json',
    url: "crud/insere.php",
    data: dados,
    success: function(data) {
        alert('funcao success');
        var objeto = JSON.parse(data);
        alert(objeto.id);

     }
 });
 return false;

to know if there is a syntax error or if the code is not even executed. If you know how to use it, you’d better use the browser’s Debugger instead of the Alerts or console.log.

Then check the apache log or your http server. For apache it is usually in /var/log/apache/error.log. See if there are any php errors there.

after this, in case you don’t use some php Debugger to see where it is failing, put some Snippets in various parts of the code even if it looks bad on the screen to see where the line is that the error occurs.

If this is not enough for you to see where the bug is, when you discover the line, edit the question with the part of the code where the bug is and I will continue to assist you.

  • It was not part of the code: echo json_encode($arr);insert the code here I implemented the line you suggested, and it did Alert('before ajax') and Alert('function Success'), but Alert(object.id) did not. Checking the error logs, I didn’t find anything either. I’m finding it impossible that it doesn’t work. Do you want a copy of the project so you can try to help me? The project is quiet, there is only this source there...

  • 1

    I think I know what it is: remove the line var objeto = JSON.parse(data); and use directly alert(data.id); I think JSON is already being passed directly and parse is not necessary. Test if this is true pf.

  • And then ? It worked ?

  • Man, it worked, working perfectly. Thanks for the help! Hugs.

  • Good. Don’t forget to select one of the answers as accepted.

Browser other questions tagged

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