S. Doe
S. Doe

Reputation: 67

Php AJAX search with external JSON file

So Im trying to create an input field that displays results without the need of a refresh from an external JSON file. My current code works fine, however how would I achieve checking for results in an external JSON file instead of directly in the php file?

My JSON file: (I'd like to display results from "name").

[
 {"name" : "300", "year" : "1999", "plot" : "X", "run" : "200 min", "rated" : "PG-13", "score" : "10/10", "source" : "A", "id" : "000"}, 
 {"name" : "200", "year" : "1999", "plot" : "X", "run" : "200 min", "rated" : "PG-13", "score" : "10/10", "source" : "A", "id" : "000"}
]

My html and Javascript:

<script>
function showHint(str) {
if (str.length == 0) { 
    document.getElementById("txtHint").innerHTML = "";
    return;
} else {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
        }
    };
    xmlhttp.open("GET", "gethint.php?q=" + str, true);
    xmlhttp.send();
}
}
</script>
<p><b>Start typing a name in the input field below:</b></p>
<form> 
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>

gethint.php

<?php
//Instead of using these I'd like to use the external JSON file
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from "" 
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
    if (stristr($q, substr($name, 0, $len))) {
        if ($hint === "") {
            $hint = $name;
        } else {
            $hint .= ", $name";
        }
    }
}
}
// Output "no suggestion" if no hint was found or output correct values 
echo $hint === "" ? "no suggestion" : $hint;
?>

Upvotes: 1

Views: 718

Answers (1)

blex
blex

Reputation: 25634

You simply need to get the contents of your JSON file using file_get_contents, convert it to an actual array using json_decode, and get the name of each item to check them against your search query:

<?php

// Here, the TRUE parameter is very important to treat it as an associative array
$films = json_decode(file_get_contents("path/to/your_json_file.json"), true);

// get the q parameter from URL if it is set
$q = isset($_REQUEST["q"]) ? $_REQUEST["q"] : "";
$hint = "";
// lookup all hints from array
$q = strtolower($q);
$len = strlen($q);
// For each film
foreach($films as $film) {//                                     <------
    // Get the name
    $name = $film['name'];//                                     <------
    // If the query is empty or if the query is found
    if ($q === "" || stristr($q, substr($name, 0, $len))) {//    <------
        if ($hint === "") {
            $hint = $name;
        } else {
            $hint .= ", $name";
        }
    }
}
// Output "no suggestion" if no hint was found or output correct values 
echo $hint === "" ? "no suggestion" : $hint;


?>

Upvotes: 1

Related Questions