Home  >  Article  >  Backend Development  >  Can JavaScript Set PHP Session Variables?

Can JavaScript Set PHP Session Variables?

Linda Hamilton
Linda HamiltonOriginal
2024-10-22 14:53:02897browse

Can JavaScript Set PHP Session Variables?

Setting PHP Session Variables with Javascript

Question: Can JavaScript be used to set session variables in PHP?

Answer: Yes, it is possible to set PHP session variables using JavaScript. Here's how:

In JavaScript:

<code class="javascript">jQuery('#div_session_write').load('session_write.php?session_name=new_value');</code>

In session_write.php file:

<code class="php"><?php
session_start();

if (isset($_GET['session_name'])) {
    $_SESSION['session_name'] = $_GET['session_name'];
}
?></code>

In HTML:

<code class="html"><div id='div_session_write'> </div></code>

This code works by creating a hidden DIV element in your HTML and using jQuery's load() function to send an HTTP GET request to the PHP script (session_write.php) with the session data. The PHP script reads the GET parameter and sets the specified session variable.

The above is the detailed content of Can JavaScript Set PHP Session Variables?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn