Mohamed Athif Mohamed Athif - 1 month ago 6
Javascript Question

ajax php post with sessions wont give results

I am trying to get pre set session variables through ajax and display in my modal. its like a cart. But when i try to get them there is no result at all when i read the ajax result from chrome inspect network or the modal. below is my code. what am i doing wrong here?

<script>
$("#cart-button").click(function(){
$.ajax({
url: "includes/cart-read.php",
success: function(data){

console.log(data);
alert(data);
$('#modal-body').empty().append(''+data+'');
}
});
});
</script>


and in cart-read.php

if(isset($_SESSION['dices'])){
foreach ($_SESSION['dices'] as $dice){

$msg = $dice;

echo json_encode($msg);

}
}


session dices is an array with simple numbers. such as 4, 5, 6.

Answer

Make sure you have the following things in your code

  1. Check if you have added session_start(); below after
  2. Try putting an else case to your session check,
  3. Try using an array to store and display the results.

    $result = array();
    $msg = array();
    if(isset($_SESSION['dices'])){
    foreach ($_SESSION['dices'] as $dice){
    
        array_push($msg,$dice);
        }
    
        if(sizeof($msg) > 0)
        {
            $result['status'] = true;
            $result['message'] = $msg;
        }
        else
        {
            $result['status'] = false;
            $result['message'] = 'No values';
        }
    }
    else
    {
    $result['status'] = false;
    $result['message'] = 'Session not set';
    }
    
      echo json_encode($result);