Ajax query "undefined"

3

My query is as follows, my code is:

$("#sPedido").change(function(){
    var codigo_c=$("#sPedido").val();


    $.post("traertabla.php",  function(datos){
        $("#midiv").html(datos);
        alert(datos.mensaje);
    });
});

The line:

$("#midiv").html(datos);  

shows me the data on the screen without any problem, the result is:

{"mensaje":"hola"}

But, when executing this line:

alert(datos.mensaje);

the alert only shows me: "undefined" .

At what point did I make the mistake?

    
asked by Luis Yul 09.03.2017 в 01:06
source

2 answers

1

For what you comment what you want to do is send a value through a function to make a query to another file and to return a value, you could use the following.

$(function(){
 $("#enviar").click(function(){
  var url = "consulta.php"; 
   $.ajax({
     type: "POST",
     url: url,
     data: $("#valor").serialize(), 
     success: function(data)
       {
          $("#respuesta").html(data); 
         }
        });

      return false; 
  });
});

<div id="respuesta"></div>

within the div you receive the response of the function.

    
answered by 09.03.2017 в 02:14
1

That's because the json that returns you is a text you must convert it.

var datos = $.parseJSON(datos);

should look like this

    $("#sPedido").change(function(){
       var codigo_c=$("#sPedido").val();


       $.post("traertabla.php",  function(datos){
           $("#midiv").html(datos);
           var datosObj = $.parseJSON(datos);
           alert(datosObj.mensaje);
       });
    });

Greetings.

    
answered by 09.03.2017 в 01:24