php - AJAX call using the last variable loaded on the page instead of current post -



php - AJAX call using the last variable loaded on the page instead of current post -

i'm creating custom plugin fires ajax phone call when sharing post on twitter, google + or liking on facebook.

within index.php file set within loop gets called on every new post on home page.

<?php cp_social_sharing_4pts(); ?>

here part of php function:

function cp_social_sharing_4pts(){ if ( is_user_logged_in() ) { echo '<script type="text/javascript"> var postid = '.get_the_id().'; function cp_share_twitter_do(){ jquery.ajax({datatype: "json", data: {action: "cp_share_twitter_do", post: postid}, success: function(data){ if(data.success==true){ boxy.alert(data.message); thebox.hide(); thebox.unload(); } else { boxy.alert(data.message); } } }); } </script> '; } // show buttons echo 'post id: '.get_the_id().'<br />'; // debug echo '<a href="https://twitter.com/share" class="twitter-share-button" data- url="'.get_permalink().'" data-text="'.get_the_title().'" data-count="horizontal" data- via="ps3blogdotnet">tweet</a>'; }

then gets loaded head:

function cp_social_sharing_js(){ if ( is_user_logged_in() ) { echo ' <script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script> <script type="text/javascript"> twttr.events.bind(\'tweet\', function(event) { cp_share_twitter_do(); }); </script> '; } } add_action('wp_head','cp_social_sharing_js');

after ajax fires goes here:

function cp_share_twitter_do(){ // tweet entry $cp_postid = $_post['post']; // issue. it's not returning right id post shared on. // more functions here echo json_encode($r); die(); } add_action('wp_ajax_cp_share_twitter_do', 'cp_share_twitter_do');

this work if on single blog post. issue on home page.

the variable postid correctly display post id on each post. when ajax phone call completes passes post id of lastly post displayed on home page instead of current post.

from see reason because not getting id 1 time again after loop has finished. when recall cp_share_fb_do() illustration var postid still set lastly id while loop. have recall get_the_id() or alternatively store id in var in each function eg

function cp_share_fb_do(){ var id = '.get_the_id().'; jquery.ajax({ ///etc

just remember create sure alter post: postid new var name.

hope helps

php jquery wordpress-plugin

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -