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

将值从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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵