A guide on efficiently implementing foreach within an Ajax GET request

I am facing an issue with displaying appointments on a calendar specifically for the logged-in user while grayed out for other users. Below is the table structure:

App. 1 user 1 06/15/2024 8:00 06/15/2024 9:00 Test the code
App. 2 user 2 06/15/2024 8:00 06/15/2024 9:00 Test the code
App. 3 user 3 06/15/2024 8:00 06/15/2024 9:00 Test the code
App. 4 user 1 06/15/2024 8:00 06/15/2024 9:00 Test the code

If "User1" is logged in, they would see the appointments as follows:

App. 1 user 1 06/15/2024 8:00 06/15/2024 9:00 Test the code
App. 2 06/15/2024 8:00 06/15/2024 9:00
App. 3 06/15/2024 8:00 06/15/2024 9:00
App. 4 user 1 06/15/2024 8:00 06/15/2024 9:00 Test the code

In order to display these appointments using Fullcalendar.io, I need to load events via ajax using the GET method:

eventSources: [
    {
        url: '/Calendar/GetEvents',
        method: 'GET',
        failure: function () {
            alert('there was an error while fetching events!');
        },
        color: 'orange',
        textColor: 'black'
    }
]

I am looking to implement a foreach loop within the ajax call to differentiate and customize the view of appointments based on logged-in user. Any suggestions or guidance on how to achieve this are greatly appreciated.

Best Regards,

Sven

Answer №1

In order to achieve this, it is necessary to utilize the success callback function as demonstrated below:

success: function(response) {
  var events = [];

  // Assuming 'response' is an array of event objects
  response.forEach(function (event) {
    if (event.userId === loggedInUserId) {
      // Display full details for events belonging to the logged-in user
      events.push({
        title: event.title,
        start: event.start,
        end: event.end,
        color: 'orange',
        textColor: 'black'
      });
    } else {
     // Display only date and time for events not belonging to the logged-in user
        events.push({
          title: '',
          start: event.start,
          end: event.end,
          color: 'gray',
          textColor: 'white'
        });
      }
    });

    // Pass the events array to the success callback
    successCallback(events);
 }

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

I am having trouble setting an object in the state using React hooks

When assigning an initial value to a state as null, the setState method does not hold the value when assigned. Calling an API in useState returns an object which cannot be directly put into setState. const [userProfile, setProfile] = useState(null); cons ...

ReactJS and MaterialUI: Creating a Dynamic Triangle Button Slider

I am facing a challenge in creating a triangle-shaped button for a slider in Material UI and ReactJS, instead of the current pizza slice shape. Here is an example of the desired outcome: https://i.sstatic.net/pNn93.png Here is the current state of the sl ...

Steps for sending a POST request to an API with an extensive amount of fields (50 or more)

Struggling with a complex API call that involves submitting all the form data. Finding it difficult to determine the most effective method for sending the serialized data to the API endpoint. One option is to gather all field values into a JavaScript ob ...

"Utilize browser detection to direct users to appropriate pages - whether by using htaccess or another method

I'm in the process of creating a website and I've noticed that it looks quite bad on Firefox and IE. I was wondering if you could help me figure out how to redirect users to different pages based on the browser they are using. Since I am not an ...

How do I create a notification when the div reaches 100% alignment on the left side using Javascript?

Is there a way to receive an alert when the div with the class name "earth" reaches 100% on the left side, without using jQuery? I attempted to utilize setTimeout but I am looking for an alternative method that does not rely on time, but rather on positi ...

Incorporating an HTML header into a QNetworkReply

I have implemented a customized QNetworkAccessManager and subclassed QNetworkReply to handle unique AJAX requests from a JavaScript application. It is functioning mostly as expected, but I have encountered an issue where my network replies seem to be missi ...

Retrieving information from an object using a randomly generated identifier

Imagine having an object structured like this. var foo = { "dfsghasdgsad":{ "name":"bob", "age":"27" } }; The variable foo will consistently only have one object, but the key is dynamically created. How can I access the values "bob" and "27" ...

Adding a loading event listener to an object in JavaScript: A step-by-step guide

I'm currently deep into developing a game using sprites in JavaScript. I've been trying to incorporate an event listener that verifies whether the sprite images have loaded before beginning the game. Employing object-oriented programming, I' ...

Unable to remove jQuery variable using jQuery .remove() method

My goal is to remove the $movieDiv that appears when I click "#buttonLicensedMovie". It successfully appends to the html and the button hides as expected. However, I am encountering an issue when clicking the anchor tag with id "licensedMovie1", the $movie ...

What is the best way to handle the keystroke event in a $.bind method?

I'm struggling with passing a specific keystroke through the bind method. $(document).bind('keyup', event, keyup_handler(event)); This is my attempt at solving it.. Here is the function it should be passed to: var keyup_handler = functio ...

Convert PHP array into a 2D JavaScript array

I am currently tackling the task of passing two SQL fields through PHP to JavaScript. While I have researched extensively on creating multidimensional arrays in JavaScript, I find myself stuck when it comes to translating PHP code into JavaScript. Although ...

What is the best way to find out if an array index is within a certain distance of another index?

I'm currently developing a circular carousel feature. With an array of n items, where n is greater than 6 in my current scenario, I need to identify all items within the array that are either less than or equal to 3 positions away from a specific inde ...

Utilizing jQuery/Ajax to send an ID parameter to a PHP script

This code is where the user interacts. <html> <head> <title></title> <script src="jquery-1.9.1.js"></script> <script src="jquery.form.js"></script> </head> <body> <?php include 'con ...

Tips for verifying a text input as an email address using JQuery

Can someone help me with writing an if statement that checks if two fields are empty and confirms if one of them is a valid email address? Also, how can I validate if the email address entered is indeed valid? var fullname = $("#name").val(); var emai ...

What is the best way to organize these checkboxes using BootstrapVue's layout and grid system?

My BootstrapVue table setup looks like this: https://i.sstatic.net/K3Rwy.png This is the code for the table: window.onload = () => { new Vue({ el: '#app', computed: { visibleFields() { return this.fields.filter(field ...

The Vue-router is constantly adding a # symbol to the current routes, and it's important to note that this is not the typical problem of hash and

After setting up my router file using Vue 3, it looks like this: import { createRouter, createWebHistory } from "vue-router"; import Home from "../views/Home.vue"; const routes = [ { path: "/", name: &quo ...

What is the best way to incorporate a close button into an HTML video popup?

I have a cool feature on my website where an image can be clicked to reveal a popup video that starts playing. However, I would like to know how I can include a close button on the video itself so users can easily return to the website without having to hi ...

Exploring the source of the "Unexpected token ;" issue in an Express-JS application

Working on a project with Parse and Express-JS, I encountered an issue when trying to display an EJS page. The error message Unexpected token ; appeared while running the command line parse develop MyApp in Terminal. Below is the full stack trace of the er ...

"Sending a serialized form data to a webapi endpoint: a step-by-step

Seeking assistance with sending a form using ajax ($.post) to a webApi. The ajax request is successful, but when I send the data to the method in the web api, the form collection returns null and the method returns "false". Any help is greatly appreciated. ...

developing a deferred commitment by utilizing promise objects

Hi everyone, I've encountered an issue with a JavaScript promise question that's throwing errors function delay(n) { return new Promise((resolve) => setTimeout(resolve, n*1000)); } The expected output should be "It is now 2 seconds later" ...