How to pass PHP variables and data to JavaScript
P粉004287665
P粉004287665 2023-08-21 12:31:08
0
2
351

I have a variable in PHP and I need to use its value in my JavaScript code. How can I pass my variables from PHP into JavaScript?

I have the following code:

getValue(); // Make API and database calls 

On the same page, I have JavaScript code that needs to pass the value of the $val variable as a parameter:

 


P粉004287665
P粉004287665

reply all (2)
P粉893457026

I usually use data-* attributes in HTML.

This example uses jQuery, but it can be adapted to other libraries or native JavaScript.

You can read more about the dataset attribute here:https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.dataset

    P粉517090748

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

    In no particular order:

    1. Use AJAX to get the required data from the server.
    2. Echo the data to a location on the page and use JavaScript to get the information from the DOM.
    3. Echo data directly into JavaScript.

    In this article, we will detail the pros and cons of each of the above methods, and how to implement them.

    1. Use AJAX to get the required data from the server

    This approach is considered the best becauseserver-side and client-side scripts are completely separated.

    advantage

    • Better separation between layers- If tomorrow you stopped using PHP and wanted to move to servlets, REST APIs, or other services, you wouldn't need to change much of your JavaScript code.
    • Easier to read- JavaScript is JavaScript, PHP is PHP. By not mixing the two, you get more readable code.
    • Allow asynchronous data transfer- Getting information from PHP can be time/resource consuming. Sometimes you just don't want to wait for information, load the page, and then get it when it arrives.
    • Data does not appear directly in the markup- This means your markup remains clean without any extra data, only visible to JavaScript.

    shortcoming

    • Delay- AJAX creates an HTTP request, and HTTP requests travel over the network and have network delays.
    • Status- Data obtained through a separate HTTP request will not contain any information obtained from the HTTP request to obtain the HTML document. You might need this information (for example, if the HTML document was generated in response to a form submission), and if you do, you'll have to transmit it somehow. If you have excluded embedding data into the page (which you have excluded if you use this technique), then you can only use cookies/sessions, which may be subject to race conditions.

    Implementation example

    To use AJAX, you need two pages, one where PHP generates the output, and another where JavaScript gets the output:

    get-data.php

    /* 在这里执行一些操作,比如与数据库、文件会话等进行交互 * 超越世界,无间地带,闪烁之城和加拿大。 * * AJAX通常使用字符串,但你也可以输出JSON、HTML和XML。 * 这完全取决于你发送的AJAX请求的Content-type头。 */ echo json_encode(42); // 最后,你需要`echo`结果。 // 所有数据都应该使用`json_encode`。 // 你可以在PHP中`json_encode`任何值,数组、字符串, // 甚至对象。

    index.php (or the name of the actual page)

      

    The combination of the above two files will pop up42when the file loading is completed.

    More reading materials

    2. Echo the data to a certain location on the page and use JavaScript to get the information from the DOM

    This method is less desirable than AJAX, but it still has its advantages. In a way, it's stillrelativelyseparated between PHP and JavaScript, since PHP is not used directly in JavaScript.

    advantage

    • Fast- DOM operations are generally fast and you can store and access large amounts of data relatively quickly.

    shortcoming

    • Potentially non-semantic markup- Typically, you use some sort ofto store the information because frominputNode.valueIt's easier to get the information in, but doing so means you have a meaningless element in your HTML. HTML has theelement for document data, and HTML 5 introduces thedata-*attribute for JavaScript-related data on specific elements.
    • Clutter the source code- PHP generated data is output directly into the HTML source code, which means you get a larger and less focused HTML source code.
    • Harder to get structured data- Structured data must be valid HTML, otherwise you have to escape and convert the string yourself.
    • Tightly couple PHP with data logic- Because PHP is used for presentation, there is no way to cleanly separate the two.

    Implementation example

    In this case, you need to create some kind of element that is invisible to the user but visible to JavaScript.

    index.php

       

    3. Echo data directly into JavaScript

    This is probably the easiest way to understand.

    advantage

    • Very easy to implement- The cost to achieve this is very low and easy to understand.
    • Does not pollute source code- Variables are output directly into JavaScript, so
      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!