0

Is this the right way to retrieve data from mysql using jquery? The php side is working fine ($data gets printed onto the page) but jquery doesn't seem to be receiving the variable at all.

Besides that, is there a way to get the jquery function to run after the page AND after the google maps initMap() function has finished loading? Is it possible to include jquery code inside a standard javascript function?

admin.php

<?php
require 'private/database.php';

$sql = "SELECT * FROM latlng";
$result = mysqli_query($conn, $sql);

$data = array();
if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        $data[] = $row;
    }
}
echo json_encode($data);

?><!DOCTYPE html>
<html>
  <head>
    <link type="text/css" rel="stylesheet" href="css/admin.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script type="text/javascript" src="js/admin.js"></script>
    <script type="text/javascript" src="js/maps.js"></script>
    <script defer 
      src="https://maps.googleapis.com/maps/api/js?key=(mykey)&callback=initMap&libraries=places&v=weekly"
    ></script>
  </head>
  <body>
    <div id="map"></div><br>
  </body>
</html>

What I've tried js/admin.js

$(document).ready(function() {
    $.ajax({
        url: '../admin.php',
        method: 'post',
        dataType: 'json',
        success: function(data) {
            console.log(data);
        }
    })
});

I received a "404 Not found" error in the console

5
  • 1
    You are generating a map with data from the db? You do not need to use ajax here ( just create a js variable with the PHP data ) but if you do decide to use ajax you must only send back the data - not the entire page which is what appears to be happening above. Use a logic test to check that you have a POST request ( from ajax request ) and process db query within that block - and use exit or die to send the data back Commented Dec 28, 2020 at 11:06
  • To get the ajax request to run after the initMap function has run - call it from within initMap at the end Commented Dec 28, 2020 at 11:07
  • 1
    If you get a 404, then you've added the wrong URL. Instead of having relative paths, like ../admin.php, use absolute paths instead. url: '/path/to/admin.php'. When starting the path with a /, it will be from the document root. The problem with relative paths are that they are relative from the page you're on, not from the actual file location. Commented Dec 28, 2020 at 11:08
  • As you appear to be targeting ( or trying to target ) the same page as the map is to be displayed upon you can alternatively use location.href rather than ../admin.php and it should be ok. The same caveats for sending an ajax request to the same page apply though Commented Dec 28, 2020 at 11:15
  • @ProfessorAbronsius Thanks for the heads up! That sounds a lot more efficient. How should I go about passing the variable? Commented Dec 28, 2020 at 11:37

1 Answer 1

2

The 404-Error indicates that you are using a wrong URL in your jQuery code to get the data. Try to enter not just the filename but the whole URL like https://example.com/admin.php for the url parameter.

Besides your problem getting the data via jQuery, what happens when you open admin.php directly in your browser? Are you getting the $data AND your HTML Code? If thats the case I would recommend you to wrap the whole PHP-Code inside an if-statement:

if($_SERVER['REQUEST_METHOD'] === 'POST'){
    header('Content-Type: application/json');
    require 'private/database.php';

    $sql = "SELECT * FROM latlng";
    $result = mysqli_query($conn, $sql);

    $data = array();
    if (mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            $data[] = $row;
        }
    }
    die(json_encode($data));
}
else{ ?>
<!DOCTYPE html>
<html>
  <head>
    <link type="text/css" rel="stylesheet" href="css/admin.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script type="text/javascript" src="js/admin.js"></script>
    <script type="text/javascript" src="js/maps.js"></script>
    <script defer 
      src="https://maps.googleapis.com/maps/api/js?key=(mykey)&callback=initMap&libraries=places&v=weekly"
    ></script>
  </head>
  <body>
    <div id="map"></div><br>
  </body>
</html>
<? } ?>

Now, if its a POST-Request like from your js, the PHP will return the data as JSON. Also the right header will be set. If its not a POST-Request the PHP will return your HTML.

To your other question: Yes, it is possible to use jQuery in a normal JavaScript function.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! The 404 error is gone but another popped up: "JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 146 of the JSON data". What is this referring to? I haven't used JSON.parse()
Hmm..Try to use die(json_encode($data) instead of echo json_encode($data).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.