What steps can be taken to display database results solely for the user currently logged in and created by them?

Currently, I'm in the midst of a project that involves extracting an HTML list from JSON data using JavaScript. The list is being displayed on the logged-in user's profile, showcasing job listings from the JSON data. While I've successfully implemented a search filter, I now aim to modify the list to show only the jobs posted by the user currently logged in. Although I grasp the underlying concept, I'm unsure about how to incorporate this functionality in JavaScript.

The proposed approach:

  1. Retrieve job data from JSON.
  2. Obtain the ID of the currently logged-in user.
  3. Match the user's ID with the createdByID field in the JSON data for each job.
  4. Show the jobs with matching IDs and hide those that don't.

VIEW WORKING EXAMPLE ON CODEPEN

Here is the functioning JavaScript code:

//USER'S ID NUMBER
var userID = "123456789"

//MATCH THIS WITH THE createdByID NUMBER FROM JSON DATA
//...code here...


//SEARCH FILTER:
$(document).ready(function() {
  $("#jobsSearch").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#jobsData tr").filter(function() {
      $(this).toggle($(this).text()
                     .toLowerCase().indexOf(value) > -1)
    });
  });
});

// Remaining JavaScript code omitted for brevity

The HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <!-- Additional HTML code omitted for brevity -->

    </head>
    <body style="padding-left: 5%; padding-right: 5%;">

        <!-- Additional HTML code omitted for brevity -->

    </body>
</html>

And the CSS:

html {
  scroll-behavior: smooth;
}

// Remaining CSS code omitted for brevity

I am eager to gain a deeper understanding of how to implement this feature. Any guidance or assistance would be greatly appreciated. Thank you.

Answer №1

Consider incorporating an if condition when initializing the variable tblRow.

It's important to note that the retrieved createdByID field is of type number, not string.


if(f.createdByID === 123456789){
        
      var tblRow = "<tr>" +
          "<td style='padding-top: 1%; padding-bottom: 1%;'>" +
             ...
             ...
             ...
          "</tr>"

}

My suggestion is to either modify or add an API request in the backend. When fetching JSON data, make sure to include the logged-in user's ID as a URL parameter to only retrieve their list, rather than the entire list.

Answer №2

If your JSON data includes an array named 'records', you can easily filter them based on the ID of the logged-in user. Here is how you can do it:

unfilteredRecords=data.records;
id='rec6LJ0WUy30M4Cys';
filteredRecords=unfilteredRecords.filter(record => record.id==id);

Simply insert this code right after function(data) {...

function(data) {
    unfilteredRecords=data.records;
    id='rec6LJ0WUy30M4Cys';
    filteredRecords=unfilteredRecords.filter(record => record.id==id);
    $.each(filteredRecords... 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering a way to capture the space bar event in a number input field with JavaScript

Is there a way to capture space bar input with an onchange event in JavaScript? <html> <head> <script type = "text/javascript"> function lala(aa){ console.log(aa + " dasda"); } </script> </head> <body> <input ty ...

The values on my text label are not refreshing when I make API calls

Currently, I am facing an issue with my API call. I am passing a parameter value to the API and appending the data to a model. However, when I try to display this data on a label, I encounter an "index out of range" crash. func fetchProfileData() { ...

Transforming a CSV document into a JSON format in order to generate a hierarchical tree structure for constructing a D3 categorical tree diagram

I have a CSV file that is structured like this: "","Sequence","Paths","sequence_length" "1","Social -> Social -> Social -> Social -> Social -> Social -> Social -> Social",29,8 "2","Social -> Social -> Social -> Social -> S ...

The perfect way to override jest mocks that are specified in the "__mocks__" directory

Within the module fetchStuff, I have a mock function named registerAccount that is responsible for fetching data from an API. To test this mock function, I've created a mock file called __mocks__/fetchStuff.ts. Everything seems to be functioning corre ...

Individualize JavaScript clients for each module in ExpressJS

Exploring the modular folder structure demonstrated by tjholowaychuk in this video. Is there a way to include a distinct client-side JavaScript file within each module? Currently, all my client JS resides in the /assets/js folder, but having a separate JS ...

Sometimes, CSS unicode characters may not render correctly and appear as jumbled symbols like "â–¾"

https://i.sstatic.net/eGvzJ.jpg Every now and then, about 1 in every 100 page refreshes, the unicode characters on my page turn into jumbled nonsense (you might need to zoom in to see it clearly). Specifically, the unicode characters are displayed as â ...

"Adjust the orientation of a video and ensure it properly fills the screen with CSS styling

Below is the CSS style being used: video { position: absolute; transform: rotate(90deg); width: 100%; height: 100%; z-index: 4; visibility: visible; } This code snippet demonstrates a video element: <video id="myVideo" ...

What steps are needed to set up my Express server so that it can render all my content, rather than just my HTML file?

I need help setting up a server for my project using Express. Here is the structure of my file directory: root-directory ├── public │ ├── css │ │ └── styles.css │ ├── images │ │ └── img1.png | | └ ...

I just stumbled upon Jupyter and I'm curious - can I utilize Javascript and store it in the cloud?

Yesterday evening, I stumbled upon Jupyter and began using it alongside Python. It seems like an excellent tool for coding, something that I've been in need of, but I'm not sure if I can integrate JavaScript with it. I noticed there are npm packa ...

Interweaving jQuery scripts

After successfully implementing a form with jQuery, I decided to add a date picker using another jQuery code. Unfortunately, the two codes clashed and now they do not work together. Here is the initial jQuery code for the form: <!doctype html> <h ...

The X path and CSS selector for a particular table will vary on every page

Hello, I am new to HTML and currently working on a project that involves scraping data from html tables using RSelenium. I have managed to use the following code successfully: for(i in 1:50){ remDR$navigate(URLs[i]) CPSHList[[i]] <- remDR$getPageSou ...

Implications of using literals, objects, or classes as arguments in functions that are called multiple times can have

Context A project I'm working on involves a scenario where a Shape class is triggering a function call SetPosition( x, y ) on a Drawer class. As part of this process, the Drawer class needs to retain the values (x, y) passed through SetPosition. The ...

Difficulties encountered when attempting to populate a select dropdown with data fetched through an AJAX request

Currently, I am working on a small project that involves managing libraries. One of the tasks at hand is populating a select tag with all the libraries stored in my database. To accomplish this, I have developed a WebService which features a web method cal ...

How to use jQuery to dynamically set the value of a column span in a

Struggling with setting the value for a table column span. Here is my jQuery code: $('tr td data-th=Name span').val('My span content...'); This is how my HTML appears: <tr> <td data-th="Name"><span class="edit-inpu ...

Tips for importing extensions with Rselenium

I could use some assistance in understanding how to activate a chrome extension using RSelenium. The extensions are visible in the browser tabs but are not automatically loaded when working with RSelenium. https://i.sstatic.net/QKqVg.png ...

What steps should I follow to develop a REST API that can retrieve a JSON or XML file from a client?

In need to create a PHP RESTful service that can exchange JSON data with the user - sending JSON and receiving either JSON or XML. While I have experience in sending JSON or XML data, I'm unsure about how to properly retrieve data from the user. ...

Display the full price when no discount is available, but only reveal the discounted price when Vue.js is present

In my collection of objects, each item is structured like this: orders : [ { id: 1, image: require("./assets/imgs/product1.png"), originalPrice: 40, discountPrice: "", buyBtn: require(&q ...

Assign a value to the Angular directive for the SharePoint People Picker

In my create form, I have successfully used a directive to capture and store values in SharePoint via REST. The directive I am using can be found at this link. Within my HTML, I am implementing the directive like this: <sp-people-picker name="CC" id=" ...

Adjust the line spacing in CSS depending on the length of the text

Upon page load, a ul list is dynamically generated via JavaScript. The relevant code snippet is as follows: <ul class="tweet_list"><li class="tweet_first tweet_odd"></li></ul> Related CSS: ​ul.tweet_list li { height: 55px; ...

"Building a dynamic form with ReactJS, Redux Form, and Material UI - Implementing an

Currently working on a nested form framework that utilizes the redux form and material UI framework. The components have been developed up to this point - https://codesandbox.io/s/bold-sunset-uc4t5 My goal is to incorporate an autocomplete field into the ...