1

As the title says I want to store an array of variables as a $_SESSION variable, so I can use it in another .PHP file and perform operations with it.

the array:

<script>
    var arrayIDs = [18, 28 31, 38, 41]
</script>

what I've tried, but didn't work:

<?php
    $_SESSION["arrayIDs"] = arrayIDs;
?>
progg24
  • 21
  • 1
  • 4
  • Did you check your error/warning logs? – bassxzero Dec 20 '20 at 08:42
  • What you have in the first snippet isn't a valid array declaration in any language. What you have in the second snippet is also invalid PHP. It looks like you're trying to mix PHP and Javascript. Study basic syntax for both first. – Markus AO Dec 20 '20 at 08:43
  • I am generating the coordinates randomly and then putting them in the array with a loop. – progg24 Dec 20 '20 at 08:44
  • 3
    You have fundamentally misunderstood the relationship between PHP and Javascript. You are creating the array in JavaScript which runs on the client machine. You're trying to somehow store that in a PHP session running on the server. You need to send the array to the server for that to happen. You can do this with AJAX, or by submitting a form. Either way is more complex than the rudimentary approach you've adopted here. – Tangentially Perpendicular Dec 20 '20 at 09:13
  • 1
    Highly recommended reading: https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming – ADyson Dec 20 '20 at 10:08

1 Answers1

1

Hi
JavaScript is the client side and PHP is the server side script language. The way to pass a JavaScript variable to PHP is through a request.
Let’s take a look at a simple example:

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
var arrayIDs = [18, 28 31, 38, 41]

$.ajax({
    url: 'main.php',
    type: 'post',
    data: {arrayIDs: arrayIDs},
    success: function(response){
        //do whatever.
    }
});
</script>

Your main.php file:

<?php
// Start the session
session_start();
$arrayIDs = $_POST['arrayIDs'];
$_SESSION["arrayIDs"] = arrayIDs;
?>

You should do sth like this and considet the session is a server side variable so you need to do it

other solution

If you want to dont use jquery you can do sth like this:

<script>
var arrayIDs = [18, 28 31, 38, 41]

var xhr = new XMLHttpRequest();
xhr.open('POST', 'main.php');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
    if (xhr.status === 200) {
        console.log(JSON.parse(xhr.responseText));
    }
};
xhr.send(JSON.stringify({
    arrayIDs: arrayIDs
}));
</script>

other solution

<script>
var arrayIDs = [18, 28 31, 38, 41]

fetch('main.php', {
  method: "POST",
  body: JSON.stringify(arrayIDs),
  headers: {"Content-type": "application/json; charset=UTF-8"}
})
.then(response => response.json()) 
.then(json => console.log(json));
.catch(err => console.log(err));
</script>
azibom
  • 1,769
  • 1
  • 7
  • 21