Mallander
Mallander

Reputation: 336

jQuery AJAX, getting variable from HTML data attribute with jQuery, then giving that back to PHP

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.

Upvotes: 1

Views: 6364

Answers (1)

aziz punjani
aziz punjani

Reputation: 25776

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).

Upvotes: 2

Related Questions