Skip to content Skip to sidebar Skip to footer

Setting A Session Variable In Php Using Ajax

After a user clicks a div this javascript function runs: $('.test').click(function(e) { e.preventDefault(); $.ajax({ url: 'ajax.php', ty

Solution 1:

Use data attributes:

Try:

<?phpwhile ($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';
            }
        });
    });

Solution 2:

Please check your JS code for data: {"id": "<?php echo $rows['id']?>"}. This line may not be able to pass your actual value so store it into div with id attribute and get it by jQuery and pass it.

JS:

$('.test').click(function(e)
{
    dataValue = $(this).attr('id');//Get user clicked div id attribute value...
    e.preventDefault();
    $.ajax({
        url: 'ajax.php',
        type: 'POST',
        data: {"id": dataValue},
        success:function(data){
            window.location.href = 'index.php';
        }
    });
});

PHP:

With above JS code you need to make some change for PHP code as well:

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

Please confirm this code by print_r($_POST); on AJAX post handler page. This will print the POST data requested by AJAX code.

Let me know if there is any concern regarding this.

Post a Comment for "Setting A Session Variable In Php Using Ajax"