When and where does JavaScript run, how about PHP? Can I combine the two?

When does a client-side language like JavaScript run and when does a server-side language like PHP run? How can I mix both?

I want to run a PHP function when a button on my site is clicked, or run a JavaScript function from PHP; is that possible?


Solution 1:

The short answer is No. You cannot run PHP functions from JavaScript[With the exception of AJAX], nor can you run JavaScript functions from PHP. The two run times are separate.

How?

To understand how JavaScript and PHP cooperate, you should first understand the basics of the HTTP protocol that powers the web.

HTTP Sequence

The diagram above demonstrates the basics of the HTTP protocol. The user (you) asks the client (your browser) to fetch you a page. The browser will then ask the server (Google, in this example) for the page. The server will reply with an HTML page, the client parses that page, and asks for the images, fonts and any other resources needed to load the page correctly. The client then presents the completed page to the user.

So where does JavaScript come in?

JavaScript is run in the Client (i.e. the browser). So JavaScript runs after the response from the server has arrived. Let's add that to our diagram.

Sequence with JavaScript

JavaScript scripts start running as soon as they are loaded, and will continue to run if they have event listeners waiting for events from the user (like clicking, typing, or moving around).

Where does PHP fit in?

PHP runs on the Server, the web server (Which is a program responsible for serving web content) will run PHP according to its configuration. PHP will process the input from the web server, and return output. That output is served back to the client.

Updated diagram:

Sequence with JavaScript and PHP

As you can see, the PHP execution does not persist. It is executed, and then ends once the response is sent.


As you can see, there is no overlap between the PHP execution and the JavaScript execution, so it isn't actually possible to make a function on one of them to work based on input from the other.

But.. but.. I've heard of AJAX!

AJAX is merely causing another HTTP request from JavaScript. You can call it a way to use PHP functions from JavaScript, but it's actually not quite that.

AJAX Sequence

As you can see, with AJAX, JavaScript will send a request to the server, which will invoke PHP, PHP will run again, like in a normal request (PHP doesn't necessarily knows that this is even an AJAX request!) and the server returns the response back to JavaScript, which uses it to do stuff.

In this case, there is an overlap between the time PHP runs and the time JavaScript runs, since JavaScript invoked a request.

Also see:

  • How to pass variables and data from PHP to JavaScript?

Solution 2:

Welcome to McBurger, a fancy (yeah right) burger joint. The smell of dried-up grease invades your nostrils, causing your bowels to gurgle with a mixture of disgust and delight. You patiently wait in line behind a mother of what should be human children. Finally, you meet the teenage cashier face to face, not without some pity. You order a burger (surprise) and some fries. You pay up and wait a bit for your order.

After some time, you get your burger, only to discover that they forgot your fries! You walk up to the cash register again, and ask for them. You again wait out for the fries to be ready. Once they are, you guzzle everything up and leave.

What does this have to do with anything?

The angsty cashier is the server, perhaps running php.

You are the client, maybe a web browser capable of understanding html/css/js.

To get service, you approach the counter and say "I want a burger". McBurger then prepares and gives you a burger.

To get service, a web browser approaches the server and says "I want this page". Your server then prepares and gives you a page.

The most important aspect of this is that there is no mingling of customer and McBurger. You won't prepare your own fries, and McBurger won't drink your milkshake. The same way, the web browser will not run php, and the server will not run javascript for you. If you want McBurger to give you their famous caramel ice-cream, you must approach the counter and ask for one. If you want your web-page to save something to the DB when you click a button, you must approach the server and ask it to do so.

You and McBurger communicate over sound. Browsers and servers communicate over HTTP.

Let's take a look at HTTP.

Rabbit, where have you taken me?

If you're running on pretty much any linux distro or a Mac, you have netcat installed. If you're on Windows, sorry, you'll have to take my word for the next section, or download a nc port or a telnet client of some sort.

Anyway, open up your favourite terminal, and let's talk to some server on port 80 (the default http port):

% nc www.stackoverflow.com 80

"Welp, that didn't do much of anything, there's just an empty prompt in front of me!"

Don't worry, random person whom I talk to during these answers, we just haven't said anything to the server! In McBurger, this'd be the equivalent of walking up to the counter and staring intently at the cashier.

Just.

Staring.

We have to start using our vocal chords fast, or they'll call security. I can't go back to that hellhole Martha, I just...can't.

...Anywho, we need to tell the cashier that we want a burger. In http, that's issuing a GET request:

% nc www.stackoverflow.com 80
GET / HTTP/1.1

Hit enter twice, and hurray, we got some output!

HTTP/1.1 400 Bad Request
Content-Type: text/html; charset=us-ascii
Date: Sat, 02 Aug 2014 10:55:16 GMT
Content-Length: 334

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request - Invalid Hostname</h2>
<hr><p>HTTP Error 400. The request hostname is invalid.</p>
</BODY></HTML>

That can't be good. Lots of stuff I don't understand, but it says that the request hostname is invalid. Let's try that again, only we give it a host this time:

% nc www.stackoverflow.com 80
GET / HTTP/1.1
Host: stackoverflow.com

Hit enter twice, and "holy bajesus, that's a lot of output!" Yes person, that is.

Rabbit, how is this relevant?

So how is this connected to php and some flowcharts? Still think that you can run php on click? Let's write a "hello world" in php and see why it's not possible.

Just for the occasion, I installed php and wrote some files:

# example.php
<?php
echo 'Hi mom!';
?>

Cool, let's do a request and see what's happening:

% nc localhost 80
GET /example.php HTTP/1.1
Host: localhost

The ritual two enter keys and:

HTTP/1.1 200 OK
Server: nginx/1.2.1
Date: Sat, 02 Aug 2014 11:00:52 GMT
Content-Type: text/html

Hi mom!

Congratulations, we have our own burger joint! We have a server, which we can respond to clients! Joy to the world!

What happened here is this conversation:

  • Me: Give me /example.php.
  • Server: okay. Hey php, run example.php
  • php: Whatever. Output is Hi mom!
  • Server: There you go client, Hi mom!
  • Me: Thank you!

In conclusion

  • Server and client are two separate beings.
  • They communicate over something called HTTP.
  • If the client wants something, it has to ask the server for it.
    • Which it does by doing HTTP requests.

Shameless self-promotion: If you want to know how to create http requests from javascript, you can refer to my gist on the matter (warning: contains traces of swear words).

Solution 3:

The other answer is great, but I'll just try a simpler approach ..

Your browser receives a page of HTML and JavaScript from the server. PHP is working on the server to assemble that final page that gets sent to the browser. It can check some databases, and do some calculations, and maybe connect with an API, but at the end of it all it takes all the info and "prints it up" on a page full of code which it then sends to your browser.

The browser gets the page and if there is any Javascript on the page, or if there are SCRIPT tags that pull in other .js files, it reads all that and then executes the Javascript.

So your page is "built" by PHP, and it can include Javascript into that somehow which will be executed by the browser, but these two processes are generally separate.

You can get PHP to "talk" to Javascript by outputting specific JS code onto the page.

You can get Javascript to "talk" to PHP by using AJAX to contact the server while a page is executing. The server can give answer info back which is then integrated back into the page using Javascript again.

But generally, the two processes are running in their own worlds.

You can do you "button starts PHP code" best with AJAX.

Running Javascript from "inside" PHP is not really done.