1

I'm trying to get the "data-postid" attribute from this HTML/PHP code, which I am then trying to use to get the unique div clicked which will then display the appropriate lightbox on click (I'm using a WordPress site, hence the Wordpress code):

EDIT: Changed the code to show current versions, and a new file called "myfile.php"

HTML/PHP Code (index.html):

<div class="person-row">
  <div id="post-<?php the_ID() ?> <?php post_class(); ?>" class="person" data-postid="<?php the_ID() ?>">
 </div>

JQuery Code (script.js):

var $post = $(this);
        var identifier = ($post.data("postid"));

        $.ajax({
            url: "myfile.php",
            type: "POST",
            data: { postNumber: (identifier) },
            dataType: "text",
            success: function(response) {
                alert(response);
            }
        });

Then trying to get it back into the PHP to use

PHP Code (myfile.php)

<?php $post = $_POST['postNumber'] ?>

PHP Code (index.html)

<?php $PID = $_GET['postNumber'] ?>

Any help would be much appreciated. If there is anything else you need to know I'll be happy to supply it.

14
  • At a glance, that looks fine. What is or isn't happening that shouldn't or should be? What has your debugging revealed about where things stop working? Commented Nov 11, 2013 at 14:18
  • 1
    You can change $($post).attr("data-postid") to $post.data("postid") Commented Nov 11, 2013 at 14:23
  • What does the the_ID() PHP function contain? Commented Nov 11, 2013 at 14:23
  • Please use htmlspecialchars when outputting to HTML to prevent XSS. Commented Nov 11, 2013 at 14:27
  • I think you might have an incorrect name in you JS. Try data: { postid: $post.attr("id") } as you've used "id" as an attribute in your html instead of "data-postid" (attribute name instead of attribute value). Commented Nov 11, 2013 at 14:37

1 Answer 1

2

Your code is not optimal, but in theory it should work. You can however improve it.

$post = $(this);
$.ajax({
    url: "index.php",
    type: "GET",
    data: { postid: $($post).attr("data-postid") }, 
    success: function(response) {
       alert(response);  
    }
});

As stated by Misiur. You can change $($post).attr("data-postid") to $post.data('postid'). jQuery provides support for accessing data attributes so there's no need to use .attr.

You were also had $post wrapped in a jQuery object, no need to re-wrap it i.e no need to do this $($post).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.