Updating a form field dynamically with AJAX in Laravel

I'm working on updating the field $medic->current based on certain logic that I have in mind. I'm quite new to using AJAX and would appreciate a little guidance to kick things off.

In my code, I am calculating the difference between two dates { $medic->end_day , current date }. Depending on the difference in dates, I aim to modify the "current" field accordingly. If the difference is less than 0, then set current = 0, else set current = 1. This is what I am trying to achieve.

So, how can I utilize AJAX to update the "current" field of $medic. Below you will find the snippet of code:

<script>
          window.onload = checkcurrent;
          var today = new Date();   

          @foreach($medics as $medic)
            @if($medic->current == 1)
              function checkcurrent()
              {
                var status = {{$medic->current}};
                var last_date= new Date('{{ \Carbon\Carbon::createFromFormat('d/m/Y', $medic->end_day)->toDateString() }}');                
                var new_last_date = new Date(last_date.getFullYear(),last_date.getMonth(),last_date.getDate());
                var diff = parseInt((new_last_date - today) / (1000 * 60 * 60 * 24));                 
                if(diff<0)
                {
                  status = 0;

                  $.ajax({ 
                   url: "stocks/{stock_tag}/medications/updatecurrent/{info_id}", 
                  type: "put", 
                  data: { current: 0 } , 
                  success: function (response) { 
                    console.log('success');                    
                  }, 
                  error: function(jqXHR, textStatus, errorThrown) { 
                  console.log(textStatus, errorThrown); 
                  }             
                 }); 
                }                  
                else
                {
                  status = 1;                     
                }                           
              }
            @endif
          @endforeach



      </script>  

Additionally, here is the method in my controller:

public function updatecurrent($stock_tag,$info_id)
    {
        $stock = Stock::find($stock_tag);
        $findInformation= Medication::where('id','=',$info_id)->first();

        $id=Input::get('current');
        $stock->under_medication=$id;        
        $findInformation->current=$id;
        $stock->save();
        $findInformation->save();
    }

I specifically need some assistance with refining the ajax code as everything else seems to be functioning correctly. When the status is 0, my goal is to update the "current" field to 0. Any suggestions on how to accomplish this?

Answer №1

After exploring various options, I managed to resolve my problem by developing a function within the model itself.

Here is the customized code:

public function autocheck()
    {
        $stock =Stock::where('tag_no','=', $this->attributes['tag'])->first();
        $medication =Medication::where('tag','=',$stock->tag_no)->where('current','=',1)->first();        
        $today = Carbon::now();
        list($enddays_day, $enddays_month, $enddays_year) = explode('/', $medication->end_day);
        $last_day = Carbon::createFromDate($enddays_year,$enddays_month,$enddays_day);
        $difference = $last_day->diffInDays($today);

        if ($difference == 0) {
            return "ends today";
        }
        else
        if ($last_day < $today)
        {
            $medication->current = 0;
            $stock->under_medication = 0;
            $medication->save();
            $stock->save();
            return "Finished Medication ";
        }
        else
        {            
            return $difference." day left";
        }        

    }

To activate the function, simply utilize

{{$paramater->function_name()}}
. Here's how it can be incorporated in the code:

@if ($medic->current == 1)
 <h2>Status : {{ $medic->autocheck() }}</h2> 
@endif 

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

Customize form input using Javascript prior to inserting into database

On my Rails form, I have a basic setup like the following: <%= form_for @song do |f| %> <p> <%= f.label :url %><br> <%= f.text_field :url %> </p> <p> <%= f.submit %> </p> <% en ...

Error: AJAX requesting page not listed in manifest

When using a cached HTML page and JQuery, I've encountered difficulty accessing a page from the server that is not listed on the manifest. Every attempt I make to access a page not included in the manifest results in a return of null or an empty strin ...

The functionality of jquery.load() seems to be experiencing issues in Internet Explorer when attempting to load an HTML file

Code $('.form').load('http://'+window.location.hostname+':8423/html/form/form_generate.html/?session='+session); In an attempt to load a html file from a different port on the same server. The original server is accessible ...

Displaying the information from a nested array of objects in an HTML table through iteration

In the code snippet below, there is an input with a nested array of objects. The main array of objects is called summary and within it, there's a nested array called run_type. let input = { "summary": [ { " ...

Jest fails to pass when encountering the double colon

Having issues testing a React app using Jest. I encounter errors when running my code: FAIL src\App.test.js ● Test suite failed to run C:/Users/user1/Projects/map-editor/src/App.js: Unexpected token (40:33) 38 | <div cla ...

Async await function two is failing to execute

I am currently working on a process where I need to unzip a file first, wait for the unzipping process to complete, and then loop through each extracted file to upload it to an S3 bucket. The unzipPromise function is working as expected, successfully unz ...

Chrome extension triggers content script upon AJAX change

Recently, I developed a Chrome extension that modifies comments on a specific website. However, the website has undergone changes in its loading mechanism. Previously, the comment block would load with a simple post request and page reload, but now it loa ...

Transmitting information via Ajax, jquery, Node.js, and Express

Seeking assistance as I struggle to comprehend the process while trying to implement it based on various online resources. My carousel directs users right after signing up, and I aim to gather information about their profile through simple input questions. ...

Tips for displaying a message when clicking on the second level in fancytree.js

I'm looking to use fancytree.js to display an alert message only when clicking on nodes in the second level. For example: <ul> <li>1</li> <ul> <li>1.1</li> ...

Updating View in Angular 2 ngClass Issue

I'm encountering some challenges with updating my view using ngClass despite the back end updating correctly. Below is my controller: @Component({ selector: 'show-hide-table', template: ' <table> <thead> ...

What is the best way to display information related to a specific id in Vue.js?

Currently, I have all the records displayed on a page located at this URI xxx.test/employer/search/filter-by. The display of these records is powered by Algolia Search, and there is a button labeled View Profile, which triggers an empty method named showPr ...

What could be causing Wordpress Jquery to only function properly after a page refresh?

Here is the code snippet I am working with: <script type="text/javascript"> jQuery( document ).ready(function() { jQuery('#bookbtn_loc_1').on('click', function(event){ jQuery("a.da-close").click(); ...

Code-based document editing with CouchBase

To test Couchbase, I need to create a servlet that will edit 1,000 JSON documents by changing the value of '"flag": false' to '"flag": true'. How can I achieve this task? Here is my view code for finding documents with '"flag": fa ...

How can we compress videos on an Android device prior to uploading them through a web browser?

Can video compression be done prior to uploading via a web browser? For example, in iOS devices you can choose a video using the HTML input type file tag and iOS will automatically compress it before uploading. Are there any JavaScript or jQuery libraries ...

Different approaches to transforming jQuery code into functional AngularJS code

I am a beginner in AngularJS and I'm looking to implement functionality for a login page similar to the one you see when you click the 'Forgot Password' link: Would it be more appropriate to use a directive instead of a controller for this ...

Using javascript to store HTML tags in a variable

Hey there, I have a quick question. Can someone help me figure out why this code isn't working? let plus = "+" + '<h1>'+"This is a heading"+'</h1>'; When I run the code, the output I get is: +<h1 ...

Dragend event for images does not trigger in webkit when using TinyMCE

When using the TinyMCE editor, I tried binding the dragend event on images with the following code: _imagePlugin.editor.dom.bind(_imagePlugin.editor.dom.select('img'), 'dragend', function(){console.log('aaaa');}); Oddly enou ...

Having difficulty with Angular's ng-options feature in a Select element

I'm currently tackling an issue with using ng-options to iterate through an array of objects and display specific properties in a select element. Upon querying the api/admin endpoint, I receive JSON data containing details of all users holding the ad ...

Is it acceptable to initiate an import with a forward slash when importing from the root directory in Next.js?

I've noticed that this import works without any issues, but I couldn't find official documentation confirming its validity: // instead of using a complex nested import like this import { myUtil } from '../../../../../lib/utils' // this ...

Schema-based validation by Joi is recommended for this scenario

How can we apply Joi validation to the schema shown below? What is the process for validating nested objects and arrays in this context? const user = { address: { contactName: 'Sunny', detailAddress: { line1: & ...