Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am trying to get ID of post on HOME page .So far my coding is

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' ) ) );
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;
}

And My jquery

jQuery(document).ready(function($) {
$('h1.entry-title 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) {
    alert(data['post']);
  }
});     

return false;
});
});

But I am getting alert Null instead of getting the id of post.

share|improve this question
    
Please format your codes and content well. For more details check this –  Maruti Mohanty Dec 19 '13 at 6:48

2 Answers 2

You are rendering the json data the wrong way.

Change the success to the below:--

success: function(data) {
    alert(data.id);
    // Now you can similarly render the other details like details.success
}
share|improve this answer
    
Thank you for help But this still alert "Null"...FYI I am trying this on Home page not single post page. –  ashraf Dec 19 '13 at 8:50
    
check if the ajax request is going right... and check if you are getting the response right... You can use a tool like firebug to do it –  Maruti Mohanty Dec 19 '13 at 10:19

First, On Chrome or some other browser you could actually check if you get any data from the server by doing "right click => inspect element => network tab".

If your Ajax function is working you should see a GET request. You are using POST type instead try using GET.

Once you see a GET request you also should parse the JSON data using JSON.parse as you were encoding the data in your php function.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.