2

Alright, so I'm having some issues on trying to find out how to pass some data that i have saved in localStorage over to a php script that I wrote, so I can then send that over to my database on a server. I did find some code earlier, (https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest), that looked like it would work but I had no luck with it.

Here's the code where I am saving the data and than trying to pass it over my phpscript

function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(initialize, showError, takeSnap);
        }
        else {
            alert("Geolocation is not supported by this browser.");
        }
    }

function initialize(position) {
        var lat = position.coords.latitude,
            lon = position.coords.longitude;

        var mapOptions = {
            center: new google.maps.LatLng(lat, lon),
            zoom: 14,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            mapTypeControl: true
        }

        var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(lat, lon),
            map: map,
            title: "Current Location"
        });
    }

function showError(error) {
        switch (error.code) {
            case error.PERMISSION_DENIED:
                alert("User denied the request for Geolocation.");
                break;
            case error.POSITION_UNAVAILABLE:
                alert("Location information is unavailable.");
                break;
            case error.TIMEOUT:
                alert("The request to get user location timed out.");
                break;
            case error.UNKNOWN_ERROR:
                alert("An unkown error occurred.");
                break;
        }
    }

function storeLocal(position) {
        if (typeof (Storage) !== "undefined") {
            var lat = position.coords.latitude,
                lon = position.coords.longitude;

            localStorage.latitude = lat;
            localStorage.longitude = lon;
        }
        else {
            alert("Your Browser doesn't support web storage");
        }

        return
    }

    function snapShot() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(storeLocal, showError);
        }
        else {
            alert("Geolocation is not supported by this browser.");
        }

        var oReq = new XMLHttpRequest();
        oReq.onload = reqListener;
        oReq.open("post", "snap.php?lat=" + localStorage.latitude + "&lon=" + localStorage.longitude, true);
        oReq.send();            
    }

    function reqListener() {
        console.log(this.reponseText);
    }

This is they script I wrote to save values into database

    <?php
    // Connecting to the database
    mysql_connect("localhost", "username", "password");
    mysql_select_db("db_name");

    $latitude = mysql_real_escape_string($_GET["lat"]);
    $longitude = mysql_real_escape_string($_GET["lon"]);

    // Submit query to insert new data
    $sql = "INSERT INTO locationsTbl(locID, lat, lon ) VALUES( 'NULL', '". $latitude ."', '". $longitude . "')";
    $result = mysql_query( $sql );

    // Inform user
    echo "<script>alert('Location saved.');</script>";

    // Close connection
    mysql_close();
    ?>
Razpiento
  • 67
  • 1
  • 11

2 Answers2

1

How about:

oReq.open("get", "snap.php?lat=" + localStorage.latitude + "&lon=?" + localStorage.longitude, true);

(you also had localStorage.lon instead of .longitude)

Since the values (strings) are in variables, you need to concatenate them, not put them in the string.

Also, since you seem to be passing these things to your PHP to save to the database, semantically speaking, you should be using a POST request...which is handled differently with AJAX requests.

In your PHP, you need to use:

$latitude = $_GET["lat"];
$longitude = $_GET["lon"];

to actually get the values that were sent with the GET request. Although these values should be escaped to avoid SQL injection.

Also, I'm not sure why you're setting the onload property of the AJAX request. Instead, use the onreadystatechange property...something like:

oReq.onreadystatechange = function () {
    if (oReq.readyState === 4) {
        if (oReq.status > 199 && oReq.status < 400) {
            console.log("successful response");
        } else {
            console.log("failed response: " + oReq.status);
        }
    }
};

The .readyState property refers to its state, where 4 means it's done (response has come back). The .status property refers to the HTTP status code. Normally between 200 & 400 is good. I know I've seen people only check for 200 (not a range).

UPDATE:

In order to pass POST parameters in the request, you don't append them to the URL - you pass them in the .send() method. Here's an example with your code:

oReq.open("POST", "snap.php", true);
oReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
oReq.send("lat=" + encodeURIComponent(localStorage.latitude) + "&lon=" + encodeURIComponent(localStorage.longitude));

And to retrieve them in PHP, you'd use:

$latitude = $_POST["lat"];
$longitude = $_POST["lon"];
Ian
  • 50,146
  • 13
  • 101
  • 111
  • Yea, but I'm not really sure how to use the POST request in my situation since I'm not grabbing the information off a field from a form. The way that it's working is that I have created a button on my page. It has an event listener which is looking for a click on an image, which than grabs the geolocation data and saves it. – Razpiento Apr 16 '13 at 16:58
  • @RenegadeScar I understand, but all you do is change `oReq.open("get"` to `oReq.open("post"`. Then in PHP, you access the values with `$_POST` instead of `$_GET` – Ian Apr 16 '13 at 17:00
  • ooooh, I see. Sorry, I'm kind of new to javascript and an average program at best. Thanks I'll give that a try. – Razpiento Apr 16 '13 at 17:02
  • @RenegadeScar No problem. It's just that `GET`, `POST`, `PUT`, and `DELETE` have meanings, and your operation seems to fit `POST` best. Not too important for now, I just wanted to point it out. – Ian Apr 16 '13 at 17:02
  • Thanks a lot! I really do appreciate the help =) – Razpiento Apr 16 '13 at 17:04
  • @RenegadeScar No problem :) Let me know if you're still having any trouble, I'd be happy to help more. – Ian Apr 16 '13 at 17:08
  • It looks like I might still be having trouble pass those values into my script, because I'm not getting the alert message to pop up that i inserted into my php script saying that the location has been save to the database. I also update the code above so you can see what i'm doing. give me a few seconds to do that – Razpiento Apr 16 '13 at 17:38
  • @RenegadeScar Remember this comment?: "all you do is change `oReq.open("get"` to `oReq.open("post"`. Then in PHP, you access the values with `$_POST` instead of `$_GET`". You changed the first part, but you're not getting the values correctly. Change `$_GET` to `$_POST` in your PHP – Ian Apr 16 '13 at 20:22
  • @RenegadeScar And I just updated my answer with a few things at the end – Ian Apr 16 '13 at 20:26
  • oh, sorry i guess i forgot to change that when I updated it above, but it is updated in my actual code. I still have nothing happening though and nothing is being inserted or updated in the database. – Razpiento Apr 16 '13 at 20:33
  • @RenegadeScar So which method are you using, GET or POST? Like I said before about POST requests - "handled differently with AJAX requests". I updated my answer with how to send a POST request. And make sure you use the `onreadystatechange` like I suggested in my answer as well. If you don't mind, please update your original question with your current code, so there isn't more confusion like this – Ian Apr 17 '13 at 13:55
0

You have code error

It should be oReq.onload = reqListener; oReq.open("get", "snap.php? lat="+localStorage.latitude+"&lon="+localStorage. lon, true); oReq.send();

Vicky Gonsalves
  • 11,593
  • 2
  • 37
  • 58