LaVOZs

The World’s Largest Online Community for Developers

'; javascript - How to get variable session in jQuery dataTables? - LavOzs.Com

I have an API called all_device with 1 parameter which is username (Image below), so I want to read current logged in user session.

enter image description here

This is what I have try.

$(document).ready(function(){
    var username = '<%= Session["username"] %>';
    console.log(username);
    var ManageDeviceTable = $('#manageDevice').DataTable({
        ajax: { 
            url: api_url+'/all_device',
            crossDomain : true,
            type : "POST",
            cache : false,
            data: {username: username},
            dataType : "json",
            contentType: "application/json",
            dataSrc : "data",
        },
    });
});

Console log

enter image description here

PHP

<?php
header('Content-Type: application/json');
$post_data = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

session_start();

$_SESSION["id"] = $post_data["id"];
$_SESSION["fullname"] = $post_data["fullname"];
$_SESSION["username"] = $post_data["login"];
$_SESSION["email"] = $post_data["email"];

echo json_encode(array('msg' => 'Session created.', 'session' => $_SESSION));
exit;

?>

PHP >= 7.0 not supports short open ASP tags. You have to change like:

var username = '<?php echo $_SESSION["username"];?>';

Or

var username = '<?= $_SESSION["username"];?>';
Related
Is there an “exists” function for jQuery?
How do JavaScript closures work?
How do I check if an element is hidden in jQuery?
How do you get a timestamp in JavaScript?
Setting “checked” for a checkbox with jQuery?
How do I redirect to another webpage?
How do I check whether a checkbox is checked in jQuery?
How to check whether a string contains a substring in JavaScript?
How do I remove a particular element from an array in JavaScript?
How do I return the response from an asynchronous call?