Wordpress Ajax Json callimg



IN functions.php 

add_action('wp_footer', 'eps_footer');
function eps_footer() {
    echo "<script>var ajax_request_url = '".admin_url( 'admin-ajax.php' )."'</script>";
}



$.get( ajax_request_url,
  {
   'action' : 'get_post_title',
   'post_id' : 1
  }, function( response ){
    if ( !response.error ) {
      alert ('AJAX request made! The post title is ' + response.post_title );
    } else {
      alert ('error: ' + response.error );
    }
},  "json" );





add_action( 'wp_ajax_nopriv_get_post_title', 'get_post_title' );
add_action( 'wp_ajax_get_post_title', 'get_post_title' );

function get_post_title() {
  if ( isset($_GET['post_id']) ){
    $id = (int) $_GET['post_id'];
    $post = get_post( $id );
    header( "Content-Type: application/json" );
    echo json_encode( array('post_title' => $post->post_title) );
  } else {
    header( "Content-Type: application/json" );
    echo json_encode( array('error' => 'bad request') );
  }
  exit;
}

0 comments:

Post a Comment

Don't Forget to comment

About Me

My photo

HI i am mohammed  a Embedded Software Developer ,SEO specialist,Electronic engineer   Read more

ads