0

Ultimately, my goal is to obtain the latitude and longitude of the current user and then be able to save it into the database.

Before that I need to make an ajax call from jquery and pass these information into the php.

Right now, I simply want to echo any data from jquery. This is a child theme. Here is my current example:

functions.php

function my_enqueue() {

    wp_enqueue_script( 'ajax-script', get_stylesheet_directory_uri(). '/js/custom.js', array('jquery') );

    wp_localize_script( 'ajax-script', 'my_ajax_object',
            array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );

//then


function singletest() {

    if (isset($_POST["latitude"]) && !empty($_POST["latitude"])) {
        $lat = $_REQUEST["latitude"];
        $lon = $_REQUEST["longitude"];
        echo '<br>';
        echo 'latitude: '. $lat;
        echo '<br>';
        echo 'longitude: '.$lon;    
    }
    die();

}
add_action ('wp_ajax_singletest', 'singletest'); //logged users
add_action ('wp_ajax_nopriv_singletest', 'singletest'); //for all users

custom.js

  function showPositionFirstTime(position) {
    var latitude =  position.coords.latitude;
    var longitude =  position.coords.longitude;

      console.log(latitude + ' space ' + longitude);

      jQuery.ajax({
        url: my_ajax_object.ajax_url,
        type: "POST",
        data: {
          action: 'singletest',
          latitude: latitude,
          longitude: longitude
        },
        success: function(response) {
          var responseTxt = 'Response for the page ' + response;
          console.log('Got this from the server: ' + response);
          $('.testing-block').append(responseTxt);

       },
        error: function(errorThrown){
          console.log(errorThrown);
        }
      });

  }
  function getLocationFirstTime() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPositionFirstTime);
    } else { 
      $('.cords').text("Geolocation is not supported by this browser.");
    }
  }

  getLocationFirstTime();

display-location.php

echo '<div class="testing-block"></div>';

I am now able to display the content of the console log into the page. I think now I am going to be able to pass the coordinates, establish database connection and insert them.

Thank you everyone for your effort.

  • Since you are writing to the console, what does the console say? And what does the request response say in Developer Tools, Network? – Rick Hellewell Oct 29 '18 at 21:38
  • Added screenshots from the console. – user153210 Oct 29 '18 at 22:17
  • Well, a 400 is a 'bad request', which means that the request probably has a syntax error of some sort. But I don't know enough about Ajax/JS to help any further. There are online Ajax/JS syntax checkers; perhaps that will help. – Rick Hellewell Oct 29 '18 at 22:47
  • Ajax/JS syntax seems to be correct. My major concern is the WordPress way of handling the request. Or maybe I got the whole idea of passing the variables from js wrong. Thanks for your time anyway. – user153210 Oct 29 '18 at 23:20
  • 1
    Unless you've misunderstood how requests to PHP work. Every request is a clean slate, you can't POST data to the server on one request, then use that data via $_POST on a new request. Nothing persists betweens requests unless you put it in the database. This isn't like a Node or a Python app that runs 24/7, when a PHP request ends, it exits, each request spins up a new instance from scratch – Tom J Nowell Oct 30 '18 at 0:18
1

The solution to my problem is to:

  1. Add actions and create a function in functions.php.
  2. Create an empty block in display-location.php.
  3. Append the response from jQuery.ajax in success function to previously created empty block.

I hope this will help someone in the future (final code is inside the edited question itself).

Thank you.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy