0

I am asking for user's location on page loading and set it to hidden fields and try to read it from their to php. The JS code works but when I echo it to php, its showing null and after printing 'value is submitted' it keeps reloading the whole page.

<script>
    var x = document.getElementById(\"latitude\");
    var y = document.getElementById(\"longitude\");
    var a;
    function getLocation()
    {
        if (navigator.geolocation)
        {
            navigator.geolocation.getCurrentPosition(showPosition);
        } else
        {
            x.innerHTML = \"Geolocation is not supported by this browser.\";
        }
    }

    function showPosition(position)
    {
        x.value = position.coords.latitude; 
        y.value= position.coords.longitude;
        submitform();
    }
    function submitform()
    {
        document.forms[\"locform\"].submit();
        console.log(\"Value is sumitted\");
    }
    getLocation();
    </script>

<form action='abc.com/list' id='locform' method='get'>
    <input type='hidden' id='latitude' name='latitude'>
    <input type='hidden' id='longitude' name='longitude'>
</form>

$users_postal=$_GET['latitude'];
echo($users_postal);

1 Answer 1

1

The problem is that your javascript code executed before the page loaded. You must wait for all HTML load then run your js code.

You can achieve that by adding change form and script tag positions. Excatly write your js after HTML code.

<form action='abc.com/list' id='locform' method='get'>
   <input type='hidden' id='latitude' name='latitude'>
   <input type='hidden' id='longitude' name='longitude'> 
</form>
<script>
   // you js code here
</script>

/then write PHP code
$users_postal=$_GET['latitude'];
echo($users_postal);
Sign up to request clarification or add additional context in comments.

1 Comment

can you share your code state with me after my answer? please send me it with pastebin.com

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.