1

I have a code using javascript ajax like this :

$.ajax({
  type: "POST",
  url: "<?= site_url('test/test'); ?>",
  dataType: "JSON",
  data: {
    id: id,
    name: name,
  },
  success: function(data){
    var data = {
      "id": id,
      "name": name,
    }
    <?php if ($this->session->userdata('class') == 'employee') { ?>
       console.log('a');
    <?php } else { ?>
       console.log('b');
    <?php } ?>
  }
})

can I use session inside ajax code?

Alif
  • 93
  • 7
  • never mix php and js - they're different languages that get executed differently – treyBake Jan 23 '20 at 09:31
  • so what should i do, if i want make a session? – Alif Jan 23 '20 at 09:35
  • 1
    Yes you can! but not recommended the way you use in question, try like this `var value = '';` –  Jan 23 '20 at 09:35
  • @Alif you're already using ajax ... return the session values in the success response – treyBake Jan 23 '20 at 09:36
  • @Dilek it's not recommended full stop. They execute differently and leads to unexpected behaviour. – treyBake Jan 23 '20 at 09:36
  • if i make a variable and then i call the variable, is it possible to use? – Alif Jan 23 '20 at 09:37
  • 2
    @Alif you need to use the ajax response (what you call data) and then don't overwrite the response straight away, then use normal JS to do the conditional on the result value – treyBake Jan 23 '20 at 09:37
  • i'm confused when i trying to cath the session, because i need to make a condition with the session – Alif Jan 23 '20 at 09:38
  • Yes ali.! @treyBake I know them executes differently, but we all need to use it that way sometimes and I realy dont think it will cause a problem. if you are using it right way. –  Jan 23 '20 at 09:39
  • See this question for how to get response from php @Alif https://stackoverflow.com/q/59489824/12232340 –  Jan 23 '20 at 09:59
  • @Dilek I don't think I've ever *needed* to mix them, but I guess it's all down to how you set up the architecture – treyBake Jan 23 '20 at 14:44

2 Answers2

5

You should separate out the code:

PHP-side:

<?php
    # what ever other code there is

    echo $this->session->userdata('class');

JS-side:

$.ajax({
    type: 'POST',
    url: '/path/to/phpfile.php',
    dataType: 'JSON',
    data: {id: id, name: name},
    success: function(response)
    {
        var data = {
            'id': id,
            'name': name,
        }

        if (response == 'employee') {
            console.log('a')
        } else {
            console.log('b')
        }
    }
})

Now we only check the response value instead of mixing languages in a way that has no benefit. We set the response valueto the session value and perform a normal JS conditoinal to console.log()

treyBake
  • 6,440
  • 6
  • 26
  • 57
4

You can only use a PHP variable (such as Session) as something you embed into the code as a hard-coded value e.g. if you write var x = '<?php echo $_SESSION["x"]; ?>'; then you create a JS variable x which has has the value of the Session value when the script starts. Assuming the Sesion value in that example was "hello" then in the final JavaScript which your browser receives and executes, you will see the following line: var x = "hello"; as a hard-coded snippet.

This is because PHP executes on the server, and generates the HTML and JS which is then sent to the browser after the PHP stops executing.

What you can't do is just write PHP inline in the JavaScript the way you've done in your example, and expect it to do anything. That PHP will execute before your JavaScript, and the result / output of the PHP (if anything) will be embedded in the JavaScript (or used to control exactly what JavaScript is generated and sent to the browser).


If you need to interact with the server during the execution of JavaScript code, but without posting back the whole page, then you need to make an AJAX request, so it generates a new HTTP request to the server, which can execute a PHP script and then return the response back to JavaScript to process.

In the specific example in your question, since you are already making an AJAX request, which can return data from PHP to JavaScript, I suggest you simply include the required Session value in the response data, and then write some JavaScript to read that value and decide what to do.


Further reading: What is the difference between client-side and server-side programming?

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • 2
    Thanks @ADyson I couldnt explain, I gave example in my comment +1 –  Jan 23 '20 at 09:41
  • so i can use that method but I must create the variable in javascript first right? – Alif Jan 23 '20 at 09:44
  • Yes! @Alif that is what you have to do exactly. –  Jan 23 '20 at 09:46
  • @Alif Yes. But see my edit - in your case, you're already making an AJAX request, so actually the sensible thing to do would be to include the Session value in the response data that PHP gives back to the AJAX request. Then you know you have got the latest value, and you don't have to resort to embedding it in the JS (which, while it can work, is not always an ideal practice, if you can it's better to keep the JS and PHP separate as much as possible, as it usually makes the code easier to maintain and debug). Treybake's answer demonstrates a simple version of this – ADyson Jan 23 '20 at 09:46
  • ok I use that method thanks for the solving for my problem, Have a nice day guys! – Alif Jan 23 '20 at 09:47