Welcome to a tutorial on how to call a PHP file from Javascript. So you need to call a PHP script to do some processing from Javascript?
The common ways to call a PHP script with Javascript are:
- Use AJAX to call a PHP script.
- Use the Fetch API to call a PHP script.
- Redirect the current page to a PHP script.
- Submit a hidden HTML form, an old-school method.
- Finally, an unorthodox method – Dynamically create a script tag that points to a PHP script.
But just how are these done? Let us walk through some examples in this guide – Read on!
TABLE OF CONTENTS
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
EXAMPLE CODE DOWNLOAD
Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
CALL PHP FROM JS
All right, let us now get into the ways and examples of calling PHP from Javascript.
TUTORIAL VIDEO
METHOD 1) AJAX CALL PHP SCRIPT
<!-- (A) HTML FORM -->
<form id="myForm" onsubmit="return ajaxcall();">
<input type="text" name="name" value="Jon" required>
<input type="email" name="email" value="jon@doe.com" required>
<input type="submit" value="Save">
</form>
<!-- (B) JAVASCRIPT -->
<script>
function ajaxcall () {
// (B1) GET FORM DATA
var data = new FormData(document.getElementById("myForm"));
// (B2) AJAX CALL
var xhr = new XMLHttpRequest();
xhr.open("POST", "x-dummy.php");
xhr.onload = function () {
console.log(this.response);
};
xhr.send(data);
return false;
}
</script>
This should be pretty straightforward:
- We have the usual HTML form, using Javascript
onsubmit="return ajaxcall()"
to handle the submission. - Practically grabbing data from the HTML form and submitting it to the server via an AJAX request.
P.S. Use http://
not file://
. Also, cross-domain AJAX calls will not work out of the box – It requires manual settings on the servers to allow cross-origins.
METHOD 2) USE FETCH API TO CALL PHP
<!-- (A) HTML FORM -->
<form id="myForm" onsubmit="return fetchcall();">
<input type="text" name="name" value="Jon" required>
<input type="email" name="email" value="jon@doe.com" required>
<input type="submit" value="Save">
</form>
<!-- (B) JAVASCRIPT -->
<script>
function fetchcall () {
// (B1) GET FORM DATA
var data = new FormData(document.getElementById("myForm"));
// (B2) FETCH
fetch("x-dummy.php", { method: "POST", body: data })
.then(res => res.text())
.then(txt => console.log(txt))
.catch(err => console.error(err));
return false;
}
</script>
If you are wondering if this is similar to AJAX – Yes, it is, fetch()
is the so-called “better modern version” of new XMLHttpRequest()
. Supposed to offer more advanced options and more flexibility. But please take note, fetch()
is not supported in ancient browsers.
METHOD 3) JAVASCRIPT REDIRECTION WITH QUERY STRING
<!-- (A) HTML FORM -->
<form onsubmit="return redirect();">
<input type="number" id="numA" value="123" required>
<input type="number" id="numB" value="456" required>
<input type="submit" value="Go!">
</form>
<!-- (B) JAVASCRIPT -->
<script>
function redirect () {
// (B1) URL SEARCH PARAMS (QUERY STRING)
var params = new URLSearchParams();
params.set("numA", document.getElementById("numA").value);
params.set("numB", document.getElementById("numB").value);
// (B2) REDIRECTION
window.location.href = "3-redirect.php?" + params.toString();
return false;
}
</script>
<!-- (C) RESULTS -->
<?php
if (isset($_GET["numA"])) { require "x-dummy.php"; }
?>
Before the angry trolls rage – I know this is not “directly calling PHP with Javascript”, but this is an old-school method that we use before AJAX and Fetch are even available. Not quite recommended in this modern age, but it still works well.
METHOD 4) JAVASCRIPT FORM SUBMISSION
<!-- (A) HIDDEN HTML FORM -->
<form id="ninja" method="post" style="display:none;">
<input type="hidden" id="numA" name="numA" required>
<input type="hidden" id="numB" name="numB" required>
</form>
<!-- (B) JAVASCRIPT -->
<input type="button" value="Go!" onclick="go()">
<script>
function go () {
document.getElementById("numA").value = "123";
document.getElementById("numB").value = "456";
document.getElementById("ninja").submit();
}
</script>
<!-- (C) RESULTS-->
<?php
if (isset($_POST["numA"])) { require "x-dummy.php"; }
?>
I know, this is not “directly call PHP with Javascript” again, but this is yet another old-school method. Should be pretty self-explanatory – We simply submit a hidden HTML form using Javascript. This is still pretty handy, just keep it as “a trick up the sleeve”.
METHOD 5) SCRIPT TAG POINTING TO PHP SCRIPT
<!-- (A) HTML FORM -->
<form onsubmit="return bad();">
<input type="number" id="numA" value="123" required>
<input type="number" id="numB" value="456" required>
<input type="submit" value="Add">
</form>
<!-- (B) JAVASCRIPT -->
<script>
function bad () {
// (B1) URL SEARCH PARAMS (QUERY STRING)
var params = new URLSearchParams();
params.set("numA", document.getElementById("numA").value);
params.set("numB", document.getElementById("numB").value);
params.set("BAD", 1);
// (B2) CREATE NEW SCRIPT & INJECT INTO HEAD
// NOT A GOOD WAY, AND NOT RECOMMENDED.
var tag = document.createElement("script");
tag.src = encodeURI("x-dummy.php?" + params.toString());
document.head.appendChild(tag);
return false;
}
</script>
Negative example warning – This funky way of creating a <script src="SCRIPT.PHP">
came from a dark corner of the Internet. While this works, it is also shunned in the modern-day. Just stick with using AJAX or Fetch.
EXTRAS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
LINKS & REFERENCES
- Javascript AJAX – A Beginner’s Tutorial – Code Boxx
- Pass PHP variables & arrays to Javascript – Code Boxx
THE END
Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
Here’s another nasty way to run some PHP if you dont need to pass data.
Your snippet is removed by the spam/security filter, but no need for “nasty” ways. Just omit the data.
xhr.send() fetch("URL").then...
Very much appreciate your examples,
I tried the 1a-ajax.html but I get CORS cross origin error
I have to got to about:config & disable the security.fileuri.strict_origin_policy
It is getting harder to do simple things these days.
I wrote a small php script to get data from a wifi device because I was getting cors error in jquery ajax. (If only I could whitelist files or url)
Thanks
Cross-origin policies exist for security reasons, and changing the config in the browser will only work on your own PC. You should either be:
I really liked the 4 methods you presented. Prior to my reading your post, I created a successful standard form submission (html form sent to php script). I now want to use the form space to present a message to someone that submits a form from my site. I’ve set up the proper CSS and a couple of js statements to hide the form and reveal the message behind. This requires I submit a form via AJAX call so I don’t require a screen refresh. To that end, I attempted to use your AJAX method, but I’m having difficulty making it work. Could I send you my html, php, & js files for you to review and tell me what I’m doing wrong?
https://code-boxx.com/faq/#help