dth34653 2016-07-01 05:32
浏览 132
已采纳

将值从jquery传递到同一页面中的php变量

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.

  • 写回答

4条回答 默认 最新

  • duanjia3187 2016-07-01 05:43
    关注

    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>
    


    EDIT:

    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;
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里