Convert the value of a Javascript variable into a PHP variable

I am feeling confused about how to pass JavaScript variables to PHP variables. Currently, I have a PHP session named example_survey and three buttons with jQuery attributes. When a button is clicked, it triggers a jQuery click event and passes the attribute value into a condition.

<?php
session_start();
if(!isset($_SESSION['loop_survey_2016'])){
  $_SESSION["example_servey"] = "0"; 
}?>

<button class="click_btn" data-status="0">btn 01 </button>
<button class="click_btn" data-status="1">btn 02 </button>
<button class="click_btn" data-status="2">btn 03 </button>

<script type="text/javascript">
$(document).ready(function(e) {
   $(".click_btn").on("click", function() {
      var status = $(this).attr("data-status");
      var session_val = '';

    if (status == '0') {
        session_val = 'empty';
    } else if(status == '1') {
        session_val = 'pending';
    } else if(status == '2'){
        session_val = 'complete';
    }

     <?php $_SESSION['example_servey'] ?> = session_val;
}); 
});
</script>

Is there a way to achieve this using pure JavaScript?

Answer №1

Since PHP operates on the server side and JavaScript functions on the client side, combining values between them directly is not possible. To accomplish this, utilizing jQuery and Ajax functions can facilitate the seamless transmission of data from client to server.

An illustrative example can be found at: How to Merge JavaScript and PHP or Setting Session Variable with JavaScript

Answer №2

PHP and Javascript serve different purposes - PHP is a server-side language, while Javascript is a client-side language. In order to achieve the desired outcome, you will need to send information from the client to the server using a request. One of the simplest and quickest methods to do so is by submitting a form and retrieving the form parameters with PHP upon page reload.

The Javascript code would look like this:

<form action="#" method="post">
<input type="hidden" value="<script>document.write(variable)</script>" name="my_var" />
<input type="submit">
</form>


<script type="text/javascript">
$( document ).ready(function(e) {
   $( ".click_btn " ).on( "click", function() {
      var status =  $(this).attr("data-status");
      var session_val = '' ;
    if (status == '0') {
        session_val = 'empty';

    } else if(status == '1') {
        session_val = 'pending';

    }else if(status == '1'){
        session_val = 'complete';
    }
     //Remove this line 
    <?php $_SESSION['example_servey'] ?> = session_val;

        $.post( "YOUR_PHP_FILE.php", { my_var : session_val } );
      }); 
    });
    </script>

And the PHP code would be:

<?php 
$javascript_var = $_POST["my_var"];
// Now you can use $javascript_var as a PHP variable
?>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the purpose of employing this expression in the context of requestAnimationFrame?

Can you explain the purpose of using this specific "if" statement in relation to requestAnimationFrame? if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime ...

Embracing Interfaces Over 'any' Types in TypeScript

https://i.stack.imgur.com/W6NMa.pngWould it be beneficial to utilize an interface as a variable type rather than opting for any? For instance, if I have 3 functions where I am declaring variables that can contain alphanumeric data, would defining them us ...

Replace the image with text inside an anchor when the anchor is being hovered

I want a logo (we'll call it .item-logo) to be shown inside a circle when not being hovered over, but when you hover over the container, the date should be displayed. Here is the HTML code: <div id="main-content" class="container animated"> ...

Variability in Swagger parameter declaration

Is it possible to specify input parameters in Swagger with multiple types? For example: Consider an API that addresses resources using the URL http://localhost/tasks/{taskId}. However, each task contains both an integer ID and a string UUID. I would like ...

Customizing Your WordPress Menu with HTML5 Features

Can someone assist me in creating a customized WordPress menu? I am facing issues with unnecessary classes added by WordPress and the lack of certain attributes on dropdowns. Below is the HTML code: <nav class="navbar navbar-default navbar-static- ...

Locate the initial ancestor element, excluding the parent element that comes before the root ancestor

My HTML structure is as follows: <div> <ul> <li> <div>Other elements</div> <div> <ul> <li class='base-parent parent'> <div>Base Parent ...

What is the process for exporting a chart into Excel?

My current challenge involves displaying data extracted from a database in the form of a bar chart and then exporting both the data and the chart as an image into an Excel file. While I have successfully displayed the bar chart, I am facing difficulties in ...

Issue in PHP Wordpress when trying to access an index that is

I seem to be facing a common issue that others have experienced, but I can't quite figure out where the problem lies. (I've double-checked the isset() function in my code and it appears fine, yet it's still not allowing an email message to b ...

Issue with date comparison capability within Aggregate feature while utilizing mongoDB and PHP

I've successfully created a query with date comparison in mongoDB, but when I try to convert that query into a PHP array and execute it using the aggregate method, I'm not getting any data back. Here is the mongoDB Query converted into PHP: $da ...

AJAX function in Chrome console is throwing an error message stating "Unexpected Token }"

Dealing with this issue has been quite unusual for me. I've spent the last 3 days trying to troubleshoot it, but now it's no longer bothering me. The situation involves a button and a textbox that sends the data from the textbox to a PHP page whe ...

Controllers in Laravel are not detecting the public function

Recently, I obtained a Laravel/Vue.js project from Bitbucket for the company I am currently collaborating with. Setting it up on my computer seemed like a routine task since I have worked on similar projects in the past. However, this time around, I encoun ...

Enclose each instance of "Rs." with <span class="someClass">

I'm facing an issue with the currency symbol "Rs." appearing in multiple places on my website. I want to enclose every instance of this text within <span class="WebRupee">. However, if it's already wrapped in <span class="WebRupee">, ...

What is the best way to get the latest props in the midst of an async function?

There's a fascinating open-source project called react-share, where the ShareButton component offers a prop known as beforeOnClick for customization. I've utilized this beforeOnClick to upload images to our CDN before sharing, ensuring that only ...

Styling multiple Higher Order Components (HoCs) using Material UI withStyles

When developing my application, I encountered an issue with using Higher Order Components (HoCs) and withStyles for styling. If I apply multiple HoCs to one component, the classes prop of the first HoC gets passed to the next one in the compose chain, caus ...

Tips for extracting the chosen value from a dropdown list within a table cell using JavaScript

Here is an example of an HTML element: <td> <select> <option value="Polygon 47">Polygon 47</option> <option value="Polygon 49">Polygon 49</option> </select> </td> I am looking for a ...

Caution: React detecting an active event listener on a scrolling-dependent 'touchstart' action

I am facing an issue with a React component that contains a Material-UI Slider. Whenever this component renders, I receive the following warning message: "Added non-passive event listener to a scroll-blocking 'touchstart' event. Consider marking ...

Unveiling and Shifting Among Concealed HTML Forms

After going through numerous tickets with similar questions, I still can't seem to achieve what I want. So, I have no choice but to ask this question myself. I currently have an HTML page with 2 forms and 2 buttons. Both forms are initially hidden us ...

Opt for Observable over Promise in your applications

I have implemented this function in one of my servlets: private setValues() { this.config.socket.on('config.weather', (values:any) => { console.log(values); } However, I would like to refactor it to something like this: private se ...

Anticipate that the function parameter will correspond to a key within an object containing variable properties

As I develop a multi-language application, my goal is to create a strict and simple typing system. The code that I am currently using is as follows: //=== Inside my Hook: ===// interface ITranslation { [key:string]:[string, string] } const useTranslato ...

What could be causing the EBUSY: resource busy or locked, open errno: -4082 error to appear while trying to build storybook 7 in next.js 13?

While attempting to create a storybook, I encountered the following error in my project: [Error: EBUSY: resource busy or locked, open 'C:\Users\ali\Desktop\Works\Design Systems\projects\storybook-test2\node_modu ...