0

The goal is to have a map with movable marker which once clicked on 'confirm position' button, saves the latitude and longitude coordinates. I already seem to have got the map with a movable marker which gets long and lat of the pointer, but I do not know how to store these values and pass it to my database using SQL.

Please NOTE - there is supposed to be a google maps link in the header page which includes one's API key. Also - I am using this link for the location picker -

<!DOCTYPE html>
<html>
<head>
  <title>Tujjari</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!--Font Awesome CDN -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <script src="https://use.fontawesome.com/265b5bff8c.js"></script>
  <script src="https://kit.fontawesome.com/420b921a12.js" crossorigin="anonymous"></script>
  <!--Animate.css link1-->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.0.0/animate.min.css"/>
  <!--Animate.css link2-->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css">
  <!--Linking style.css-->
  <link rel="stylesheet" type="text/css" href="tujjaricss.css?v=<?php echo time(); ?>">
  <!--Bootstrap CDN's-->
  <script src="https://unpkg.com/scrollreveal"></script>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
  <script src="https://unpkg.com/location-picker/dist/location-picker.min.js"></script>
  <script
    src="https://code.jquery.com/jquery-3.5.1.js"
    integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
    crossorigin="anonymous"></script>
  <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
  <script type="text/javascript"
            src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAMq_YJsJ75HOUWUAK3MyZp47vzdR7_Jv8"></script>
  <script src="https://unpkg.com/location-picker/dist/location-picker.min.js"></script>
</head>
<body>
  <div id="map" ></div>
    <br>
    <center>
    <button id="confirmPosition" class="btn btn-secondary" formaction="congrats.php">Confirm Position</button></center>
    <br><br>
  </div>
  <br><br>
  <script>
    // Get element references
    var confirmBtn = document.getElementById('confirmPosition');
    var longlat = document.getElementById('longlat');
    var onIdlePositionView = document.getElementById('onIdlePositionView');
   
    // Initialize locationPicker plugin
    var lp = new locationPicker('map', {
      setCurrentPosition: true, // You can omit this, defaults to true
    }, {
      zoom: 15 // You can set any google map options here, zoom defaults to 15
    });
   
    // Listen to button onclick event
    confirmBtn.onclick = function () {
      // Get current location and show it in HTML
      var location = lp.getMarkerPosition();
      console.log(location);
      xmlhttp = new XMLHttpRequest();
      xmlhttp.open("REQUEST", "ajax.php", "&location.lat=" + location.lat + "&location.lng=" + location.lng, true);
      xmlhttp.send();
    };

    // Listen to map idle event, listening to idle event more accurate than listening to ondrag event
    google.maps.event.addListener(lp.map, 'idle', function (event) {
      // Get current location and show it in HTML
      var location = lp.getMarkerPosition();
      onIdlePositionView.innerHTML = 'The chosen location is ' + location.lat + ',' + location.lng;
      console.log(location.lat)
    });
  </script>
  <script>
    src="https://code.jquery.com/jquery-3.5.1.js"
    integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
    crossorigin="anonymous">
  </script>
</body>

<style type="text/css">
  @media only screen and (max-width: 600px) {
 .locu{
  width: 40%;
 }
 .loca
 {
  margin-left: 75px;
 }
 .locus{
  margin-left: 31px;
 }
  }
@media only screen and (min-width: 768px) {
  .locu,.loca{
    margin-left: 306px;
  }
  .locu{
    width: 40%;
  }
  .locus{
    margin-left: 262px !important;
    width: 40%;
  }
}
#map {
    width: 100%;
    height: 480px;
  }
</style>

Ajax code

<?php include("db/db.php");
if($_GET['confirm']){
    print_r($_REQUEST);
    $latitude = $_REQUEST['location.lat'];
    $longitude = $_REQUEST['location.lng'];
    $query = mysql_query("insert into location(latitude, longitude) values('$latitude', '$longitude')") or die(mysql_error());  
}
?>
AB7zz
  • 82
  • 1
  • 1
  • 6
  • What the issue? You have an ajax request going (although for clarity's sake i think you should omit the dots in the get variables), so all you need to do is implement an insert to your database. You can do a `$_REQUEST['location.lat']` (or whatever you change it to) and same thing for longitutde in your `ajax.php`, sanitize your input and simply insert into your database. – peterxz Dec 06 '20 at 12:27
  • The issue is that, I don't know how to pass that location.lat value to my table in the database...Okay I'll try that out – AB7zz Dec 06 '20 at 12:29
  • 1
    First you should make sure that the values land in your `ajax.php` file. A very easy way to tell is to do `print_r($_REQUEST);` in the ajax file, and monitor the Network tab of your dev tools. When you send the ajax request by pressing the button, you will see this ajax file show up in this tab; click into "Response" and make sure the values are there. Then look into `PDO` ( https://www.php.net/manual/en/book.pdo.php ). Explaining how to insert into a database is beyond the scope of the question as its too broad but if you have specifics that you struggle with feel free to come back. – peterxz Dec 06 '20 at 12:35
  • Hey, I've updated the code. Even put the ajax code. I'm actually not a pro at this, just learning. I usually insert values into the table using php. But here I'm not able to pass the location.lat value to my php so that makes it hard. Please check the ajax code and let me know what to change. Thanks! – AB7zz Dec 06 '20 at 12:53
  • "not able to" means what exactly? What do you see in the browser's network tool when running the Ajax request? Are the values sent correctly in the URL? What does the PHP log when it receives the values (you should add some logging if you haven't already)? And why are you using the old and insecure `mysql_query`? It was removed in newer versions of PHP. If that function is not giving an error then it means you're using an out of date insecure version of PHP as well! – ADyson Dec 06 '20 at 13:24
  • P.s. for info, your database is not "in" phpMyAdmin... phpMyAdmin is just a tool you can use (one of many) to manage your databases in a mySQL Server. The mySQL Server is the place your database actually lives. – ADyson Dec 06 '20 at 13:26
  • One more thing, actually this is perhaps the most important thing which I just noticed: you are not sending any "confirm" parameter in your AJAX request, so `if($_GET['confirm'])` will never be true, and so the rest of the PHP code will never run. – ADyson Dec 06 '20 at 13:28
  • Btw do you realise you have included jQuery about 4 times in your page? And other things are there multiple times and/or with multiple versions too. It's unnecessary, inefficient and might even in some cases cause bugs. Take a good look at your code and have a tidy up – ADyson Dec 06 '20 at 13:34
  • I know this a lot to ask for, but we will need a step by step procedure to fix this code as we are beginners in ajax.. or could you just please edit the bug out for me? would really appreciate that – AB7zz Dec 06 '20 at 15:23
  • Well what didn't you understand from what I said? Look at this line: `xmlhttp.open("REQUEST", "ajax.php", "&location.lat=" + location.lat + "&location.lng=" + location.lng, true);`...see how you included the latitude and longitude parameters? You need to include another one called confirm. Or you need to remove the `if` statement that I mentioned before from your PHP. – ADyson Dec 06 '20 at 15:28
  • 1
    Please stop using this ancient, insecure, and deprecated API, and see about sql injection and the importance of prepared and bound queries – Strawberry Dec 06 '20 at 19:36

1 Answers1

1

You've already managed to get a map working and you also have an onclick event that sends an ajax request to your backend; all you have to do is actually insert the values. The problem with your ajax interaction is the following:

  1. You do not have 'confirm' parameter in this call: xmlhttp.open("REQUEST", "ajax.php", "&location.lat=" + location.lat + "&location.lng=" + location.lng, true); which is why your ajax call not doing anything - you can either 1) remove the opening if() in your ajax file, or 2) pass through a confirm parameter like you have with location.lat and location.lng.
  2. Like I said in the comments, your best bet of debugging ajax files is using var_dump() and print_r() functions in the ajax file; you can monitor the ajax calls in dev tools -> Network tab (CTRL + Shift + I on Firefox and Chrome). You can click into each individual call -> click Response tab and see the dump of your variables. Alternatively, you can use an onsuccess event handler too, which is fairly easy with jquery:
$.ajax({
    url: '/your/endpoint/here.php', //you can also append $_GET variables on the end of this, e.g. /your/endpoint/here.php?confirm=y&long=5&lat=5 - if you do this you do not need the data parameter also unless you know what you doing 
    method: 'POST', //or 'GET', //this is also not required, defaults to GET
    data: '', // this parameter can be missed out entirely, or you can manually build a string such as confirm=y&latitude=5&longitutde=5 OR you can use $('form').serialize() to get all input field values sent
    success: function(data) {
        console.log(data); //this will dump to the console the exact thing you would find in the Network tab and response 
    }
});
  1. You really need to get rid of all the duplication of jQuery and other includes. There is not only no reason to include multiple versions but you are also opening yourself up to potential conflicts and also slowing your page down for no reason. Have ONE version included of everything only.
  2. Your database driver is not phpmyadmin, phpmyadmin is an interface to interact with the driver - it usually runs either MySQL or MariaDB.
  3. To learn how to actually insert values into your database, please see this answer here: https://stackoverflow.com/a/60496/7691338
peterxz
  • 864
  • 1
  • 6
  • 23