Skip to content
Advertisement

Search a google spread sheet using JQuery

I want to search a specific column in my google spreadsheet which contains strings. I used PHP to read the data from the sheet and stored them into an array. Printing the array shows me the column values, however when using (json_encode), I am only getting the last value in the array which is pretty weird.

Here is my code:

<?php
require 'vendor/autoload.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Publications</title>
<meta charset="utf-8">
</head>
<body>
    <?php
    $client = new Google_Client();
    $client->setApplicationName('Google Sheets and PHP');
    $client->setScopes([Google_Service_Sheets::SPREADSHEETS]);
    $client->setAccessType('offline');
    $credentials_file = __DIR__ . "/TestCase-641dce71a5df.json";
    $spreadsheetId = '1wP-NqVcGK9CBSPQRQ_oognVuKF07wsuiHjOAP0rQ3xI';
    $range = 'Responses!F2:F';
    $client->setAuthConfig($credentials_file);
    $service = new Google_Service_Sheets($client);
    $response = $service->spreadsheets_values->get($spreadsheetId, $range);
    $values = $response->getValues();
    if (empty($values)) {
        print "No data found.n";
    } else {
        foreach ($values as $row) {
            $values_array = array($row[0]);
            echo "Normal:",json_encode($values_array), "n";
        }
    }
    ?>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    var complexArray = <?php echo json_encode($values_array); ?>;
    console.log(complexArray);
    $("complexArray").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});
</script>
<h2>Filterable Table</h2>
<p>Type something in the input field to search</p>  
<input id="myInput" type="text" placeholder="Search..">
<br><br>
</body>
</html>

Advertisement

Answer

You’re rewriting the array to the last value here:

$values_array = array($row[0]);

Try

var complexArray = <?php echo json_encode($values); ?>;
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement