How to display PHP data in ajax?

1

I am trying to load the PHP data on the page when it finishes loading, but it does not show me the data, here is a simple example:

<?php
   $datos = new stdClass();
   $datos->mensaje = "hola";
   header('Content-type: application/json; charset=utf-8');
   $json= json_encode($datos);

   echo $json;
?>

that is tomardatos.php, here the ajax code

window.onload = function () {
    $.getJSON("Tomardatos.php", exito);
};

function exito(data) {

    alert(data.mensaje);
}

I saw that .getJSON is to get data from the server, but it does not work, I hope your help, thanks:)

    
asked by Shum 28.07.2018 в 03:27
source

1 answer

3

You must call the jQuery library to work, try this:

<script
src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>

<script>
window.onload = function () {
 $.getJSON("Tomardatos.php", exito);
};

function exito(data) {
  alert(data.mensaje);
}

</script>

getJson is not a native function of javaScript. I tried it and threw the alet with "hello", I hope it works for you.

    
answered by 28.07.2018 в 04:03