$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>jquery - Ajax call in WordPress - unable to display the data on the page|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

jquery - Ajax call in WordPress - unable to display the data on the page

matteradmin9PV0评论

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.

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.

Share Improve this question edited Oct 30, 2018 at 3:12 asked Oct 29, 2018 at 21:16 user153210user153210 10
  • 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 Commented Oct 29, 2018 at 21:38
  • Added screenshots from the console. – user153210 Commented Oct 29, 2018 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 Commented Oct 29, 2018 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 Commented Oct 29, 2018 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 Commented Oct 30, 2018 at 0:18
 |  Show 5 more comments

1 Answer 1

Reset to default 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.

Post a comment

comment list (0)

  1. No comments so far