Call a PHP function using JavaScript.

This is a common question amongst beginner developers. And I still remember how this question crossed my mind back when I first started out writing PHP scripts.

Simply put: You cannot “call” a PHP function using JavaScript. This is because JavaScript is executed on the client side and PHP is executed on the server side.

However, there is a way to do what you’re trying to do.

So let me explain, because if you are searching for this question, it means that you don’t fully understand what is going on.

Why can’t I call a PHP function using JavaScript?

When the user navigates to your PHP script, this is what happens:

  1. Your web server receives the request from the browser and it loads the relevant PHP file.
  2. Your PHP code is parsed and executed.
  3. The web server gathers the response / output and sends it back to the browser.
  4. The browser displays this output.
  5. Finally: If the output contains any JavaScript, then the browser will execute it.

Basically, by the time your browser has started to execute your JavaScript code, PHP has already done it’s job. It is finished. The “connection” between the user and the PHP code on your server no longer exists. Your PHP code exists on a remote server that the browser has finished speaking to. The PHP function you intended on calling is no longer accessible.

It’s over, mate. Move on.

OK. So what can I do?

To access a PHP script without reloading the page, you will need to use Ajax. Using Ajax, you can open a new connection to the PHP on your web server without forcing the user to navigate away from the page. And the best thing is: It all happens in the background, so the user is blissfully unaware and left undisturbed.

By using Ajax, you can access PHP scripts and return a response to the browser in the background. You can then use this response to dynamically change content that is on the page.

If you think that Ajax will solve your problem, then you should read some of the tutorials that I have written on the subject:

Hopefully, this article saved you time by clearing up any confusion and sending you down the right path.