dongqing7789 2015-12-08 05:06
浏览 67
已采纳

使用AJAX在PHP中设置会话变量

After a user clicks a div this javascript function runs:

$('.test').click(function(e)
    {
        e.preventDefault();
        $.ajax({
            url: 'ajax.php',
            type: 'POST',
            data: {"id": "<?php echo $rows['id']?>"},
            success:function(data){
                window.location.href = 'index.php';
            }
        });
    });

I want to pass in an ID associated with the div the user clicks into my ajax.php file where this code runs:

<?php
    session_start();
    //connect to db here
    $_SESSION['id'] = $_POST['id'];
?>

However this is not working. To expand further what I did to pass get the rows['id'] variable is run this SQL code:

$sql_select = "SELECT id FROM ids WHERE id = '$id'";
$results_select = $conn->query($sql_select);

I then outputted a bunch of divs with id's corresponding to them:

<?php
    while ($select_rows = mysqli_fetch_array($results_select))
    {
        echo "<div class = 'test'></div>";
    }
?>

Does anyone know how I can accomplish this?

  • 写回答

2条回答 默认 最新

  • doucheng5705 2015-12-08 05:12
    关注

    Use data attributes:

    Try:

    <?php
        while ($select_rows = mysqli_fetch_array($results_select))
        {
            echo "<div data-id='".$rows['id']."' class = 'test'></div>";
        }
    ?>
    

    js:

    $('.test').click(function(e)
        {
            e.preventDefault();
            $.ajax({
                url: 'ajax.php',
                type: 'POST',
                data: {"id": $(this).attr('data-id')},//fetch the data attribute 
                success:function(data){
                    window.location.href = 'index.php';
                }
            });
        });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算