I have this code:

<script type="text/javascript">
    var foo = 'bar';
    <?php
        file_put_contents('foo.txt', ' + foo + ');
    ?>

    var baz = <?php echo 42; ?>;
    alert(baz);
</script>

Why does this not write "bar" into my text file, but alerts "42"?


NB: Earlier revisions of this question were explicitly about PHP on the server and JavaScript on the client. The essential nature of the problem and solutions is the same for any pair of languages when one is running on the client and the other on the server. Please take this in to account when you see answers talking about specific languages.

upvote
  flag
@deceze: Well, you can always post your answer below, provided there's a decent question to post it too. But either way, I always enjoy a bit of ASCII-art! :-) – T.J. Crowder
1 upvote
  flag
@deceze I'm not so sure about random's revision. Just pinging you to roll it back if you wish. – Mike
upvote
  flag
@Mike Thanks. I indeed have no idea why he felt the need to edit. – deceze
1 upvote
  flag
You should not be including meta commentary about the question in the question itself. The question should just be asking a question, not explaining why you're asking a question. – Servy
upvote
  flag
The file_put_contents ought to be edited to have some possibility of actually referencing the foo variable. As-is, it's just writing a static string to the file and is really not demonstrating the server-side vs. client-side execution issue. – Andrew Medico
upvote
  flag
@Andrew That's the point, there is no possibility. It's a sample code to introduce the problem. If you have a better suggestion, please feel free to edit it. – deceze
1 upvote
  flag
This question actually has no specificity to JavaScript or PHP and is instead a broad definition of the differences between client-side and server-side programming. A title edit has been suggested of "What is the difference between client-side and server-side programming?" and the client-side and server-side tags added. – Jhoverit
1 upvote
  flag
@Jhawins While this may now be more accurate, it hardly allows novice users (who have this problem the most) to find this question easily. The previous title reflected much more what someone whom I wrote this for might search for. – deceze
upvote
  flag
@deceze then I would find some way to incorporate both. It's simply not good enough to pretend this is a JS/PHP problem. New users need to know that this applies to so much more. Otherwise a new question will need to be created to serve essentially the exact same purpose as yours and we will have a duplicate. If yours is to serve a specialized purpose, that would imply that we need one for each purpose and likely another for the concept as a whole. This would just be a lot of the same info over and over again but maybe it's the way. – Jhoverit
2 upvote
  flag
A few months down the line, users are now finding questions with a title like this one originally had, duly marked as duplicates of this one. Problem solved. – tripleee

4 Answers 11

up vote 334 down vote accepted

Your code is split into two entirely separate parts, the server side and the client side.

                    |
               ---------->
              HTTP request
                    |
+--------------+    |    +--------------+
|              |    |    |              |
|    browser   |    |    |  web  server |
| (JavaScript) |    |    |  (PHP etc.)  |
|              |    |    |              |
+--------------+    |    +--------------+
                    |
  client side       |      server side
                    |
               <----------
          HTML, CSS, JavaScript
                    |

The two sides communicate via HTTP requests and responses. PHP is executed on the server and outputs some HTML and maybe JavaScript code which is sent as response to the client where the HTML is interpreted and the JavaScript is executed. Once PHP has finished outputting the response, the script ends and nothing will happen on the server until a new HTTP request comes in.

The example code executes like this:

<script type="text/javascript">
    var foo = 'bar';
    <?php
        file_put_contents('foo.txt', ' + foo + ');
    ?>

    var baz = <?php echo 42; ?>;
    alert(baz);
</script>

Step 1, PHP executes all code between <?php ?> tags. The result is this:

<script type="text/javascript">
    var foo = 'bar';

    var baz = 42;
    alert(baz);
</script>

The file_put_contents call did not result in anything, it just wrote " + foo + " into a file. The <?php echo 42; ?> call resulted in the output "42", which is now in the spot where that code used to be.

This resulting HTML/JavaScript code is now sent to the client, where it gets evaluated. The alert call works, while the foo variable is not used anywhere.

All PHP code is executed on the server before the client even starts executing any of the JavaScript. There's no PHP code left in the response that JavaScript could interact with.

To call some PHP code, the client will have to send a new HTTP request to the server. This can happen using one of three possible methods:

  1. A link, which causes the browser to load a new page.
  2. A form submission, which submits data to the server and loads a new page.
  3. An AJAX request, which is a Javascript technique to make a regular HTTP request to the server (like 1. and 2. will), but without leaving the current page.

Here's a question outlining these method in greater detail

You can also use JavaScript to make the browser open a new page using window.location or submit a form, emulating possibilities 1. and 2.

upvote
  flag
This answer begins with "Your code is split into two entirely separate parts, the server side and the client side." and should explain why I've changed the title by itself. – Jhoverit
1 upvote
  flag
You can also open second page using window.open or load a page using an iframe. – jcubic
upvote
  flag
It might be worth adding WebSockets to the list of communication methods. – Quentin

Your Javascript will execute on the client, not on the server. This means that foo is not evaluated on the server side and therefore its value can't be written to a file on the server.

The best way to think about this process is as if you're generating a text file dynamically. The text you're generating only becomes executable code once the browser interprets it. Only what you place between <?php tags is evaluated on the server.

By the way, making a habit of embedding random pieces of PHP logic in HTML or Javascript can lead to seriously convoluted code. I speak from painful experience.

2 upvote
  flag
Your answer here is noteworthy as it makes mention to the/a interpeter. However, javascript can be compiled and run in a server environment, and it can be interpeted by a server as well. – Brett Caswell

To determine why PHP code doesn't work in JavaScript code we need to understand what is client side and server side language and how they work.

Server-side languages (PHP etc.): They retrieve records from databases, maintain state over the stateless HTTP connection, and do a lot of things that require security. They reside on the server, these programs never have their source code exposed to the user

Image from wikipedia_http://en.wikipedia.org/wiki/File:Scheme_dynamic_page_en.svg image attr

So you can easily see that server side language handle HTTP request and process it and as @deceze said PHP is executed on the server and outputs some HTML and maybe JavaScript code which is sent as response to the client where the HTML is interpreted and the JavaScript is executed.

While at the other hand Client Side Language (like JavaScript) resides on browser and runs at the browser, Client-side scripting generally refers to the class of computer programs on the web that are executed client-side, by the user's web browser, instead of server-side.

JavaScript is visible to the user and can be easily modified so for security stuff we must not rely on JavaScript.

So when you make a HTTP request on server than The server first reads the PHP file carefully to see if there are any tasks that need to be executed and send response to client side and again as @deceze said *Once PHP has finished outputting the response, the script ends and nothing will happen on the server until a new HTTP request comes in.*

Graphical representation

Image source

So now what can I do if I need to call PHP? It depends how you need to do it: either by reloading the page or by using an AJAX call.

  1. You can do by reloading page and send HTTP request
  2. you can make AJAX call with JavaScript and this does not require reloading page

Good Read:

  1. Wikipedia : Server-side scripting
  2. Wikipedia : Client-side scripting
  3. Madara Uchiha : Difference between client side and server side programming

In web application every task execute in a manner of request and response.

Client side programming is with html code with Java script and its frameworks, libraries executes in the internet explorer, Mozilla, chrome browsers. In the java scenario server side programming servlets executes in the Tomcat, web-logic , j boss, WebSphere severs

Not the answer you're looking for? Browse other questions tagged or ask your own question.