-4

I want to return Javascript variable in JSON format in PHP.

Below is my Javascript code which returns Longitude and Latitude.

function showPosition(){
        if(navigator.geolocation){
            navigator.geolocation.getCurrentPosition(function(position){

                 var positionInfo = "Your current position is (" + "Latitude: " + position.coords.latitude + ", " + "Longitude: " + position.coords.longitude + ")";
                //document.getElementById("result").innerHTML = positionInfo;


            });
        } else{
            alert("Sorry, your browser does not support HTML5 geolocation.");
        }
    }
    showPosition();
    //document.write(positionInfo);

How can i get the values of variable position.coords.latitude and position.coords.longitude as response in json format using php

Please note: We are calling this php script in background, so solution of fetching the variables on html input fields is not a viable solution for us.

R Pooja
  • 31
  • 1
  • 8
  • 2
    This JS returns nothing ... and further the relationship to php is neither present, nor explained. – YvesLeBorg Jan 10 '19 at 12:04
  • I am trying to learn javascript and php. i don't know the solution. I have value in positioninfo and i don't know how to use this php. Please help if you can. – R Pooja Jan 10 '19 at 12:10
  • This is sample demo - https://labs.jonsuh.com/jquery-ajax-php-json/ – Mittul At TechnoBrave Jan 10 '19 at 12:13
  • Your question fails to explain if you want to SEND the values to a php script, or RECEIVE them from there. (Code indicates transfer to php, but bytext suggests fetching from.) – mario Jan 10 '19 at 12:29

1 Answers1

0

One of the possible solutions is to issue an AJAX request and send the data to your PHP script:

var locationData = {'latitude':position.coords.latitude,'longitude':position.coords.longitude}; //Your data in JSON
locationData = JSON.stringify(locationData); //Your data as a JSON string

  var xhttp = new XMLHttpRequest(); //Create a new ajax request

  xhttp.open("POST", "script.php", true); //Set the method to POST, and the location of the php script

  xhttp.send(locationData); //Send data in string format

I recommend that you read more about AJAX requests, or use an alternative JavaScript library for simpler syntax.

gee
  • 142
  • 7