1

I have this ajax code:

$.ajax({
    type: "POST",
    url: "inc/ajax.php",
    data: $('#form-responder').serialize(),
    success: function (data) {
        console.log(data); // prints: {"sucesso":"true", "mensagem":"Correta: A pulseira de identificação se aplica a todos os pacientes, sem exceção. ", "index_proxima":"2"}
        //var sucesso = eval(data.sucesso);
        var mensagem = data.mensagem;
        alert(mensagem); // shows: undefined
    }
});

I need to get some object values but all of them are returning 'undefined', what is wrong with that? I used to do data.something and always worked before, maybe something with this jQuery version 2.1.3 ?

Francisco Souza
  • 806
  • 15
  • 38
  • 1
    You need to specify `dataType: 'json'` in your ajax call if you 're returning json data. – kidA Mar 04 '15 at 19:37
  • Try add `async: false` or check link: http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call – Miloslav21 Mar 04 '15 at 19:44

2 Answers2

2

You need to use parseJson()

JsFiddle

data = jQuery.parseJSON( data);
alert(data.mensagem);
Romain Derie
  • 516
  • 7
  • 17
1

"mensagem" is string key, you should use it with array key format like so: data['mensagem'].

var data = {"sucesso":"true", "mensagem":"Correta: A pulseira de identificação se aplica a todos os pacientes, sem exceção. ", "index_proxima":"2"};

$('input').val(data['mensagem']);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input />
Tomanow
  • 7,247
  • 3
  • 24
  • 52