Receive variable real time ajax

3

Well I'm making a system, and I need to get the variable of a php page every time, so I can work on it on my index.php page.

A friend of mine who understands more about ajax than I passed the following code:

However, I do not know how to pass the values of the variable x in PHP ( loading.php ), to my JavaScript in the page index.php .

The code of my index.php page looks like this:

<html>
    <head>
        <script src="jquery-3.0.0.min.js"></script>
    </head>
    <body>
        <script type="text/javascript">
            $.get("loading.php", function(data) {
                alert(data);
            });
        </script>
    </body>
</html>

How can I do this?

    
asked by anonymous 03.07.2016 / 01:00

2 answers

2

If you want to pass several values I suggest you submit a PHP JSON for JavaScript.

JSON is an organized data string and in PHP you can create JSON of arrays or objects with json_encode($aMinhaVariavel);

To make AJAX catch this data, you have to use echo .

So on the PHP side you can have for example like this:

$array = array('dados A', 'dados B');
echo json_encode($array);

In JavaScript you can use the $.getJSON() of jQuery that already converts the JSON string.

And then you can have it like this:

$.getJSON("loading.php", function(array) {
    alert(array[0]);
    alert(array[1]);
});
    
03.07.2016 / 01:13
2

Well here would be an example of sending data by ajax

  $.ajax({
              var dado= "algumas coisa que queira enviar";
              url: "recebe.php",

              type: 'POST',

              data: dado,

              success: function (data) {
               $("body").html(data);



              }
            });

In the php that receives this data, which in the case is the receive.php, which receives this data through the POST method, it would look like this.

 <?php
    $DadoRecebido= $_POST['dado'];
    echo "deu certo";
?>

And the ajax there would write in the body "It worked," which is the echo that I gave in the php that received the ajax data. I hope I have helped

    
03.07.2016 / 01:12