Trouble with javascript/php passing

All,

Explanation of my idea:

I have a google maps with marker clusters on it. The markers are generated by coordinates being selected from a table from a database. If a marker is clicked it should show an info window with information that I specify in the code (for example: a name, address, etc.) That information should also be retrieved from the database. To do this, I decided to go with getting the coordinates from the clicked marker, store them in a variable(s) and use them to retrieve the right information from the database > store them also in one or different variables and add them to the infowindow with infowindow.setContent.

What got I working so far?

generating the google maps
adding the markers/cluster markers
info window being shown if a marker has been clicked
Where is the issue?

=> Passing the coordinates from the clicked marker (Javascript to PHP) where my database connection is being made and query to retrieve the info, pass it back to javascript to shown it in the info window. All this without refreshing the page and should work for each marker that is being clicked. Ofcourse each marker is going to give other information.

I first try to do this with passing the coordinates from the clicked marker in the url (without refreshing) but it only added the coordinates to the url and once I refreshed and clicked a marker it would show the information of the clicked marker before the refresh. So now trying with AJAX.

My question(s)

I read up and looks like this should be done with AJAX. First time using AJAX on this project. So still getting used to it. But is my general way of doing it good or can it be done another way? So passing Javascript to PHP and back to Javascript without refreshing the page. Iā€™m also doing this in 1 PHP file (woninggespot.php). Should I work with different files?

Code - Javascript

function initMap()
    {

        //Options for the map
        var mapOptions = {
            zoom: 8,
            center: new google.maps.LatLng(50.503887, 4.469936),
            clickableIcons: false
        };

        //generate map
        var map = new google.maps.Map(document.getElementById('map'), mapOptions);

        //image marker
        var imagemarker = './images/marker_small.png';

        //info window
        var infoWindow = new google.maps.InfoWindow();

        //fill map with markers
        var markers = locations.map(function(location, i) {

            var marker = new google.maps.Marker({
                position: location,
                icon: imagemarker
            });
            google.maps.event.addListener(marker, 'click', function(evt) {

                //AJAX
                function post()
                {
                    var latitude = evt.latLng.lat();
                    var longitude = evt.latLng.lng();

                    $.post('woninggespot.php',{latMarker:latitude,lngMarker:longitude});
                }

                //fill var's with values from database (from php)
                var prijs = <?php echo json_encode($prijs); ?>;
                var type = <?php echo json_encode($type); ?>;
                var slaapkamers = <?php echo json_encode($slaapkamers); ?>;

                infoWindow.setContent(prijs + type + slaapkamers);
                infoWindow.open(map, marker);


            });

            return marker;
        });

        //Marker cluster
        var markerCluster = new MarkerClusterer(map, markers,
            {imagePath: './googlemaps/markerclusterer/images/m'});

    }
    var locations = <?php echo "[".$array."]"; ?>;
</script>

Code - PHP

FYI: I left out the database connection code because itā€™s not relevant here

<?php

    //get lat and lng javascript when marker has been clicked
    $latMarker = $_POST["latmarker"];
    $lngMarker = $_POST["lngmarker"];

    $clickedMarkerLocation = $latMarker . ", " . $lngMarker;

    $query = mysqli_query($conn, "SELECT * FROM spotwoning WHERE coordinaten='$clickedMarkerLocation'");

    while ($record = mysqli_fetch_assoc($query))
    {

        $prijs = $record['prijsklasse'];
        $slaapkamers = $record['slaapkamers'];
        $type = $record['typewoning'];

    }    
?>

Last update: (based on this found post: Link)

Javascript

 function initMap()
    {

        //Options for the map
        var mapOptions = {
            zoom: 8,
            center: new google.maps.LatLng(50.503887, 4.469936),
            clickableIcons: false
        };

        //generate map
        var map = new google.maps.Map(document.getElementById('map'), mapOptions);

        //image marker
        var imagemarker = './images/marker_small.png';

        //create info window
        var infoWindow = new google.maps.InfoWindow();

        //fill map with markers
        var markers = locations.map(function(location, i) {

            var marker = new google.maps.Marker({
                position: location,
                icon: imagemarker
            });
            google.maps.event.addListener(marker, 'click', function(evt) {

                //get coordinates from clicked marker
                var latitude = evt.latLng.lat();
                var longitude = evt.latLng.lng();

                var prijs = <?php echo json_encode($prijs); ?>;
                var type = <?php echo json_encode($slaapkamers); ?>;
                var slaapkamers = <?php echo json_encode($type); ?>;

                console.log(prijs + type + slaapkamers + latitude + ", " + longitude);

                //var content = prijs + type + slaapkamers;

                //set content from info window
                infoWindow.setContent();
                infoWindow.open(map, marker);

            });

            return marker;
        });

PHP

<?php

//get lat and lng javascript when marker has been clicked
$latMarker = $_GET["latitude"];
$lngMarker = $_GET["longitude"];

$clickedMarkerLocation = $latMarker . ", " . $lngMarker;

$query2 = mysqli_query($conn, "SELECT * FROM spotwoning WHERE coordinaten='$clickedMarkerLocation'");

while ($record = mysqli_fetch_assoc($query2)) {

    $prijs = $record['prijsklasse'];
    $slaapkamers = $record['slaapkamers'];
    $type = $record['typewoning'];

};

?>

1: Your jquery $.post should have a success: clause to handle whatever data comes back.
2: Your PHP should actually send some data back.

The First answer I get and will try it out.

But what do you mean with the 2nd one exactly?
Cause Iā€™m trying to send data back like this:

var prijs = <?php echo json_encode($prijs); ?>;
var type = <?php echo json_encode($slaapkamers); ?>;
var slaapkamers = <?php echo json_encode($type); ?>;

You need to echo it inside your PHP code.

while ($record = mysqli_fetch_assoc($query2)) {

    $prijs = $record['prijsklasse'];
    $slaapkamers = $record['slaapkamers'];
    $type = $record['typewoning'];
// echo it here
};
// or echo it here

It gets passed back to your JavaScript to the success() function.

As you have multiple items, youā€™ll need to encode them when you echo them out of your PHP script.

These lines

var prijs = <?php echo json_encode($prijs); ?>;

are only run when your page is initially drawn.

Those lines are in your Javascript, not your PHP.

The two do not run at the same time. Ever. PHP runs first, on your server, and replaces all the <?php ?> blocks with whatever it thinks should be there. It then hands the resulting HTML to your browser. PHP is then done.

Javascript is called by the browser once itā€™s done receiving the HTML, and starts its process.

So, you show me [quote=ā€œtomdeboeck, post:1, topic:292842ā€]
var prijs = <?php echo json_encode($prijs); ?>;
var type = <?php echo json_encode($slaapkamers); ?>;
var slaapkamers = <?php echo json_encode($type); ?>;
[/quote]

and say ā€œI put the data inā€.

As far as Javascript is concerned, that block looks like

var prijs = {imathing: 'doop'};
var type = {imaotherthing: 'doopa'};
var slaapkamers = {imathing2: 'dee'};

So yes, you will always get the same value.

AJAX is the method by which Javascript can ask PHP to do some more processing. (Vast oversimplification, but it works for this purpose).

Your AJAX call says ā€œServer, I need the result of thisā€. It then continues on to do whatever it was doing while it waits. (Thatā€™s the first ā€œAā€ in AJAX)
At that point, the Server can run PHP again, and hand back a piece of data (or a website, or anything really. But here weā€™re talking about passing data) as if the browser had loaded another webpage.

The javascript can then wake up and catch that result once PHP is done, and use it.

So what I have now but itā€™s still not working but tried to write a success() function as you said.
Any help or pointers?

Javascript:

<script>
    function initMap()
    {

        //Options for the map
        var mapOptions = {
            zoom: 8,
            center: new google.maps.LatLng(50.503887, 4.469936),
            clickableIcons: false
        };

        //generate map
        var map = new google.maps.Map(document.getElementById('map'), mapOptions);

        //image marker
        var imagemarker = 'https://immokoopadvies.be/images/marker_small.png';

        //create info window
        var infoWindow = new google.maps.InfoWindow();

        //fill map with markers
        var markers = locations.map(function(location, i) {

            var marker = new google.maps.Marker({
                position: location,
                icon: imagemarker
            });
            return marker;

            google.maps.event.addListener(marker, 'click', function(evt) {

                //get coordinates from clicked marker
                var latitude = evt.latLng.lat();
                var longitude = evt.latLng.lng();

                var LatLng = latitude + ", " + longitude;

                $.ajax({
                        url: 'woninggespot.php',
                        type: 'post',
                        data: {"clickedMarkerLocation" : JSON.stringify(LatLng)},
                        success: function(data){

                        //set content from info window
                        infoWindow.setContent(data);
                        infoWindow.open(map, marker);
                }
                });
            });
        });

        //Marker cluster
        var markerCluster = new MarkerClusterer(map, markers,
            {imagePath: './googlemaps/markerclusterer/images/m'});

    }
    var locations = <?php echo "[".$array."]"; ?>;
</script>

PHP

<?php

if (isset($_POST["LatLng"])) {
    $clickedMarkerLocation  = json_decode($_POST["clickedMarkerLocation"]);

    echo "Data is: " . $clickedMarkerLocation;

    $query2 = mysqli_query($conn, "SELECT * FROM spotwoning WHERE coordinaten='$clickedMarkerLocation'");

    while ($record = mysqli_fetch_assoc($query2)) {

        $prijs = $record['prijsklasse'];
        $slaapkamers = $record['slaapkamers'];
        $type = $record['typewoning'];

    };

    echo $prijs; 
    echo $slaapkamers; 
    echo $type;
}?>

Can you also check my reply to droopsnootā€™s last post?

If youā€™re only expecting one row to come back from your query, thereā€™s no real point having a while() loop, just call mysqli_fetch_assoc() a single time to get the data. Once you have it, have a look at json_encode() in PHP to encode all three items into a single object to pass back into JS as data. Then back in your calling code, decode your result into the individual fields to display locally. Donā€™t forget to remove your first debug echo line as that will mess things up.

Incidentally if the database is under development, Iā€™d advise against storing the lat/long co-ordinates in a single column, for various reasons I would imagine it would be much better to have separate columns for them.

Iā€™m keep getting ā€˜0ā€™ as result in the info window and also getting undefined in my console for the .send part.

Javascript

<script>
    function initMap()
    {

        //Options for the map
        var mapOptions = {
            zoom: 8,
            center: new google.maps.LatLng(50.503887, 4.469936),
            clickableIcons: false
        };

        //generate map
        var map = new google.maps.Map(document.getElementById('map'), mapOptions);

        //image marker
        var imagemarker = './images/marker_small.png';

        //create info window
        var infoWindow = new google.maps.InfoWindow();

        //fill map with markers
        var markers = locations.map(function(location, i) {

            var marker = new google.maps.Marker({
                position: location,
                icon: imagemarker
            });
            google.maps.event.addListener(marker, 'click', function(evt) {

                //get coordinates from clicked marker
                var latitude = evt.latLng.lat();
                var longitude = evt.latLng.lng();
                var latLng = latitude + ", " + longitude;
                var xhr;

                //AJAX
                if (window.XMLHttpRequest) { // Mozilla, Chrome, Safari,...
                    xhr = new XMLHttpRequest();
                } else if (window.ActiveXObject) { // IE 8 and older
                    xhr = new ActiveXObject("Microsoft.XMLHTTP");
                }

                var data = latLng;
                console.log(data); //troubleshooting
                    xhr.open("POST", "test.php", true);
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    var xhrsend = xhr.send(data);
                    console.log(xhrsend); //troubleshooting **returns undefined
                    xhr.onreadystatechange = display_data;
                        function display_data(){
                            if (xhr.readyState == 4){
                                if (xhr.status == 200){
                                    console.log('OK.'); //troubleshooting
                                    //show infowindow + content
                                    infoWindow.setContent(xhr.responseText);
                                    infoWindow.open(map, marker);
                                } else {
                                    console.log('There was a problem with ajax the request.'); //troubleshooting
                                }
                            }
                        }
            });
            return marker;
        });

        //Marker cluster
        var markerCluster = new MarkerClusterer(map, markers,
            {imagePath: './googlemaps/markerclusterer/images/m'});

    }
    // fill map with marker cluster by getting coordinates
    var locations = <?php echo "[".$array."]"; ?>;
</script>

test.php

<?php
$SERVER = "...";
$DB_USERNAME = "...";
$DB_PASSWORD = "...";
$DB_NAME = "...";

//Maak connectie
$conn = new mysqli ($SERVER, $DB_USERNAME, $DB_PASSWORD, $DB_NAME);

//Kijk connectie na
if ($conn->connect_error){
    die("Connectie gefaald met DB: " . $conn->connect_error);
}

//Get value from AJAX request
$clickedMarkerLocation  = $_POST["latLng"];

$query = mysqli_query($conn, "SELECT * FROM spotwoning WHERE coordinaten='$clickedMarkerLocation'");

while ($record = mysqli_fetch_assoc($query)) {

    $prijs = $record['prijsklasse'];
    //going to add more data once I figured the problem out

}
echo $prijs;
?>

Your code returns a single field from a single row. Presumably the row contained a 0 in the field you specified.

Sorry, canā€™t follow completelyā€¦;
So where is my mistakeā€¦

The test.php you say gives an output of 0 in the info window.

The code has the following lines:

   $prijs = $record['prijsklasse'];
...
echo $prijs;

If 0 is being echoā€™d from test.php, then itā€™s reasonable to presume that prijsklasse in the database contains 0.

You can investigate that further by doing a var_dump of $prijs.

var_dump($prijs);
echo $prijs;

No it doesnā€™t contain 0, thatā€™s why Iā€™m clicking those markers, cause I know for certain it should give me another number instead of 0.

With the var_dump I get this:
string(1) ā€œ1ā€ 1

In this bit

var latLng = latitude + ", " + longitude;
... then a bit later ..
var data = latLng;
... and then ...
var xhrsend = xhr.send(data);

Donā€™t you need to define the parameter name that youā€™re sending through? That is, how does your receiving PHP code know that the LatLng string you are sending across is called ā€œlatLngā€ when it gets there? Shouldnā€™t there be something like

var data = "latLng="  + latLng;

to define it? Or does the JavaScript do something magical based on the variable name? Iā€™ve only used this code with ā€œGETā€ requests myself, so am not sure.

Also,

console.log(xhrsend); //troubleshooting **returns undefined

is not surprising, in async mode the send() method returns ā€œundefinedā€. ( https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send )

UPDATED CODE

getting nothing in return now, empty info window

Javascript

<script>
    function initMap()
    {

        //Options for the map
        var mapOptions = {
            zoom: 8,
            center: new google.maps.LatLng(50.503887, 4.469936),
            clickableIcons: false
        };

        //generate map
        var map = new google.maps.Map(document.getElementById('map'), mapOptions);

        //image marker
        var imagemarker = './images/marker_small.png';

        //create info window
        var infoWindow = new google.maps.InfoWindow();

        //fill map with markers
        var markers = locations.map(function(location, i) {

            var marker = new google.maps.Marker({
                position: location,
                icon: imagemarker
            });
            google.maps.event.addListener(marker, 'click', function(evt) {

                //get coordinates from clicked marker
                var latitude = evt.latLng.lat();
                var longitude = evt.latLng.lng();
                var latLng = latitude + ", " + longitude;
                var xhr;

                //AJAX
                if (window.XMLHttpRequest) { // Mozilla, Chrome, Safari,...
                    xhr = new XMLHttpRequest();
                } else if (window.ActiveXObject) { // IE 8 and older
                    xhr = new ActiveXObject("Microsoft.XMLHTTP");
                }

                var data = "latLng=" + latLng;
                    console.log(data);
                    xhr.open("POST", "test.php", true);
                    var xhrsend = xhr.send(data);
                    xhr.onreadystatechange = display_data;
                        function display_data(){
                            if (xhr.readyState == 4){
                                if (xhr.status == 200){
                                    //show infowindow + content
                                    infoWindow.setContent(xhr.responseText);
                                    infoWindow.open(map, marker);
                                } else {
                                    console.log('There was a problem with ajax the request.');
                                }
                            }
                        }
            });
            return marker;
        });

        //Marker cluster
        var markerCluster = new MarkerClusterer(map, markers,
            {imagePath: './googlemaps/markerclusterer/images/m'});

    }
    var locations = <?php echo "[".$array."]"; ?>;
</script>

test.php

<?php
$SERVER = "...";
$DB_USERNAME = "...";
$DB_PASSWORD = "...";
$DB_NAME = "...";

//Maak connectie
$conn = new mysqli ($SERVER, $DB_USERNAME, $DB_PASSWORD, $DB_NAME);

//Kijk connectie na
if ($conn->connect_error){
    die("Connectie gefaald met DB: " . $conn->connect_error);
}

$clickedMarkerLocation  = $_POST["latLng"];

$query = mysqli_query($conn, "SELECT * FROM spotwoning WHERE coordinaten='$clickedMarkerLocation'");

while ($record = mysqli_fetch_assoc($query)) {

    $prijs = $record['prijsklasse'];
    $bewoonbare_oppervlakte = $record['bewoonbare_oppervlakte'];
    $perceel_oppervlakte = $record['perceel_oppervlakte'];
}
//printf ("Prijs: " . $prijs);

echo $prijs;
//echo $bewoonbare_oppervlakte;
//echo $perceel_oppervlakte;
?>

Also,

console.log(xhrsend); //troubleshooting **returns undefined
is not surprising, in async mode the send() method returns ā€œundefinedā€. ( https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send )

True, I figured out that it returns undefined always.

If you console.log(xhr.responseText) what does it say?

Nothing

First line: latLng=50.954365, 4.036592400000018
Second line: empty

And keeps doing that for each click

OK, what about modifying the PHP code to just echo the value of $_POST['latLng'] and then exit, just to see if the data is getting there OK?

ETA - that looks like a long set of decimals on the longitude.

Just to be sure, you mean this right?

<?php

$clickedMarkerLocation  = $_POST["latLng"];
echo $clickedMarkerLocation;

?>

Still empty
Good idea by the way!

OK, just to be absolutely sure:

<?php

$clickedMarkerLocation  = $_POST["latLng"];
echo "Result" . $clickedMarkerLocation;

?>

If the console shows ā€œResult:ā€ then you know your PHP is running, but the data is not getting to it. If itā€™s still blank. itā€™s not calling the PHP code.