• Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Set JavaScript variable from PHP

How I can set the JavaScript variable strUser from PHP?

I am using the following code:

Joshua Dwire's user avatar

2 Answers 2

If you want to set the variable when the page loads, you could use something like this in the PHP code:

Just make sure to remove the later variable declaration from the JavaScript.

If you want to set the variable after the page loads, you'll have to use an AJAX call to ge the value from the server.

Use Cookie in your javascript

in your php

Padmanathan J's user avatar

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged php javascript or ask your own question .

Hot Network Questions

set javascript variable with php

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

DEV Community

DEV Community

Supun Kavinda

Posted on Jul 13, 2019 • Originally published at groups.hyvor.com

How to create Javascript variables from PHP variables?

Sometimes, you may need to declare dynamic JS variables using PHP.

One thing you can do is to manually write the JS code as following.

But, we can create a function to do this easily with a better data types support.

This function requires an PHP array, which contains key/value pairs which are the Javascript variable name and the value. Also, this function automaically creates Javascript variables according to the data type of the PHP variable.

PHP Arrays will be converted into JSON format. If you don't need the '<script>' tags, just remove those two echo statements.

I previously published this post on PHP Group on my new website, Hyvor Groups.

Top comments (2)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

msamgan profile image

nice article, but this will only work if we are using JS in the same PHP file. What if we include the js from some other file?

supunkavinda profile image

I think you are talking about adding some PHP variables into a Javascript file. For example, you need index.js to have some dynamic variables to be set with PHP.

If it is what you meant, you can include the js file and the JS file should contain PHP in it.

This will execute the PHP code in it and echo the contents to the current PHP file. But, having PHP code inside a Javascript file is a mess, in my opinion.

If you need to use this approach, I would recommend adding those dynamic variables into your PHP file. You can use an include for this. Here's how I do that.

And, js-config.php will have something like:

If you don't need the Javascript variables (or JSON data) on the page load, the best way is to fetch the data from the server using AJAX.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

Classic DEV Post 👇

Visualizing promises and async/await 🤯, my favorite courses to learn coding and programming in 2023.

javinpaul - Feb 19

alexandrg profile image

Visual regression tests for Storybook with Loki

Oleksandr Hrishchuk - Feb 22

snowiewdev profile image

9 Useful Chrome Extensions for Web Developers / Web Development

Snowie Wong - Feb 21

rms profile image

Trending JavaScript repos of the week 📈

Rodrigo M.S. - Feb 22

Once suspended, supunkavinda will not be able to comment or publish posts until their suspension is removed.

Once unsuspended, supunkavinda will be able to comment and publish posts again.

Once unpublished, all posts by supunkavinda will become hidden and only accessible to themselves.

If supunkavinda is not suspended, they can still re-publish their posts from their dashboard.

Once unpublished, this post will become invisible to the public and only accessible to Supun Kavinda.

They can still re-publish the post if they are not suspended.

Thanks for keeping DEV Community safe. Here is what you can do to flag supunkavinda:

supunkavinda consistently posts content that violates DEV Community's code of conduct because it is harassing, offensive or spammy.

Unflagging supunkavinda will restore default visibility to their posts.

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Data Structure

How to pass JavaScript variables to PHP?

You can easily get the JavaScript variable value on the same page in PHP. Try the following codeL.

Johar Ali

0 Followers

Tutorials Point

Related Articles

How to pass variables and data from PHP to JavaScript ?

In this article, let’s see how to pass data and variables from PHP to JavaScript.

We can pass data from PHP to JavaScript in two ways depending on the situation. First, we can pass the data using the simple assignment operator if we want to perform the operation on the same page. Else we can pass data from PHP to JavaScript using Cookies. Cookie work in client-side.

Program 1: This program passes the variables and data from PHP to JavaScript using assignment operator.

Here, we just take input by statically or dynamically and pass it to JavaScript variable using the assignment operator. The PHP code in the JavaScript block will convert it into the resulting output and then pass it to the variable x and then the value of x is printed.

Program 2: This program passes the variables and data from PHP to JavaScript using Cookies.

PHP provides a method to set the cookie using the setCookie() method. Here, we can set the data or variable in PHP cookie and retrieve it from JavaScript using document.cookie.

Steps to Run the program:

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples .

Please Login to comment...

Improve your Coding Skills with Practice

Start your coding journey now.

Image

How to Pass a PHP Variable to JavaScript – Easy Way

set javascript variable with php

For something seemingly so straight-forward, you would think that the information out there would be a bit better on this subject. Passing a variable from PHP to JavaScript is actually very easy! There are just a couple things you need to keep in mind and some ways to do it to ensure it actually works.

I find that putting the following code into the <head> section of my website is the most foolproof method:

That’s it! You just define the PHP variable first, then echo it into a basic JS variable declaration statement. I know there are lots of ways to define a JavaScript variable, but this is the one I find works in the most circumstances. I’m not an expert here, but most of the others seem to not work a lot of the time.

A few things to keep in mind for this:

1. The PHP variable needs to be defined before the JS one. 2. The JS variable needs to be defined before you actually use it anywhere. This seems obvious, but if you forget this fact and try to put this declaration into the footer of your site and then use it in the content, you’ll find it doesn’t work! That’s why I like to put this in the head section of my website. Or, if you were in WordPress or another CMS, make sure to place it in the header.php file of your active theme.

Additionally, you should be aware that if your variable is not a string and is instead a number, you would want to define it without the quotes around it, i.e.:

Note that as Sherri mentioned in the comments, if you have more complicated strings or any strings with quotes (“) in them, this will break. You’ll want to look into json encoding if needed. But for simple strings and variables, this should do the trick.

Hard to go wrong with any of this. There are of course more complicated ways to use this, but I’m not going to go into any of those here. Let me know if you have any problems!

12 Comments on “How to Pass a PHP Variable to JavaScript – Easy Way”

' src=

This just helped me a ton. Thank you!

' src=

The scenario:

1. There is a php script which (possibly complemented by a direct written HTML code) consrtucts a HTML page via its echo command, based on whatever algoritmus eventually based on supplementary data from server files or databases.

2. This php script leads to data being saved into string variable(s), which (possibly) can contain arbitrary characters, including control codes (newline, tab…), HTML special characters (&,<…) and non-ASCII (international) characters.

3. These non-ASCII characters are UTF-8 encoded, as well as the HTML page (I do highly recommend) *)

4. The values of these PHP string variables have to be transferred into javascript variables for further processing by javascript (or exposing these values in HTML directly)

The problem:

it is not safe to PHP-echo such variables into HTML (javascript) directly, because some of characters possily contained in them cause malfunction of the HTML. These strings need some encoding/escaping in order to become strings of non-conflicting characters

The solution

There may be a big lot of ways of this encoding. The following one seems to me the easiest one: The PHP variable with unpredictable value can originate from some file, as an example (or from user input as well):

$variable=file_get_content(…)

1. Convert all bytes of that string into hex values and prepend all hex-digit-pairs with %

$variable_e=preg_replace("/(..)/","%$1",bin2hex($variable))

The new variable is now guarantied to contain only %1234567890abcdefABCDEF chracters (e.g. %61%63%0a…) and can safely be directly echoed into HTML:

var variable="” //that’s NOT all folks

But now the value is still encoded. To get the original value of the variable, it has te be decoded: *)

var variable=decodeURIComponent(“”)

The value of the variable is now the same as the original value.

*) I have no idea about non-UTF-8 encoded pages/data, espetially how the decodeURIComponent works in such a case, because i have no reason to use other encodings and handle them as highly deprecatad.

WARNING: this approach is not (generally) safe against code injection. I highly recommend some further check (parsing) of the value depending on the particular case.

P.S. For very large amount of data, I would recomment to save them into file on the PHP side (file_put_content) and read them by javascript via HTTP Request.

I use this approach as it needs one line of code on server as well as client side. I do agree with arguement that not all chaeacters have to be encoded.

Do not enjoy my possibly stupid solution, if you have a better idea

' src=

2. This php script leads to data being saved into string variable(s), which (possibly) can contain arbitrary characters, including control codes (newline, tab…), HTML special characters (&,<…) and non-ASCII (international) characters.

$variable_e=preg_replace("/(..)/","%$1",bin2hex($variable))

var variable="” //that’s NOT all folks

' src=

And remember, that whatever variables you add to your javascript, will be visible when anyone uses their browser to view the code in the page.

' src=

First, thanks for a great write up. I’m hoping you can offer me a simple solution here. I have to say first that I’m dealing with an ordinary http: page, and I absolutely want to avoid setting up my .htacess file to allow PHP parsing of HTML files (among many reasons, it cases some old browsers to attempt to download rather than display the page!). My page is for my own music, and I use php calls withing HTTP requests to allow visitors to download songs, for example like click here . Things like this work fine (In this case The PHP will find the file and initiate a download ). Now the only thing missing is that I need to be able to retrieve a simple value from the PHP call. For example if I’m checking the authorization of the visitor based on some passed cookie. Since the page itself is .html and not .PHP, the page is not going to be redisplayed, and so an ‘echo’ probably won’t work. Best thing i can think of is having the php write the results I want into a temporary file (on thye server side of course) which I could then read with a javascript XMLHttpRequest(), run within a page wide javascript intervalTimer. This sounds like an awkward rupe goldber approach though. And to make matters worse (maybe) I’m committed to learning to do things in pure PHP and javascript, without loading in jquery, ajax, or other helper libraries.

' src=

Why exactly are you using .html pages instead of .php? It seems like it would solve all of your problems just to fix that. And it’s not hard at all to do… Just rename them “.php” and add “ ” to the beginning of the document and “ ” to the end and voila! You’re done. PHP and html work perfectly together. At that point you could add whatever PHP you want to the page, just remember to start each php line with “ “.

' src=

Actually that’s exactly what Sherri was talking about.

Here is the trick :

In my php file, I put this

https://codeshare.io/507Dyn

(My code is on an external website cause I can’t write code here. It gonna expire in 24h… so please modify my reply with the code in it.

And now there is a variable called js_variable that I can use in any javascript.

Thank you all.

' src=

Is is possible to do the opposite? I’m trying to update a field in wordpress’ database on a button click. I’ve tryied somethings. But so far couldn’t make it work. Chrome didn’t allowed me to post the code here. But the answer to this question is what I’ve tryied so far. https://stackoverflow.com/questions/51372897/how-can-i-save-the-value-of-a-custom-field-to-wordpress-user-meta-after-alterin

PHP is server-side and happens before the page is rendered, so no. But you could pass the JS variable as a URL parameter or something and go to a new page or refresh the current page to get it.

' src=

Stumbled on this while looking for a package to convert php vars to js.

No clue how old this article is…but. Please don’t follow this recommendation. The second your string contains a double quote, it will break. If you want to use other types you have a world of headaches.

A better method is to json_encode the value before giving it to the js.

That may be true, but for my purposes (and likely the purposes of most of the people here), we don’t need to worry about quotes being in our variables. Generally I’m just doing something quick and easy and don’t want to go through the trouble of encoding and doing other complicated things that really aren’t necessary for what I’m doing.

I try to pass something like $array[‘info1’][‘info2’].

But it doesn’t work, my var contain a string.

Here is what I put in my js script :

var data = “”;

My php script is called in the top of the page and the javascript on the bottom.

Maybe it’s linked about what Sherri was talking about. I don’t really know. I’m not good at all at javascript.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Projects

set javascript variable with php

Homes by Tradition

set javascript variable with php

Society of Clinical Psychology

set javascript variable with php

Unmapped Brewing

set javascript variable with php

River School of Music

set javascript variable with php

Hedgehog Project

set javascript variable with php

Momentum Design Group

Never worry about missing important WordPress updates again by subscribing to our newsletter.

Do you like what you see?

set javascript variable with php

set javascript variable with php

How to pass the javascript value to a PHP variable?

set javascript variable with php

Add your solution here

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Print

devsheet logo

Assign a Javascript variable to PHP variable

Why do we assign a javascript variable to a php variable .

There are many reasons why one might want to assign a Javascript variable to a PHP variable. Some possible reasons include:

-To pass data from Javascript to PHP (for example, to use PHP to process or store data that was entered into a form via Javascript)

-To make use of PHP's built-in functions and libraries from within Javascript

-To take advantage of PHP's faster execution speed when working with large data sets or complex algorithms.

Use document.cookie and $_COOKIE to assign a JS variable to a PHP variable

The document.cookie is used to store cookies in javascript and  $_COOKIE is a PHP superglobal variable that is used to access cookies. We will use document.cookie to store javascript variable value to a cookie and access it in PHP using $_COOKIE .

In the above code example:

user image

The first time you log in it doesn't work. If you reload the page everything is fine. This is because php will execute first only then the javascript.

IMAGES

  1. How to Set PHP Variable in JavaScript With Example

    set javascript variable with php

  2. 39 Set Javascript Value To Php Variable

    set javascript variable with php

  3. 33 Set Javascript Variable From Php

    set javascript variable with php

  4. 39 Set Javascript Value To Php Variable

    set javascript variable with php

  5. 39 Javascript Set To Array

    set javascript variable with php

  6. JavaScript Sets: What They Are and How to Use Them

    set javascript variable with php

VIDEO

  1. Javascript Variable

  2. php://input

  3. ReDeclare same JavaScript variable Using var #shorts

  4. Variables in PHP

  5. Javascript Variable Scope #ytshorts #javascript #programming #coding

  6. Javascript for Beginners

COMMENTS

  1. Set JavaScript variable from PHP

    Set JavaScript variable from PHP ; function val() { var e = document.getElementById("ali"); var strUser = e. · options[e. · selectedIndex].text; }

  2. How to create Javascript variables from PHP variables?

    Sometimes, you may need to declare dynamic JS variables using PHP. One thing you can do is to manually write the JS code as following. var x = "

  3. How to assign a PHP variable to JavaScript

    PHP tags with single or double quotes assign a PHP value to a JavaScript variable when setting a PHP variable. Several times you might need

  4. How to pass JavaScript variables to PHP

    You can easily get the JavaScript variable value on the same page in PHP. Try the following codeL. <script> var res = "success";

  5. How to pass JavaScript variables to PHP ?

    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.

  6. How to pass variables and data from PHP to JavaScript

    How to pass variables and data from PHP to JavaScript ? · Install local server like XAMPP server into your system. · Save the file in htdocs

  7. HTML : how to assign javascript variable value to php variable

    HTML : how to assign javascript variable value to php variable [ Beautify Your Computer : https://www.hows.tech/p/recommended.html ] HTML

  8. How to Pass a PHP Variable to JavaScript

    $php_variable = 'string'; //Define our PHP variable. You can of course get the value of this variable however you need. ?> <script>

  9. How to pass the javascript value to a PHP variable?

    Solution 1 · 1. Add a hidden field. HTML. <input type="hidden" id="btnClickedValue" name="btnClickedValue" value="" /> · 2. Store the button inner

  10. Assign a Javascript variable to PHP variable

    Use document.cookie and $_COOKIE to assign a JS variable to a PHP variable · We have a Javascript variable named user_name that contains a string value. · We are