AJAX with PHP

AJAX PHP

In the following example, we will create an interactive application to find the details of the user-specified continent by using PHP.

Example

The following is the server-side coding using PHP.

continent-json.php
<?php var obj = {population:"",area:"",countries:""}; switch($_POST['data']){ case "Africa": obj.population = "121.61 crores"; obj.area = "30.37 million km²"; obj.countries = "Nigeria, South Africa, Egypt"; break; case "Oceania": obj.population = "2.46 crores"; obj.area = "7.692 million km²"; obj.countries = "Fiji, Guam, Palau"; break; case "Asia": obj.population = "446.1 crores"; obj.area = "44.58 million km²"; obj.countries = "Japan, Singapore, china"; break; case "Europe": obj.population = "74.14 crores"; obj.area = "10.18 million km²"; obj.countries = "Russia, Germany, UK"; break; } echo obj; ?>

The following is the client-side coding for user interaction.

HTML Online Compiler
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <style> table, td, th{ border: 1px solid black; padding: 10px 5px; } table{ width: 100%; border-collapse: collapse; margin-top: 20px; } table tr th{ width: 150px; } </style> </head> <body> <h1>AJAX example using PHP</h1> <p>Select any continent for details</p> <select> <option>Africa</option> <option>Asia</option> <option>Europe</option> <option>Oceania</option> </select> <div id="point"></div> <script> $(document).ready(function(){ $("select").change(function(){ $.post("/continent-json.php",{ data: $("select").val() },function(data){ // Create table on fly var myTable = "<table><tbody><tr><th>Population</th><td>"+data.population+"</td></tr><tr><th>Area</th><td>"+data.area+"</td></tr><tr><th>top countries</th><td>"+data.countries+"</td></tr></tbody></table>"; $("#point").html(myTable); }); }); // Trigger change() method only when the page load/refreshed $("select").trigger("change"); }); </script> </body> </html>

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author