tutorial on updating database status with ajax in Laravel

Currently, I am using Laravel in my project and I need to modify the patient's status when they schedule an appointment with a doctor. The patient can have one of three statuses: Accept, Waiting (automatically assigned when the patient selects a date and time), or Not Accept. However, I am encountering an issue where clicking on the active button does not result in any changes in the database.

This is the controller responsible for changing the status:

public function changeStatus(Request $request)
{
    $user = rdv::find($request->IDP);
    $user->Etat_de_rdv = $request->status;
    $user->save();

    return response()->json(['success'=>'Status changed successfully.']);
}

This is the controller used when a patient schedules an appointment:

public function rdv(Request $request) {

        // Variables: input values
          $date=$request->input('time');
          $time=$request->input('date');
          $doctor=$request->input('goID');
        // Array to compare inputs to existing values in the database
          $att = [
            'IDD' => $doctor,
            'time' => $time,
            'date' => $date
                ];

            $data=rendezvous::where($att)->first();
        // Required inputs 
        $this->validate($request, [
            'np' => 'required', 
            'tel' => 'required',
            'date' => 'required',
            'time' => 'required',
        ]);
        // Adding to rendezvous
        $rdv = new rendezvous() ;
        $patient_id=$request->session()->get('patient_id');
        $rdv->Nom_et_prénom=$request->input('np');
        $rdv->Numéro_de_téléphone=$request->input('tel');
        $rdv->IDD=$request->input('goID');
        $rdv->date=$request->input('time');
        $rdv->time=$request->input('date');
        $rdv->IDP=$patient_id;

        // Checking if data already exists
           if ($data!==null) {
              return redirect()->back()->withErrors('Time and date are occupied, please choose another!' ) ;
           }

        $rdv-> save();
        return redirect("/rendezvous_$doctor")->withSuccess('Appointment saved, please check the status of your appointment!') ; 

    }

This is the view that the doctor sees with all appointments:

<h3> Your patients :</h3>
 @foreach($pat as $lo)
@if ($lo->IDD== $med->ID)
<div class="admin">
<div class="info">
<h3> {{ $lo->Nom_et_prénom  }} </h3>
<p>{{ $lo->Numéro_de_téléphone }}</p>
<p>{{ $lo->date}}</p>
<p>{{ $lo->time }}</p>
 <input data-id="{{$lo->IPD}}" class="toggle-class" type="checkbox" data-onstyle="success" data-offstyle="danger" data-toggle="toggle" data-on="Accept" data-off="Busy Time" {{ $lo->Etat_de_rdv ? 'checked' : '' }}>
</div>
 </div>
 @endif
 @endforeach  

This is the Ajax script:

   <script>
      $(function() {
        $('.toggle-class').change(function() {
            var Etat_de_rdv = $(this).prop('checked') == true ? Accept : Busy Time; 
            var id = $(this).data('IPD'); 
            $.ajax({
                type: "GET",
                dataType: "json",
                url: '/changeStatus',
                data: {'Etat_de_rdv': 'status', 'IDP': id},
                success: function(data){
                  console.log(data.success)
                }
            });
        })
      })
    </script>

Answer №1

Make sure you are passing the correct parameter inside your ajax request. Instead of using 'Etat_de_rdv', consider using 'status' which holds the value you need. Take a look at the example below:

        var Etat_de_rdv = $(this).prop('checked') == true ? Accepter : Temps charger; 
        var id = $(this).data('IDP'); 
        $.ajax({
            type: "GET",
            dataType: "json",
            url: '/changeStatus',
            data: {
                'status': 'your_value', //Use this instead
                'IDP': id
            },
            success: function(data){
              console.log(data.success)
            }
        });

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

Exploring the dynamic duo of MongoDB and GridFS

We currently manage a large-scale project that accommodates thousands of users daily. Our database system is MySQL, but we are considering transitioning to MongoDB along with GridFS. Is it feasible to utilize MongoDB and GridFS for projects on this scale? ...

Updating API calls with form submission in React.js

Currently working on a weather application and attempting to update my API call upon submitting a form. This project marks my initial attempt at developing my own program, and I've encountered an obstacle. The plan is for the user to input a city, cli ...

Generate a distinct identifier for the select element ID whenever a new row of data is inserted into a table

Although my title accurately describes my issue, I believe the solutions I have been attempting may not be on the right track. I am relatively new to javascript and web development in general, so please forgive me for any lack of technical terminology. Th ...

What is the best method for constructing an array of sets using Raphael?

This code snippet creates a total of 48 squares, each labeled with a number from 0 to 47 within them. Utilizing sets is the recommended method for achieving this on stackoverflow. By grouping the rectangle shape along with its corresponding number, it allo ...

Troubleshooting the issue: Incompatibility between jQuery .focus() and dynamically generated list items from ng-repeat in AngularJS

I am currently working on enhancing the keyboard accessibility of a website, specifically focusing on making a dropdown menu accessible via keyboard. I am attempting to establish focus on the element with the id= list-0. Below is the HTML code snippet: & ...

If the prompt displays 'Monday', then you can output the following days in the console: 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', and 'Sunday'

Could someone assist me with modifying my code so that the entered day is displayed at the end of all days in the console? Currently, it shows up at the top. Here is what I have tried: JavaScript const daysOfWeek = ["monday", "tuesday" ...

Show the button's value in the textbox and update the selected button's color using JavaScript

I am having difficulty changing the background color of a selected button after displaying its value in a textbox. The code below successfully displays the button value in the textbox, but I can't figure out how to change the background color of the s ...

The object continues to be undefined despite its placement in a global scope

Currently, I am working on building a game of pong and encountering an issue with creating a paddle in the initialize method. Despite storing it as a global variable, the paddle remains undefined. I even tried making it a property of 'window', bu ...

Leveraging symbols as object key type in TypeScript

I am attempting to create an object with a symbol as the key type, following MDN's guidance: A symbol value may be used as an identifier for object properties [...] However, when trying to use it as the key property type: type obj = { [key: s ...

Deciphering the evolution of APIs and managing internal API systems

I'm currently exploring the world of APIs and I have a few questions that are puzzling me. Question1: I understand that APIs facilitate communication between different applications. But why would a company need an API for internal use? For example, i ...

Transmit HTML form information through a POST request to an ASP.NET web service

Having an HTML page with a contact form is great, but I'm facing the challenge of sending the data using AJAX. I attempted to send the data to a webservice without converting the structure to JSON format, but unfortunately, I did not succeed. Is ther ...

What is the process for retrieving the value of the 2nd td by clicking on the checkbox in the 1st td with JavaScript

When I click on "in", I am looking to retrieve the value of "out". This can be easily understood by referring to the image below: The timesheet displayed is generated using an array. All the data is stored in the array and needs to be presented in a table ...

The uploaded file in Laravel does not seem to be visible in the designated "public/storage" directory

After executing the command: php artisan storage:link, a new folder is created at /public/storage. Next, I have a piece of code that handles uploaded files: // Here we extract the original name and extension of the file // We then generate a new filename ...

Is it feasible to assess JavaScript expressions during compilation using Webpack?

I'm currently in the process of setting up webpack for a new project. This project is quite extensive and available in multiple languages. I am aiming to have each entry point in my project be represented by separate files in each language. The catch ...

How can you access and utilize the inline use of window.location.pathname within a ternary operator in

I need assistance with writing a conditional statement within Angularjs. Specifically, I want to update the page to have aria-current="page" when a tab is clicked. My approach involves checking if the tab's anchor href matches the current window' ...

Display multiple items from a JSON object in Django on the following page

I need to implement a feature that allows users to select multiple entries from a JSON object displayed in an HTML table. After selecting their entries and submitting, they should be redirected to a new page where only their chosen items are shown for conf ...

Is AngularJS the right choice for creating components?

Currently, I am developing a PHP web application with approximately 200 unique views. Most of these views simply display tables or forms. However, there are about 10 pages where users could benefit from dynamic/async components to prevent constant page re ...

What is the process for immediately changing the background color of an input field as soon as text is entered?

I am encountering an issue with the code snippet provided below. My goal is to change the background color of an input field as soon as I start typing something into it. The scenario involves 4 input fields where if the submit button is clicked and any f ...

Sending an Ajax request to C# code

UPDATE After some research, I discovered what seems to be the "correct way" to handle the issue by using a combination of JSON.stringify and creating a model, as explained in this thread. I still can't figure out why the original approach didn't ...

What is the best way to extract a value from two different HTML identifiers?

Something tells me that this task is quite simple. I just need some guidance on what I might be missing here. All I really want is a basic program that can extract the content from <span id "text"> and paste it into <div id="text2">. funct ...