Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

php

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?

like image 767
Madara's Ghost Avatar asked Aug 02 '14 10:08

Madara's Ghost


People also ask

Can we combine JavaScript and PHP together?

Besides, PHP and JavaScript similarities, these two languages are a powerful combination when used together. Large numbers of websites combine PHP and JavaScript – JavaScript for front-end and PHP for back-end as they offer much community support, various libraries, as well as a vast codebase of frameworks.

Where does the JavaScript run?

The JavaScript Console. JavaScript is most often run on webpages inside the browser, but it can also be run server-side.

What is JavaScript and PHP?

JavaScript is used to create real-time games and applications, mobile applications etc. A PHP program is used to create dynamic pages, send cookies, receive cookies, collect form data, etc. 9. JavaScript is case sensitive in case of functions. PHP is not case sensitive in case of functions.


2 Answers

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?
like image 181
Madara's Ghost Avatar answered Oct 08 '22 05:10

Madara's Ghost


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).

like image 44
Zirak Avatar answered Oct 08 '22 04:10

Zirak