⇧
vadnica-logo
My Services About the Project Telegram O meni O meni

AJAX with PHP

AJAX is used to create more interactive applications. This example demonstrates how a web page can communicate with a web server while a user enters characters into an input field. When the user types a character into the input field, a function called searchEngine() is triggered by the onkeyup event. The code first checks if the input field is empty (str.length === 0), and if so, it clears the content of the placeholder element s and exits the function. However, if the input field is not empty, the XMLHttpRequest object is executed, followed by the created function once the server response is ready. The request is sent to a PHP file named alphabet.php on the server. We can also observe that the parameter q is appended as "alphabet.php?q=" + str, where the variable str contains the content of the input field. The PHP file checks an array of names and returns the matching names to the browser.

EXAMPLE
RESULT

The PHP script alphabet.php receives the parameter q from the GET request, converts it to lowercase, and searches a predefined list of names. It returns all names that start with the input, separated by commas. If no names match, it outputs the message “No results found”. This script enables dynamic filtering of names, which is called by the AJAX example in the JavaScript file.

<?php
$a[] = "Alenka";
$a[] = "Borut";
$a[] = "Cene";
$a[] = "Črtomir";
$a[] = "Damjana";
$a[] = "Emil";
$a[] = "France";
$a[] = "Gregor";
$a[] = "Helena";
$a[] = "Irena";
$a[] = "Jana";
$a[] = "Klemen";
$a[] = "Lidija";
$a[] = "Marinka";
$a[] = "Nataša";
$a[] = "Ojdip";
$a[] = "Peter";
$a[] = "Roman";
$a[] = "Sabina";
$a[] = "Špela";
$a[] = "Tanja";
$a[] = "Uroš";
$a[] = "Veronika";
$a[] = "Zdenka";
$a[] = "Žiga";

// Get the q parameter from the URL
$q = $_REQUEST["q"];

$suggestion = "";

// Find all suggestions from array if q is not empty
if ($q !== "") {
    $q = strtolower($q);
    $len = strlen($q);
    foreach ($a as $name) {
        if (stristr($q, substr($name, 0, $len))) {
            if ($suggestion === "") {
                $suggestion = $name;
            }   else {
                $suggestion .= ", $name";
            }
        }
    }
}

// If no suggestion was found
echo $suggestion == "" ? "No results found" : $suggestion;