3

I'm trying to pull content from Wordpress posts AJAX.

I have included my efforts so far below.

Loaded scripts.

wp_enqueue_script( 'my-ajax-request', get_stylesheet_directory_uri() . '/js/ajax.js', array( 'jquery' ) );
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

JavaScript

jQuery(document).ready(function($) {

  $('.ajax a').click(function(event) {
    event.preventDefault();
    var id = $(this).data('id');

    $.ajax({
      type: 'POST',
      url: MyAjax.ajaxurl,
      data: {'action' : 'ajax_request', 'id': id},
      dataType: 'json',
      success: function(data) {
        console.log(data);
      }
    });     

    return false;

  });

});

Here I set up my action. How to encode post data as JSON and return?

add_action('wp_ajax_nopriv_ajax_request', 'ajax_handle_request');
add_action('wp_ajax_ajax_request', 'ajax_handle_request');

function ajax_handle_request(){
}
4
  • When are you wanting to pull informations from the posts, on or after posting? Also what information do you want to pull? Commented Aug 18, 2013 at 22:32
  • FYI, there is a WordPress-specific Stack Exchange site, although questions like this are welcome here as well. Commented Aug 18, 2013 at 22:34
  • Also, if your goal is to learn about AJAX and JSON in general, this WordPress example is probably not the best starting point, as WordPress doesn't really have an API for this sort of thing (I don't think), and certainly not a standard-looking one that returns a nice JSON result. I use AJAX extensively, but honestly have always struggled trying to do what you want with WordPress. Commented Aug 18, 2013 at 22:36
  • @iRector I want to pull post information on anchor click. I have added a data attribute to anchors that include the the id of the post. I want to include the get_post($post_id) variable which includes all the information about the post. Commented Aug 18, 2013 at 22:38

2 Answers 2

6

Update:

I'm seeing activity on this post, and it's very old.

Please use the WP REST API instead: https://developer.wordpress.org/rest-api/


I was able to figure this out by setting global $post variable.

Then by encoding the $response.

add_action('wp_ajax_nopriv_ajax_request', 'ajax_handle_request');
add_action('wp_ajax_ajax_request', 'ajax_handle_request');

function ajax_handle_request(){

    $postID = $_POST['id'];
    if (isset($_POST['id'])){
        $post_id = $_POST['id'];
    }else{
        $post_id = "";
    }

    global $post;
    $post = get_post($postID);

    $response = array( 
        'sucess' => true, 
        'post' => $post,
        'id' => $postID , 
    );

    // generate the response
    print json_encode($response);

    // IMPORTANT: don't forget to "exit"
    exit;
}

Using jQuery to retrieve the data and output.

jQuery(document).ready(function($) {

  $('.ajax a').click(function(event) {
    event.preventDefault();
    var id = $(this).data('id');

    $.ajax({
      type: 'POST',
      url: MyAjax.ajaxurl,
      data: {'action' : 'ajax_request', 'id': id},
      dataType: 'json',
      success: function(data) {
        console.log(data['post']);
      }
    });     

    return false;
  });
});
Sign up to request clarification or add additional context in comments.

Comments

0

Use the functions wp_send_json_success and wp_send_json_error to return the Ajax request result.

Both of them use wp_send_json, which takes care of the header, JSON encoding and echoing, and to die.

Also, you should send a nonce when localizing the script:

array(
    'url'   => admin_url( 'admin-ajax.php' ),
    'nonce' => wp_create_nonce( "my_long_unique_string_name" ),
)

And check it within wp_ajax_* action callback:

check_ajax_referer( 'my_long_unique_string_name', 'nonce' );

Example: https://wordpress.stackexchange.com/a/106436/12615

2 Comments

How would I call these functions given my answer above? Does my solution suggest any call to the ajax_request action is technically a success then?
@hyperdrive, if post ID is not set, I'd return an error. See the example I linked...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.