PHP (getAutocomplete.php)
<?php
header("Content-Type: application/json");
// Ensure a query parameter is provided
if (isset($_GET['q']) && !empty($_GET['q'])) {
$query = urlencode($_GET['q']);
// Google suggestion endpoint
$url = "http://suggestqueries.google.com/complete/search?client=firefox&q={$query}";
// Fetch suggestions from Google
$response = file_get_contents($url);
if ($response !== false) {
echo $response;
} else {
echo json_encode(["error" => "Unable to fetch suggestions"]);
}
} else {
echo json_encode(["error" => "No query provided"]);
}
?>
HTML & JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Google Autocomplete without API Key</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
#suggestions {
border: 1px solid #ccc;
max-width: 300px;
margin-top: 5px;
}
.suggestion-item {
padding: 5px;
cursor: pointer;
}
.suggestion-item:hover {
background-color: #f0f0f0;
}
</style>
</head>
<body>
<input type="text" id="autocomplete" placeholder="Type to search..." style="width: 300px; padding: 10px;">
<div id="suggestions"></div>
<script>
$(document).ready(function() {
$('#autocomplete').on('input', function() {
let query = $(this).val();
// Clear suggestions if query is empty
if (!query) {
$('#suggestions').empty();
return;
}
// Call PHP proxy to get suggestions
$.ajax({
url: 'getAutocomplete.php',
data: { q: query },
dataType: 'json',
success: function(data) {
// The response is an array where the second element holds the suggestions
let suggestions = data[1];
let suggestionHtml = "";
suggestions.forEach(function(item) {
suggestionHtml += `<div class="suggestion-item">${item}</div>`;
});
$('#suggestions').html(suggestionHtml);
},
error: function() {
$('#suggestions').html("<div class='suggestion-item'>Error fetching suggestions</div>");
}
});
});
// Optionally handle suggestion click
$(document).on('click', '.suggestion-item', function() {
$('#autocomplete').val($(this).text());
$('#suggestions').empty();
});
});
</script>
</body>
</html>
How It Works
PHP Proxy (getAutocomplete.php):
Accepts a query string (q) from the client.
Forwards the query to Google's suggestion endpoint.
Returns the JSON response to the client.
HTML & JavaScript:
The input field listens for user input.
On every input change, an AJAX request is made to the PHP proxy.
Suggestions from Google are extracted (the second element of the returned JSON array) and displayed.
Clicking on a suggestion fills the input field with that value.
0 Comments