5 Ways To Call PHP File From Javascript – Simple Examples

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:

  1. Use AJAX to call a PHP script.
  2. Use the Fetch API to call a PHP script.
  3. Redirect the current page to a PHP script.
  4. Submit a hidden HTML form – An old school method.
  5. 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!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

REAL QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes JS Call PHP Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

CALL PHP FROM JS

All right, let us now get into the ways and examples of calling PHP from Javascript.

 

1) AJAX CALL PHP SCRIPT

1-ajax.html
<!-- (A) HTML FORM -->
<form onsubmit="return ajaxcall();">
  <input type="text" id="name" required/>
  <input type="email" id="email" required/>
  <input type="submit" value="Save"/>
</form>

<!-- (B) JAVASCRIPT -->
<script>
function ajaxcall() {
  // (B1) GET FORM DATA
  var data = new FormData();
  data.append('name', document.getElementById("user-name").value);
  data.append('email', document.getElementById("user-email").value);
 
  // (B2) AJAX CALL
  var xhr = new XMLHttpRequest();
  xhr.open('POST', "0-dummy.php");
  xhr.onload = function () {
    console.log(this.response);
  };
  xhr.send(data);
  return false;
}
</script>

This should be pretty straightforward:

  • A – We have the usual HTML form, using Javascript onsubmit="return ajaxcall() to handle the submission.
  • B – Practically grabbing data from the HTML form and submitting 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.

 

 

2) USE FETCH API TO CALL PHP 

2-fetch.html
<!-- (A) HTML FORM -->
<form onsubmit="return fetchcall();">
  <input type="text" id="name" required/>
  <input type="email" id="email" required/>
  <input type="submit" value="Save"/>
</form>
 
<!-- (B) JAVASCRIPT -->
<script>
function fetchcall() {
  // (B1) GET FORM DATA
  var data = new URLSearchParams();
  data.append('name', document.getElementById("name").value);
  data.append('email', document.getElementById("email").value);
 
  // (B2) FETCH
  fetch("0-dummy.php", {
    method: 'post',
    body: data
  })
  .then(function (response) {
    return response.text();
  })
  .then(function (text) {
    console.log(text);
  })
  .catch(function (error) {
    console.log(error)
  });
  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 the older browsers.

 

 

3) JAVASCRIPT REDIRECTION WITH QUERY STRING

3-redirect.php
<!-- (A) HTML FORM -->
<form onsubmit="return redirect();">
  <input type="number" id="numA" required/>
  <input type="number" id="numB" required/>
  <input type="submit" value="Go!"/>
</form>
 
<!-- (B) JAVASCRIPT -->
<script>
function redirect () {
  // (B1) APPEND THE JS VARIABLES AS QUERY STRING
  var src = "3-redirect.php";
  src += "?numA=" + document.getElementById("numA").value;
  src += "&numB=" + document.getElementById("numB").value;
  src = encodeURI(src);
 
  // (B2) REDIRECTION
  window.location.href = src;
  return false;
}
</script>

<!-- (C) RESULTS -->
<?php 
if (isset($_GET['numA'])) { require "0-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.

 

4) JAVASCRIPT FORM SUBMISSION

4-form.php
<!-- (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 "0-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”.

 

 

5) SCRIPT TAG POINTING TO PHP SCRIPT

5-unorthodox.html
<!-- (A) HTML FORM -->
<form onsubmit="return bad();">
  <input type="number" id="numA" required/>
  <input type="number" id="numB" required/>
  <input type="submit" value="Add"/>
</form>
 
<!-- (B) JAVASCRIPT -->
<script>
function bad () {
  // (B1) CREATE NEW SCRIPT & APPEND DATA
  // NOT A GOOD WAY, AND NOT RECOMMENDED.
  var tag = document.createElement("script");
  var src = "0-dummy.php";
  src += "?numA=" + document.getElementById("numA").value;
  src += "&numB=" + document.getElementById("numB").value;
  src += "&BAD=1";
  tag.src = encodeURI(src);
 
  // (B2) INJECT SCRIPT TAG
  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 on the Internet. While this works, it is also shunned upon in the modern-day. Just stick with using AJAX or Fetch.

 

USEFUL BITS & LINKS

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

 

YOUTUBE TUTORIAL

 

INFOGRAPHIC CHEAT SHEET

How To Call PHP Script From Javascript (click to enlarge)

 

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!

4 thoughts on “5 Ways To Call PHP File From Javascript – Simple Examples”

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

    1. 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:

      • * Looking into server-side solutions.
      • * OR enabling CORS on the servers.
  2. 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?

Leave a Comment

Your email address will not be published. Required fields are marked *