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 have a button within a post which a user can click. Once clicked, an AJAX call is made.

My question is, within my PHP AJAX helper function (located in my theme's function.php) how can I retrieve, for instance, the ID of the post that the request was sent from.

I can get the ID from the markup and pass it in the AJAX call but it seems messy, i.e.

<article id="post-12">
<!-- article content -->
</article>


// JS
var postID = $("article").attr("id");

Is there a better way? Some kind of global that is accessible perhaps?

share|improve this question

2 Answers 2

up vote 0 down vote accepted

Use wp_localize_script() to declare globals.

Example:

wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

You could store your query results there and access them later.

share|improve this answer
    
The issue there is that the variable is being stored in the mark-up, meaning that anyone that knows how to use firebug can modify the variable and send bogus requests to my helper function. –  aprea Nov 2 '11 at 22:05
    
@aprea You can a) use a nonce within localize script and check this in the post which you then check back in your cb fn and b) you can assign anything (but a more dim. js-array) to the localized object. –  kaiser Feb 4 '12 at 3:28
    
@kaiser nonce only makes sense if users are registered. –  Mamaduka Mar 11 '12 at 9:52
    
@aprea You'll have to validate your result anyway. –  kaiser Mar 11 '12 at 14:36

If this is within the loop, you can use the_ID() or get_the_ID() and pass the value. I don't see how a helper function can know what the post is unless you tell it explicitly.

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.