I have a problem with ajax that doesn't seem that common. I found very few other posts with the same issue as mine and tried fixing it with replacing the 'return' with 'echo' in my php file and adding the type property to my ajax request. But no matter what I do, my 'data' is always empty.
When I set the value directly, without ajax, like this:
- var data = <?php
- require "script.php";
- $link = createConnection();
-
- $result = mysqli_query($link, "SELECT * FROM Snippets");
-
- $output = array();
-
- while($row = mysqli_fetch_array($result)) {
- $snippet = new Snippet($row["id"], $row["name"], $row["language"], $row["library"], $row["description"], $row["code"]);
- array_push($output, $snippet);
- }
-
- echo json_encode($output);
- ?>;
Then it's working. But like this:
- $(document).ready(function() {
-
- $.ajax({
- url: "script.php",
- async: false,
- data: {langNav: true}
- }).done(function(data) {
- console.log(data);
The logged value is always empty. First I tried just returning the json_encoded value with the php script and parsing it. But since it's empty it fails. Then I echoed it, so I don't have to parse it, but still, it's empty. I don't know how I can fix this..
script.php:
- if (isset($_POST["langNav"]) && !empty($_POST["langNav"])) {
- getLangNav();
- }
-
- function getLangNav() {
-
- $link = createConnection();
-
- $result = mysqli_query($link, "SELECT * FROM Snippets");
-
- $output = array();
-
- while($row = mysqli_fetch_array($result)) {
- $snippet = new Snippet($row["id"], $row["name"], $row["language"], $row["library"], $row["description"], $row["code"]);
- array_push($output, $snippet);
- }
-
- echo json_encode($output);
-
- }