How to fetch data from a PHP file to another PHP/HTML file using AJAX and jQuery?

If you want to pass data from one PHP file to another, you can use AJAX (Asynchronous JavaScript and XML). Also, jQuery is a very useful library for harnessing your JavaScript’s potential.

In this example we will pass one variable from ‘storage.php’ and show it to ‘index.php’.

index.php

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX using Jquery</title>
</head>

<body>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script>
        $.ajax(
            'storage.php', {
                success: function(data) {
                    alert('AJAX call success! \nThe data passed is: ' + data);
                },
                error: function() {
                    alert('An error occurred!');
                }
            }
        );
    </script>

</body>

</html>

storage.php

<?php
$variable = "Congrats!";

echo $variable;

Save the two files on your localhost directory. If you don’t know how to setup your localhost server, you can check my simple tutorial on Coding Basics: How to host your own website using localhost (LAN).

Enjoy!

Published by Christian Foster

Code-blooded, coffee-lover, tall, dark and chubby. I love to draw, has motion-sickness and a sleepy-head. BTW, graduate of BS Computer Science, Associate in Computer Science and certified UiPath RPA Developer. Loyal to my partner and a father of a cute bouncing baby daughter!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create your website with WordPress.com
Get started
%d bloggers like this: