0

I have a created sqlite server that holds JSON data about users. The data looks like this:

{
0:{
    id: 1,
    name:   "Sam Smith",
  },
1:{
    id: 2,
    name:   "Jane Smith",
  }
}

I also have a basic html page with a form:

<div id="input" class="searchuser">
        <form>
            <legend class="useradd-fonts">Search Existing User</legend>


            <label for="search_byname">Name: <input type="text" id="search_byname"/></label>
            <input type="button" id="get-btn" value="Search" /><br>
        </form>
</div>

I also have code for getting this data from the server with an XMLhttprequest(), however, the code only allows to get the whole JSON data and display all the users:

const getBtn = document.getElementById("get-btn");

const getData = function() {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", "http://127.0.0.1:3000/users");

    xhr.onload = function() {
        const data = JSON.parse(xhr.response);
        console.log(data);
    };
    xhr.send();

};

getBtn.addEventListener("click", getData);

My question is, how can I search a user by their name, so in the HTML form, write Sam Smith, and after clicking the button this will return only the first user's information and not all of the users in the dataset? I would like to do this with XMLhttprequests without using any external libraries, is this possible to do?

  • Yes, this is possible to do. Do you know how to filter data out of a JavaScript array? Do you know how to display the result? See the many Q&A on this site. For example [this](https://stackoverflow.com/questions/23720988/how-to-filter-json-data-in-javascript-or-jquery) – trincot Dec 25 '19 at 20:19
  • @trincot Yes I do know about filtering JSON data, however I do not understand how to add that filter to a XMLhttprequest. – user12231674 Dec 25 '19 at 20:26
  • You don't need to add filter logic to XMLhttprequest, you simply need to filter on the response `data` object `const data = JSON.parse(xhr.response);` – Sarvesh Mahajan Dec 25 '19 at 20:30
  • How do I filter the response? – user12231674 Dec 25 '19 at 20:36
  • I don't understand: *"I do know about filtering JSON data"* and *"How do I filter the response?"* contradict each other. The response is JSON... – trincot Dec 25 '19 at 21:41
  • To clear it up, I meant I know how to filter JSON data, if I just have a JSON file that I created myself, I know how to navigate and select different aspects of that JSON data, but I don't know how to filter the response variable in the XMLhttprequest, meaning I don't understand where to start in this line to filter the JSON : const data = JSON.parse(xhr.response); I have only been learning web development for 2 months, therefore, cannot see straight away what correlates to what and how to use basic JSON handling within functions. Hope that cleared it, in the end I didn't need to filter it. – user12231674 Dec 26 '19 at 02:01

3 Answers3

0

Backend side

You need to specify the search service in your backend firstly. For example, you may check if there is a GET parameter named search then filter users by given parameter value.

PHP

<?php

$search = @$_GET['search'];
$query = 'SELECT * FROM users';

if (strlen($search) > 0) 
  $query .= " WHERE name LIKE '%$search%'");
}

// Then execute $query and print data as json

?>

Express.js

app.get('/users', (req, res) => {
  let search = req.query.search;
  let query = 'SELECT * FROM users' + (
    search && search.length ? ` WHERE name LIKE '%${search}%'` : '';
  );

  // execute [query] and send response
});

The code above code is only for example purpose, don't use it in production which may lead to SQL Injection.

Frontend side

Change your js with that code:

const getBtn = document.getElementById("get-btn");
const searchByNameInput = document.getElementById("search_byname");

const getData = function() {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", "http://127.0.0.1:3000/users?search=" + encodeURIComponent(searchByNameInput.value));

    xhr.onload = function() {
        const data = JSON.parse(xhr.response);
        console.log(data);
    };
    xhr.send();

};

getBtn.addEventListener("click", getData);

In that code, we used query string to give the server additional arguments to filter our request. To specify query string you need to add ? (question mark) after the url and specify the parameters separated by & symbol.

https://website.tld/link/to/page?param1=value1&param2=value2&...&paramN=valueN

On the backend side, you can get the given parameters easily by using your language's or framework's features then filter results by using sql WHERE clause.

Here are other code examples to get query string parameters in different languages/frameworks.

halfer
  • 19,824
  • 17
  • 99
  • 186
TheMisir
  • 4,083
  • 1
  • 27
  • 37
  • The backend is not written in php but Javascript, and as I saw it takes a parameter users/:userID, so do I need to just add extra code that takes users/:userNAME ? – user12231674 Dec 25 '19 at 20:41
  • @user12231674 could you edit backend code. or the data is provided by the third-party? – TheMisir Dec 25 '19 at 20:42
  • I can edit it, but I should not have to, since the id: and name: and barcode: keys are there, I just need to use them somehow to filter the response. – user12231674 Dec 25 '19 at 20:48
  • Could you post the backend code (especially users request part) in somewhere? We need to check the code to let you know how to filter the response. – TheMisir Dec 25 '19 at 20:50
0

I have figured it out, the server has a separate javascript file that performs GET requests. Therefore instead of this:


    xhr.open("GET", "http://127.0.0.1:3000/users");


I should write this:

xhr.open("GET", "http://127.0.0.1:3000/search?type=user&name=" + input);
-1

This could be done two ways, you could filter the data before it is served to your web page (server logic), or you could just use the first object in your JSON array when it arrives at the web page, you might want to order the dataset before taking the first one.

If you are getting all the user's information in your query (xhr.open("GET", "http://127.0.0.1:3000/users")) and you are trying to filter it on the frontend, then your xhr.onload should be something like.

xhr.onload = () => {
        const jsonArray = JSON.parse(xhr.response);
        const user = Object.keys(jsonArray).map(key => jsonArray[key]).filter(e => e.name == document.getElementById("search_byname").value)[0];
        console.log(user );
    };

if your JSON array is already filtered (if you queried your database filtering by name), then it should be

xhr.onload = () => {
        const user = JSON.parse(xhr.response)[0];
        console.log(user);
    };
Yashwardhan Pauranik
  • 5,370
  • 5
  • 42
  • 65
Banned007
  • 15
  • 8
  • I cannot filter the data before I don't think, since I need to type any name that is present in the JSON data and it needs to show me everything corresponding to that name. – user12231674 Dec 25 '19 at 20:38
  • Then I did't understand your question. In the last part you said that you are going to be displaying the first one on the dataset, correct? – Banned007 Dec 25 '19 at 20:41
  • In the statement `xhr.open("GET", "http://127.0.0.1:3000/users");` are you asking for everything on your dataset? – Banned007 Dec 25 '19 at 20:47
  • It was only an example, I should be able to type any name, and that name and details about that user should display. – user12231674 Dec 25 '19 at 21:15