PaumaDregis
PaumaDregis

Reputation: 23

Attribute from php to Jquery.click within php foreach

I've been trying out different things for a while, but nothing seems to be working. And would probably need another kind of perspective.

For the question: I got a php foreach loop going, and every object is posting the ID of that object.

But my problem in this that when i click, the object is giving me the last number of the foreach. Ive been trying to post the value in JSON, and just plain php.

PHP

<?php
foreach ($places as $place) {
    $place_id = json_encode($place['id']);
    echo "<div class='placeContainer' onClick='openMessage(\'' . $place_id . 
'\')'>";
?>

Jquery

$(document).ready(function () {
    $('.placeContainer').click(function () {
        $(this).attr(phpvar);
        var myKey = JSON.parse(phpvar);
        console.log(myKey);
    })
});

Thanks for the help!

Upvotes: 2

Views: 52

Answers (1)

aprogrammer
aprogrammer

Reputation: 1774

Try this :

PHP Code :

<?php
foreach ($places as $place) {
    $place_id = json_encode($place['id']);
    echo "<div class='placeContainer' data-id='".$place_id."'>";
?>

JS Code :

$(document).ready(function () {
    $('.placeContainer').click(function () {
        var myKey = $(this).attr('data-id');
        console.log(myKey);
    })
});

Upvotes: 1

Related Questions