How can I pass variables and data from PHP to JavaScript?

Ask a question+

I have a variable in PHP, and I need to send its value to JavaScript. How can I do that?

My code looks like this:

// Makes an API and database call
= $myService->getValue();

I have JavaScript code that needs val and looks along the lines of:

// I tried this, but it didn’t work

 // This didn’t work either
<?php myPlugin.start($val); ?>

// This works sometimes, but sometimes it fails
BabkenM 1K
add comment

2 Answers


Well that is a very long detailed answer.

Here is the short and quick for your case.

.start(<?php echo $val; ?>

Just need to echo out the value. This will solve your problem.

Lainrawr 295
add comment

There are several approaches to do this. Some require more overhead than others, and some are considered better than others.

In no particular order:

  1. Use AJAX to get the data you need from the server.
  2. Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.
  3. Echo the data directly to JavaScript.

In this post, we’ll examine each of the above methods, and see the pros and cons of each, as well as how to implement them.

1. Use AJAX to get the data you need from the server

This method is considered the best because your server-side and client-side scripts are completely separate.


  • Better separation between layers - If tomorrow you stop using PHP, and want to move to a servlet, a REST API, or some other service, you don’t have to change much of the JavaScript code.
  • More readable - JavaScript is JavaScript, PHP is PHP. Without mixing the two, you get a more readable code on both languages.
  • Allows for asynchronous data transfer - Getting the information from PHP might be time/resources expensive. Sometimes you just don’t want to wait for the information, load the page, and have the information reach whenever.


  • Latency - AJAX creates an HTTP request, and HTTP requests are carried over the network and have network latencies.
  • State - Data fetched via a separate HTTP request won’t include any information from the HTTP request that fetched the HTML document. You may need this information (e.g., if the HTML document is generated in response to a form submission) and, if you do, will have to transfer it across somehow. If you have ruled out embedding the data on the page (which you have if you are using this technique), then that limits you to cookies/sessions, which may be subject to race conditions.

Implementation Example

With AJAX, you need two pages, one is where PHP generates the output, and the second is where JavaScript gets that output:


    /* Do some operation here, like talk to the database, the file-session
     * The world beyond, limbo, the city of shimmers, and Canada.
     * AJAX generally uses strings, but you can output JSON, HTML, and XML as well.
     * It all depends on the Content-type header that you send with your AJAX
     * request. */

    echo json_encode(42); // In the end, you need to <strong>echo</strong> the result.
      // All data should be <em>json_encode()</em>d.

      // You can json_encode() any value in PHP, arrays, strings,
      //even objects.

index.php (or whatever the actual page is named like)

<!-- snip -->
    function reqListener () {

    var oReq = new XMLHttpRequest(); // New request object
    oReq.onload = function() {
        // This is where you handle what to do with the response.
        // The actual data is found on this.responseText
        alert(this.responseText); // Will alert: 42
    oReq.open("get", "get-data.php", true);
    //                               ^ Don't block the rest of the execution.
    //                                 Don't wait until the request finishes to
    //                                 continue.
<!-- snip -->

The above combination of the two files will alert 42 when the file finishes loading.

2. Echo the data into the page somewhere, and use JavaScript to get the information from the DOM

This method is less preferable to AJAX, but it still has its advantages. It’s still relatively separated between PHP and JavaScript in the sense that there is no PHP directly in JavaScript.


  • Fast - DOM operations are often quick, and you can store and access a lot of data relatively quickly.


  • Potentially Unsemantic Markup - Usually, what happens is that you use some sort of <input type=hidden> to store the information because it’s easier to get the information out of inputNode.value, but doing so means that you have a meaningless element in your HTML. HTML has the <meta> element for data about the document, and HTML 5 introduces data-* attributes for data specifically for reading with JavaScript that can be associated with particular elements.

Implementation Example

With this, the idea is to create some sort of element which will not be displayed to the user but is visible to JavaScript.


<!-- snip -->
<div id="dom-target" style="display: none;">
        $output = "42"; // Again, do some operation, get the output.
        echo htmlspecialchars($output); /* You have to escape because the result
                                           will not be valid HTML otherwise. */
    var div = document.getElementById("dom-target");
    var myData = div.textContent;
<!-- snip -->
Ashutosh200 80
add comment

Your Answer