Ajax and dataType JSON

Asked

Viewed 5,249 times

0

When I do so, the return is a parsererror.

$.ajax({
    type: "GET",
    url: "servicos.php",
    data: "id=1",
    dataType: 'json', ==========================> Essa linha bem aqui
    success: function(retorno,status){
    // retorno = JSON.parse(retorno);

    $("#tudo").html(retorno);
},
error: function(retorno,erro){

    $("#tudo").html(retorno.responseText);

}
});

Only gives Success if remove this line or leave as 'text'.

However (still leaving dataType: 'json'), when I ask to return the error of this fomra:

error: function(retorno,erro){

    $("#tudo").html(retorno.responseText);

}

I get the same Success result without "dataType: 'json'"

I didn’t understand that.

  • What is this PHP returning? Are you sure it is a valid JSON?

  • 2

    Another thing is that jQuery tries to parse json alone, even without declaring the datatype. So it could just be that, the return argument is already an object, you can use directly from your callback.

  • the return looks something like this: [{"id":"1","name":"Juca","status":"1"}]

  • Friend I tested here and it worked,just by replacing dataType by datatype

1 answer

1

If you simply copy and paste your request ajax, in thesis, it will work. But you should consider the following: I noticed that your file php services. returns an array of objects:

the return is something like this: [{"id":"1","name":"Juca","status":"1"}]

So when you "receive" the matrix/array (in the success), should display the response so:

$("#tudo").html(retorno[0].nome);

retorno[0] will reference the first object in the matrix/array returned in the request;

.nome will reference the attribute nome on the returned object;

See the difference in usage:

// Quando o json retornado é array: [{"id":1, "nome":"juca", ...}]
$("#tudo").html(retorno[0].nome);

// Quando o json retornado é objeto: {"id":1, "nome":"juca", ...}
$("#tudo").html(retorno.nome);

Normally a matrix is used/array when receiving more than one object:

json = JSON.parse('[{"id":0,"nome":"jao","status":1},{"id":1,"nome":"juca","status":1},{"id":2,"nome":"ze","status":0}]');

console.log(json[0].nome);  //jao
console.log(json[1].nome);  //juca
console.log(json[2].nome);  //ze

In my tests I used jQuery 1.12.4.

I went up a project based on that answer in my Github/Lipespry/sopt-ajax-e-datatype-json

Browser other questions tagged

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