Best practices for making an AJAX call to fetch information from a database

I have a database containing a single table. The table includes columns for Company and Time, among others, with Company and Time being crucial. Users can make appointments by filling out a form. Within the form, there are 2 <select> elements - one for selecting a Company and another for selecting a Time slot. Once both selections are made, the user clicks a button to store the form in the database. How can I utilize AJAX to retrieve all booked Time slots and disable them accordingly? For instance, if an appointment is made with Nokia at 9:30, that specific Time slot should be disabled to prevent overlapping bookings.


function MakeApp() {

    var AppWith = $("#CompanySelect").val();
    var AppTime = $("#TimeSelect").val();
    var Yritys = $("#YritysNtext").val();
    var Henkilonimi = $("#HenkilonimiText").val();
    var Asema = $("#AsemaText").val();
    var PuhelinNR = $("#PuhelinText").val();
    var EMail = $("#EMailText").val();
    var Keskustelun = $("#KeskustelunText").val();
    var app = { AppWithYritys: AppWith, AppTime: AppTime, YritysN: Yritys, Henkilonimi: Henkilonimi, Asema: Asema, PuhelinNR: PuhelinNR, EMail: EMail, Keskustelun: Keskustelun }

        var request = $.ajax({
            type: "POST",
            data: JSON.stringify(app),
            url: "/api/Appointments",
            contentType: "application/json",
            dataType: "html"
        });
        request.done(function (podaci) {
            if (podaci != -1) {
                alert("You Have successfully made an appointment");
                location.assign("BookAppointment.html");
            }
            else {
                $("#p1").html("Greska pri unosu");
            }
        });

        request.fail(function (gr) {
            $("#p1").html(gr.statusText);
        });
};

Answer №1

In reality, it is the responsibility of your server to manage data and databases. AJAX simply provides a method for sending information to a server asynchronously. One approach you could take is to use AJAX to retrieve only the occupied times when the page loads. Then, you can disable those options in your select menu. When the server receives a request, it checks if there are any available slots for the company and times.

Unfortunately, I don't have specific code to provide since the concept seems pretty clear. However, if you need further assistance, feel free to ask, and I will do my best to help.

Edit

Below are a few lines of code outlining the main algorithm, though it's not complete as some details are missing.

Your server:

{GET}
public void getUnavailable() {
    // Retrieve all times from the database for today's date.
    // Encode them in JSON format.
    // Return the unavailable times.
}

Assuming your JSON data looks like this:

[
{
    "company": "Nokia",
    "times": [
        "9:30",
        "10:00",
        "10:30"
    ]
}
]

You'll need to fetch and parse this JSON data to disable certain selections in the dropdown list:

$(document).ready(function(){
$.ajax({
    'url': API_URL + 'event/getUnavailable',
    'method': 'GET',
    'success': function(data) {
        $.each(data.data, function($index, $company){
            var select = /* .. Get the Select of the current company .. */
            $.each($company.times, function($index, $times){
                select./*.. Find the time associate with $time .. */.setDisable(true); // You may need to verify if setDisable is the correct function to use.
            })
        })
    },
    'error': function(error) {
        console.error(error.data);
    }
});

$('.myForm').submit(function(){
    // Submit your data to the server here.
    $.ajax({
        'url': API_URL + "event/create",
        'method': 'POST',
        'data': /* your data */,
        'success': function(){
            console.log('success');
        },
        'error': function(error) {
            console.error(error);
        }
    })
});
})

This is the extent of what I can provide based on the information given.

Answer №2

The best approach to tackling this issue is to utilize the web technology powering /api/Appointments to fetch and display available appointments. It seems that the variable names used may be confusing, so take some time to comprehend the code snippet provided below.

$.get( "/api/Appointments", JSON.stringify(app) )
  .done(function( data ) {
    // Take note that the "data" variable contains the list of available appointments
    // You can return a JSON document listing available appointment times to filter your selection


    // An example of the JSON structure could be like this
    // { "availableAppointments": ["9:30 AM", "10:00 AM"] }


    // Proceed to iterate through each available appointment and populate your selection dropdown
    for(var i = 0; i < data.availableAppointments.length; i++){
         $('#yourSelectId').append($('<option>', {
           value: '930',
           text: data.availableAppointments[i]
         }));
    }

  });

Please bear in mind that this code snippet might not be entirely accurate from a syntax perspective.

Below are some helpful links that guided me in providing this solution, in case you find them useful as well.

Adding options to a <select> using jQuery?

https://api.jquery.com/jquery.get/

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

When working with Angular 12, the target environment lacks support for dynamic import() syntax. Therefore, utilizing external type 'module' within a script is not feasible

My current issue involves using dynamic import code to bring in a js library during runtime: export class AuthService { constructor() { import('https://apis.google.com/js/platform.js').then(result => { console.log(resul ...

Are you able to develop a customized TestNG Listener to cater to your specific requirements?

I have developed a unique concept for a TestNG listener that meets my specific requirements. Essentially, I aim to design a custom listener that generates a report using a predefined HTML format. The crux of my idea revolves around declaring the listener ...

creating a nested JavaScript object within another object

I need to create an object using the angular.forEach() function and then push another object while initializing all values to false. However, the current approach is causing errors. How can I achieve this correctly? Using "item.id" and "index.id" does not ...

Having issues with regEX functionality in an Angular form

I need to validate a phone number using regEX. My criteria is as follows: 10 digits alpha/numeric, where an Alpha CHAR is in the 4th position (excluding hyphens). For example: 586R410056  NNN ANN NNNN  (NNN) ANN NNNN  NNN-ANN-NNNN  (NNN) AN ...

Generating dynamic divs in parallel

Despite encountering numerous posts related to the issue at hand, none of them have solved my specific problem. I am aiming for 3 divs to display in each row, but the current code is causing each div to show up on a new line vertically: JQuery ...

Using placeholders with inputs in an Angular2 table generated by ngFor

I have an array public example = [['hallo', 'fruit', 'rose'], ['apple','book']] Currently, I am working on creating a table of inputs. The values in this table depend on the specific part that I am usin ...

jquery form submission issue unresolved

I am currently utilizing jQuery version 1.10.1 and here is a snippet of my HTML code: <li> <a href='' id='logout'>Log Out</a></li> <form id='logout_form' method='post'> <i ...

Is it possible to trigger the onNewRequest property when the onBlur event is fired for AutoComplete in Material-UI?

Currently, I am utilizing Material-UI and making use of the onNewRequest property in the AutoComplete field. However, the onNewRequest only triggers when Enter is pressed or when a value is selected. I am interested in calling the onNewRequest even when ...

Mastering the art of grouping by a key and generating sub-objects from a plain array of key-value pairs in JavaScript ES5 without relying on third-party libraries

My dataset consists of an array of objects, each containing 4 keys: [ { "team": "USA", "team_profile_id": "10", "player": "Captain America", "player_id": "10X1" }, { "team": "USA", "team_profile_id": "10", "player": "The ...

Is there a way to implement the adjacent selector in combination with the :before selector?

Hello there, I am working on a timeline area with a slick effect and have implemented slick.js for that purpose. I am trying to change the color of my spans within the elements. Specifically, I changed the first span in the slick-active class element succe ...

Tips for updating form tag details within the same blade file upon reloading

I have set up a payment page that displays the total amount to be paid. To facilitate payments through a 3rd party gateway, I have utilized a form tag on the page. Now, I am looking to integrate a promo code feature on this payment page so that the total a ...

Tips on customizing the CSS responsiveness of your Bootstrap carousel

I have recently installed a Bootstrap theme on my Wordpress site and I am trying to make some CSS adjustments. One issue I am facing is with the carousel. Currently, when I resize the website or view it on a mobile device... The carousel maintains a lar ...

Tips for integrating jwt token into axios request

I am facing an issue with my backend endpoint. I can successfully retrieve a list of customers using jwt token on Postman, but when I try to fetch the list from a React app using axios get request, it fails. After reading through this question, I implemen ...

Utilizing jQuery Ajax to submit multiple forms using a single selector in one go

I'm having an issue with jQuery Ajax involving multiple forms. Each time I execute it, only the top form works properly while the others do not function as expected. Can anyone provide assistance with this? Here is the source code: <form id="form_ ...

Using jQuery to set the background-image on the body's after pseudo-element with CSS

I am currently utilizing body:after for setting the page wallpaper. body:after { background-image: url('assets/img/wallpapers/<?php echo $getWallpaperFile; ?>'); } CSS content: ' '; display: block; position: absolute; left: ...

Tips for organizing dynamic table data following an append operation

Hey there! I'm currently working on a project involving sorting students after applying filters. Once the students have been filtered, I need to append classes and text to buttons as shown in the image below: https://i.stack.imgur.com/c9Mtm.png The HT ...

Display various v-dialog boxes with distinct contents in a vue.js environment

Hello there! I am currently working on customizing a Vue.js template and I have encountered an issue with displaying dynamic v-dialogs using a looping statement. Currently, the dialog shows all at once instead of individually. Here is the structure of my ...

The MongoClient object does not possess the 'open' method

I recently started working on a project using Node.js, Express.js, and MongoDB. I've encountered some issues while trying to set up the database configuration. Below is a snippet of code from my index.js file: var http = require('http'), ...

angular trustAsHtml does not automatically insert content

Two divs are present on the page. Upon clicking button1, an iframe is loaded into div1. The same applies to button2 and div2. These iframes are loaded via ajax and trusted using $sce.trustAsHtml. This is how the HTML looks: <div ng-bind-html="video.tru ...

Data binding in Vue.js seems to be malfunctioning

I'm having trouble with my Vue component creation. I've been using v-show to hide certain elements, but it doesn't seem to be working as intended. The goal is to hide an element when clicked from a list by setting element.visible to false i ...