How to execute a PHP script without reloading the page

We are going to see two ways of doing that: an easy one and an intermediate one.

Photo by Ben on Unsplash

Hello everyone!

Since I started using PHP, I had a big problem: When I wanted to execute a code, a new PHP generated website opened.
In some cases, I didn’t want that, and I started looking for ways of eviting it. Today I’m going to explain to you the ones that I use the most.

The easy way

If you want to execute a PHP code and you don’t need a response from it (for example, if you want to send an email), you can use HTML iframes.
This is the easiest option, but if some errors happen on the PHP script, you won’t be able to know it.
Let’s go to the code!

In the HTML document, add an iframe. For now, do not define any source and make it invisible using the following styling. Add also an ID to identify the element with Javascript:

<iframe id="frame" style="height:0px; width:0px; border:none;"></iframe>

If you use the display: none; property, our project is not going to work because the PHP code is not going to execute.

Now we are ready. When you want to execute a PHP script, use Javascript to change the iframe source as it follows:

document.getElemenyById(“frame”).src = “YOUR PHP FILE SOURCE”

And that’s all! What an easy method!

As you have seen, this way is pretty easy, but the PHP script can’t return any information to our Javascript file.
Let’s take a look at another way that will allow us to do that.

Intermediate way

We will use ajax to execute a PHP code and get a response from it without reloading the page (like in a live search).
Let’s go to the code!

function call_php() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// MANAGE THE RESPONSE
var response = this.responseText;
}
}
xmlhttp.open(“GET”, “example.php”, true);
xmlhttp.send();
}
}

Here, we call the example.php file and we save its response on a variable that we called response.

This way is a little bit more complex than the iframe method, but it can return information to our code.

For more information about ajax and PHP, see the following tutorial: https://www.w3schools.com/pHP/php_ajax_php.asp

Conclusion

Thank you very much for reading this article!
I hope that you learned how to execute a PHP code without reloading the page.

Thank you very much,
Markus

PD: Which way do you like the most?

I'm a young programmer who likes creating new things.