Andrei Dobai
Andrei Dobai

Reputation: 33

How do I send a variable from PHP to javascript using Ajax?

So I have a PHP file where I fetch the data from the database. I also have a JavaScript file where I make an ajax request. Everything is okay, but I'd like to stop the JSON from going on my web page when I echo it. I just want to work with the JSON in Javascript. Here is my code:

Javascript:

$(document).ready(function() {
  var url = "../../DB/get-data.php";
    $.ajax({
      type: "POST",
      url: url,
      success: function(data){
         var mydata = jQuery.parseJSON(data);
         console.log(mydata);
      }
    });
});

PHP:

$sql = "SELECT * FROM animals ORDER BY age DESC";
$result = $conn->query($sql);
$animals = [];
while($row = $result->fetch_assoc()) {
  $animal = new Animals($row['name'], $row['species'], $row['color'], $row['age']);
  array_push($animals, $animal);
}
echo json_encode($animals);

Upvotes: 1

Views: 57

Answers (1)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You could separate the two files, the file that gets the data without the echo :

get-data.php

$sql = "SELECT * FROM animals ORDER BY age DESC";
$result = $conn->query($sql);
$animals = [];
while($row = $result->fetch_assoc()) {
  $animal = new Animals($row['name'], $row['species'], $row['color'], $row['age']);
  array_push($animals, $animal);
}

And another file for the JSON result that implements the echo statement and includes the first one :

get-data-json.php

include 'you_path_here/get-data.php';

echo json_encode($animals);

Then the URL variable in your JS code should call the JSON route like :

var url = "../../DB/get-data-json.php";

Upvotes: 1

Related Questions