Can php and javascript share variables?

I'm going to try a simpler answer:

Explanation of the problem

First, let's understand the flow of events when a page is served from our server:

  • First PHP is run, it generates the HTML that is served to the client.
  • Then, the HTML is delivered to the client, after PHP is done with it, I'd like to emphasize that once the code leaves the server - PHP is done with it and can no longer access it.
  • Then, the HTML with JavaScript reaches the client, which can execute JavaScript on that HTML.

So really, the core thing to remember here is that HTTP is stateless. Once a request left the server, the server can not touch it. So, that leaves our options to:

  1. Send more requests from the client after the initial request is done.
  2. Encode what the server had to say in the initial request.

Solutions

That's the core question you should be asking yourself is:

Am I writing a website or an application?

Websites are mainly page based, and the page load times needs to be as fast as possible [for example - Wikipedia]. Web applications are more AJAX heavy and perform a lot of round trips to get the client fast information [for example - a stock dashboard].

Website

Sending more requests from the client after the initial request is done is slow as it requires more HTTP requests which have significant overhead. Moreover, it requires asynchronousity as making an AJAX request requires a handler for when it's complete.

I would not recommend making another request unless your site is an application for getting that information from the server.

You want fast response times which have a huge impact on conversion and load times. Making Ajax requests is slow for the initial uptime in this case and unneeded.

You have two ways to tackle the issue

  • Set a cookie - cookies are headers sent in HTTP requests that both the server and client can read.
  • Encode the variable as JSON - JSON looks very close to JavaScript objects and most JSON objects are valid JavaScript variables.

Setting a cookie is really not very difficult, you just assign it a value:

setcookie["MyCookie", $value]; // Sets the cookie to the value, remember, do not
                               // Set it with HTTP only to true.

Then, you can read it with JavaScript using document.cookie:

Here is a short hand rolled parser, but the answer I linked to right above this has better tested ones:

var cookies = document.cookie.split[";"].
    map[function[el]{ return el.split["="]; }].
    reduce[function[prev,cur]{ prev[cur[0]] = cur[1]; return prev },{}];
alert[cookies["MyCookie"]]; // Value set with PHP.

Cookies are good for a little data. This is what tracking services often do.

Once we have more data, we can encode it with JSON inside a JavaScript variable instead:


    var myServerData = ; // Don't forget to sanitize
                                                 //server data

Assuming $value is json_encodeable on the PHP side [it usually is]. This technique is what Stack Overflow does with its chat for example [only using .NET instead of PHP].

Application

If you're writing an application - suddenly the initial load time isn't always as important as the ongoing performance of the application, and it starts to pay off to load data and code separately.

My answer here explains how to load data using AJAX in JavaScript:

function callback[data]{
    // What do I do with the response?
}

var httpRequest = new XMLHttpRequest;
httpRequest.onreadystatechange = function[]{
    if [httpRequest.readyState === 4] { // Request is done
        if [httpRequest.status === 200] { // successfully
            callback[httpRequest.responseText]; // We're calling our method
        }
    }
};
httpRequest.open['GET', "/echo/json"];
httpRequest.send[];

Or with jQuery:

$.get["/your/url"].done[function[data]{
    // What do I do with the data?
}];

Now, the server just needs to contain a /your/url route/file that contains code that grabs the data and does something with it, in your case:

Chủ Đề