Backend Development 3 min read

How to Pass Values from PHP to JavaScript

This article explains several practical techniques—including echo, json_encode, HTTP headers, and external script files—for transferring data from PHP to JavaScript, helping developers choose the most suitable method based on data complexity and application requirements.

php中文网 Courses
php中文网 Courses
php中文网 Courses
How to Pass Values from PHP to JavaScript

In PHP and JavaScript interaction, values need to be passed to achieve data exchange and cross‑language communication. The following methods show how to transfer values from PHP to JS.

1. Use echo to output a variable

$value = 'Hello JS';
echo "
";

This outputs a script block in the HTML that assigns the JavaScript variable jsValue the value Hello JS .

2. Use json_encode function

$data = array('name' => 'John', 'age' => 30);
$json = json_encode($data);
echo "
";

The json_encode function converts a PHP array or object to a JSON string, which can then be assigned to a JavaScript object.

3. Use header function

header("X-JS-Data: " . json_encode($data));

This adds a custom HTTP response header; JavaScript can retrieve the header value via an XMLHttpRequest.

4. Use an external JavaScript file

Include an external script and pass the value through a data attribute.

<script src="script.js" data-value="
"></script>

In script.js :

var value = document.querySelector('script[data-value]').getAttribute('data-value');

Choosing the appropriate method

The choice depends on the specific requirements and technical constraints of the application:

For simple strings or numbers, the echo method is convenient.

For complex data structures such as arrays or objects, json_encode to JSON is more suitable.

When cross‑origin communication is needed, the header method can embed data in HTTP requests.

The external JavaScript file method is useful when the value must be reused across multiple pages or applications.

JavaScriptWeb Developmentheaderdata-passingjson_encodeEcho
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.