I know similar questions to this have been asked before but I don't see an answer that suits my question. I have a div that triggers a jquery script which stores an id. I can get the id into a variable in the jquery but I want to then assign that id to a PHP variable that exists on the same page.
So far this is what I've got. Here is my div that exists in index.php
:
echo '<div id="'.$unit_id.'" class="dropdown unit '.$unit_size.' unit-'.$unit_number.' '.$unit_status.' data-unit-id-'.$unit_id.'">';
And here is my jquery that I call in from functions.php
:
<script>
$('.unit.available').click(function(){
var unit_id = $(this).attr('id');
$.ajax({
type: 'post',
data: {id: unit_id}, //Pass the id
});
});
</script>
I want to pass the unit_id
into a variable on index.php
called $getID
but I can't seem to find a way of getting in there. I've tried using post but there really isn't a form being submitted. It's just a dive being clicked on.
You must change your id
in your <div>
and set it to fetch the variable sent by jQuery. Other than that, your jQuery script looks fine.
Here's how I would do it:
# Fetch the variable if it's set.
<?php $unit_id = (isset($_POST["id"])) ? $_POST["id"] : null; ?>
# Echo it as the id of the div.
<div id = "<?= $unit_id; ?>" class = "dropdown unit"></div>
The PHP code above is equal to:
# Fetch the variable if it's set.
<?php
if (isset($_POST["id"])):
$unit_id = $_POST["id"];
else:
$unit_id = null;
endif;
?>
Assign id to div id attribute like this, Use:
<div id="<?php echo $unit_id; ?>" class="dropdown unit"></div>
Try this hope it will work
<div id="<?php echo $unit_id;?>" class="dropdown unit"></div>
<script>
$('.unit.available').click(function(){
var unit_id = $(this).attr('id');
$.ajax({
type: 'post',
'id='+unit_id, //Pass the id
});
});
</script>
What you mean by this '$unit_id' in div ID. Just put the code in PHP Tag, while working with PHP in HTML pages use the code inside PHP tags.
Availale PHP tags : <?php echo $unit_id ?>
(or) <?=$unit_id ?>
(short tag).
Change your div with :
<div id="<?=$unit_id ?>" class="dropdown unit"></div>
or
<div id="<?php echo $unit_id ?>" class="dropdown unit"></div>
Then your script will be work
<script>
$('.unit.available').click(function(){
var unit_id = $(this).attr('id');
// to check whether value passing or not
console.log(unit_id);
$.ajax({
type: 'post',
data: {id: unit_id}, //Pass the id
});
});
</script>