2

I'm trying to write a script that pass geolocation's lat and lng as an array to PHP and return a value to the client side by using jQuery AJAX. The best solution that i could find was JSON. My following scripts return me NULL value for some reason that i couldn't tell.

index.html

<div id="geoloc"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
            if(navigator.geolocation){
                navigator.geolocation.getCurrentPosition(showPosition);
            } else {
                $('#geoloc').html("<p>Geolocation is not supported by this browser</p>");
            }

            function showPosition(position) {
                var latlng = [ {"lat":position.coords.latitude, "lng":position.coords.longitude}];

                $.ajax({
                    type: "POST",
                    url: "libs/filterstores.php",
                    data: { json: JSON.stringify(latlng) },
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(data){
                        $('#geoloc').html("Latitude: " + data.lat + "<br />Longitude: " + data.lng);
                    }
                });
            }

        });
</script>

filterstores.php

$currloc = json_decode($_POST['latlng'], true);

$stores = array('lat'=>$currloc['lat'],'lng'=>$currloc['lng']);

echo json_encode($stores);

The following will be results what i got in returns once i hit the "share location" button pop up from the browser

Latitude: sdf
Longitude: sdfsd
3
  • 1
    Could you be a bit more specific? What is returning null for instance. You are showing a piece of Jquery. Is anything even executed? Check some sort of developer tools (f12 in chrome for instance) to see you request, do some console.log things to see if your code is actually run. Then add that debugging info here= (in the question, not in a comment!) Commented Aug 2, 2013 at 6:02
  • log php-script execution. See what you have in $_POST['currloc'] and $currloc after json_decode. Commented Aug 2, 2013 at 6:06
  • AFAIK, if you use datatype: "json", JQuery will automatically JSON encode the data you give. No need to do it on your own. Commented Aug 2, 2013 at 6:09

5 Answers 5

2

Should this line:

    data: { json: JSON.stringify(latlng) },

not specify currloc as the parameter?

i.e.

    data: { currloc: JSON.stringify(latlng) },
Sign up to request clarification or add additional context in comments.

3 Comments

Hi Stephen, thanks for your feedback. i've tried that but it still showing NULL as mentioned above.
@Wei did you try console.log(data) within the success ? is there a response returned? Secondly try adding something similar to this: error: function(xhr, ts, et){ $('#geoloc').html(ts+' '+et); }
@Manju - Hello Manju, it returns Null for both lat and lng as i mentioned earlier. Thank you
1

I think you are making double json coding in your AJAX function. If something went wrong when codifying, JSON function will give you a null as an answer. You only have to pass the string without json codification and surely it'll work:

function showPosition(position) {
$.ajax({
    type: "POST",
    url: "libs/filterstores.php",
    data: { lat:position.coords.latitude, lng:position.coords.longitude },        
    dataType: "json",
    success: function(data){
    $('#geoloc').html("Latitude: " + data.lat + "<br />Longitude: " + data.lng);
    }
});
}

Your PHP only will have to accept the POST, without json encoding:

PHP File:

$lat = $_POST['lat'];
$lng = $_POST['lng'];

$stores = array('lat'=>$lat,'lng'=>$lng);

echo json_encode($stores);

2 Comments

Hi there, Thank you so much for the answer! That resolve the problems! I thought it has to specify clearly the JSON when passing to PHP so i include the contentType and the data in such format. Also i was hoping to learn to pass as an JSON array and that's why i code it the way i posted earlier. But in this case it'll be perfectly fine! I'll try look around see if i could find some advice on how to passing JSON array to PHP down the track. Thanks again Choco! Thanks a million!
@Wei Check my solution if you want to pass data as JSON array :)
1

Just try to search 'sdfsd' or "sdfsd" and 'sdf' or "sdf"

And you will yourself get solution to your problem.

2 Comments

is that assuming request to libs/filterstores.php was successful? Issues seems to be with the way request is sent.
i've tried changing the $stores = array('lat'=>$currloc['lat'],'lng'=>$currloc['lng']); to $stores = array('lat'=>'test lat','lng'=>'test lng'); and it does return as intended. It has to be somewhere between passing in from the client-side to server-side
0

Try this

$currloc = json_decode($_POST['json'], true);

instead

$currloc = json_decode($_POST['latlng'], true);

or try this in SCRIPT

     function showPosition(position) {
            $.ajax({
                type: "POST",
                url: "libs/filterstores.php",
                data: {"lat":position.coords.latitude, "lng":position.coords.longitude},
               dataType: "json",
                success: function(data){
                    $('#geoloc').html("Latitude: " + data.lat + "<br />Longitude: " + data.lng);
                }
            });
        }

IN PHP FILE

$stores = array('lat'=>$_POST['lat'],'lng'=>$_POST['lng']);

echo json_encode($stores);

Hope it will help

1 Comment

Did tried that before and just tried again. Doesn't work. Thank you
0

This is how you can send and receive JSON data

$.ajax({
        type: "GET",
        url: "filterstores.php",
        data: {json: latlng},
        contentType: "application/json; charset=utf-8;",
        dataType: "json",
        success: function(data){
            $('#geoloc').html("Latitude: " + data.lat + "<br />Longitude: " + data.lng);
        }
});

And the PHP file

$currloc = $_GET['json'];
$stores = array('lat'=>$currloc[0]['lat'],'lng'=>$currloc[0]['lng']);
echo json_encode($stores);

Comments

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.