Passing PHP Variables into JavaScript Tutorial

In this tutorial, we will tackle about how to Pass PHP Variables into JavaScript. This tutorial aims to provide solutions and references to beginners or new programmers to enhance their programming skills. Here, I will be providing multiple solutions with snippets and sample scripts for said topic or situation needed for coding.

Why do you need to Pass PHP variables into JavaScript?

Passing PHP variables into JavaScript is not a requirement for building or developing a PHP Project or Web application. Although, a lot of programmers use PHP Language as the Backend for coding or developing dynamic websites such as organization sites, content management sites, blogs, etc. Programmers or developers commonly use JavaScript to give the end-users a better experience while using the web application. Aside from CSS (Cascading Style Sheets), JS helps the programmers to create more creative UI/UX such as manipulating DOM or changing Elements data without leaving or refreshing the page. Passing PHP Variables to PHP helps the developer to manage the dynamic data on the client side.

How to Pass PHP Variables into JavaScript?

I will be providing 3 Solutions or ways on how to Pass PHP Variables into JavaScript. These 3 techniques are the best way and most effective that I can think of to achieve our goal for this tutorial.

The 3 Solutions for Passing PHP Variables into JS

  1. Setting a JS Variables with PHP Values
  2. Using JS Fetch API
  3. Using Ajax Reuests

Setting a JS Variables with PHP Values

We can pass PHP variable simply by setting JavaScript variables with PHP Values. This solution can be only used if the PHP variable is callable on the current page or script of your project. Before setting the JS variables, make sure that the PHP variables values are already set.

Here is the sample snippets for this solution:

PHP Script

  1. <?php
  2. $variable1 = "Hello World!";
  3. $variable2 = "My Sample Data.";
  4. $variable3 = ["a" => "PHP", "b" => "JavaScript"];
  5. ?>

JS Script

  1. var variable1 = '<?= $variable1 ?>',
  2. variable2 = '<?= $variable2 ?>',
  3. variable3 = '<?= json_encode($variable3) ?>';
  4.  
  5. console.log(`---- Solution 1: Setting a JS Variables with PHP Values ----`);
  6. console.log(`Variable #1: ${variable1}`);
  7. console.log(`Variable #2: ${variable2}`);
  8. console.log(`Variable #3:`, JSON.parse(variable3));

Using JS Fetch API

We can also pass the variables from PHP to JS using the JS Fetch API. This solution will create a request to the other page or file and return the data needed. Using this, setting PHP Variables on the page will be no longer a requirement because PHP Variables and data will be given from the request-response.

Here is the sample snippets for this solution:

PHP Script

  1. <?php
  2. $variable1 = "Hello World!";
  3. $variable2 = "My Sample Data.";
  4. $variable3 = ["a" => "PHP", "b" => "JavaScript"];
  5. ?>

JS Script

  1. fetch('./vars.php')
  2. .then((response)=>{
  3. return response.json();
  4. })
  5. .then((data)=>{
  6. console.log(`---- Solution 2: Using Fetch API of JS ----`)
  7. console.log(`Variable #1: ${data.variable1}`)
  8. console.log(`Variable #2: ${data.variable2}`)
  9. console.log(`Variable #3:`, data.variable3)
  10. })

Using Ajax Request

This solution requires you to load the jQuery Library on the current page. The jQuery Library must be loaded first before the browser will read and execute your Ajax Request. This solution is similar to Fetch API.

Here is the sample snippets for this solution:

PHP Script

  1. <?php
  2. $variable1 = "Hello World!";
  3. $variable2 = "My Sample Data.";
  4. $variable3 = ["a" => "PHP", "b" => "JavaScript"];
  5. ?>

JS Script

  1. $(function(){
  2. $.ajax({
  3. url:'./vars.php',
  4. dataType:'json',
  5. error:err=>{
  6. console.error(err)
  7. },
  8. success: function(resp){
  9. console.log(`---- Solution 3: : Using AJAX Request ----`)
  10. console.log(`Variable #1: ${resp.variable1}`)
  11. console.log(`Variable #2: ${resp.variable2}`)
  12. console.log(`Variable #3:`, resp.variable3)
  13. }
  14. })
  15. })

DEMO VIDEO

There' you have it! You can test the solutions on your end using the snippets I provided above. You can also download the simple script I created that demonstrates the main goal of this tutorial. The source code contains all the 3 solutions and can be validated using your browser's DevTools Console. The download button is located below this article.

I hope this tutorial will help you with what you are looking for and you'll find this useful for your current and future projects. Explore more on this website for more Tutorials and Free Source Codes.

Add new comment