Curbside Coder

"Tech blog for code newbies, wizards and ninjas!"

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!

Leave a comment

Navigation

About

Hello world! I’m Christian Foster, your Curbside Coder! Welcome to my corner of the internet. Let’s make a dent in the universe!

Design a site like this with WordPress.com
Get started