jquery - Get post data using AJAX -


i'm perusing attempt learn ajax , json, , i'm having trouble finding decent resource. still have many questions i'm looking resource.

my aim pull content wordpress posts. tried looking tutorials , discussions solutions found wouldn't work me or didn't like, wan't understand i'm doing wrong.

i have included efforts far below, but not primary question.

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 set action. how encode json , return post data used?

add_action('wp_ajax_nopriv_ajax_request', 'ajax_handle_request'); add_action('wp_ajax_ajax_request', 'ajax_handle_request');  function ajax_handle_request(){ } 

i able figure out setting global $post $post variable.

then printing out $response array.

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 response     print json_encode($response);      // important: don't forget "exit"     exit; } 

using jquery retrieve data , 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;   }); }); 

Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo