skip to Main Content

I want to get the location from this JavaScript to the controller and store it in the database:

var currPosition;

navigator.geolocation.getCurrentPosition(function(position) {
  updatePosition(position);
  setInterval(function() {
    var lat = currPosition.coords.latitude;
    var lng = currPosition.coords.longitude;
    jQuery.ajax({
      type: "POST",
      url: "myURL/location.php",
      data: 'x=' + lat + '&y=' + lng,
      cache: false
    });
  }, 1000);
}, errorCallback);

var watchID = navigator.geolocation.watchPosition(function(position) {
  updatePosition(position);
});

function updatePosition(position) {
  currPosition = position;
}

function errorCallback(error) {
  var msg = "Can't get your location. Error = ";
  if (error.code == 1)
    msg += "PERMISSION_DENIED";
  else if (error.code == 2)
    msg += "POSITION_UNAVAILABLE";
  else if (error.code == 3)
    msg += "TIMEOUT";
  msg += ", msg = " + error.message;
  alert(msg);
}

2

Answers


  1. you just need to change uri parameter to codeginter route that you have

    setInterval(function(){
        ....
        url:  "change this to codeigniter route url", 
        ....
    }, 1000);
    

    then in the controller you just need to save those parameter,

    class X extends CI_Controller{
    
        function update_position(){
            $x = $this->input->post('x');
            $y = $this->input->post('y');
    
            // then save it using model or query.
            $this->model_name->insert([...])
        }
    }
    
    Login or Signup to reply.
  2. To send post with .ajax():

    // ....
    let formData = new FormData();
    const lat = currPosition.coords.latitude;
    const lng = currPosition.coords.longitude;
    formData.append("x", lat);
    formData.append("y", y lng;
    $.ajax({
        url: "myURL/location.php", // update this with you url
        dataType: 'text',
        cache: false,
        contentType: false,
        processData: false,
        data: formData,
        type: 'POST',
        success: function(data){
            const response = jQuery.parseJSON(data);
        }
    });
    //....
    

    To receive post data in codeigniter :

    $x = $this->input->post('x');
    $y = $this->input->post('y');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search