Retrieve information and auto-fill text boxes based on the selected dropdown menu option

UPDATED QUESTION STATUS

I'm currently working with Laravel 5.7 and VueJs 2.5.*. However, I am facing a challenge where I need to automatically populate form textboxes with data from the database when a dropdown option is selected. Despite my efforts over several days, I have not been successful in finding a solution as I am relatively new to this.

WHAT I AIM TO ACHIEVE: I have two types of invoices: VendorInvoice and CustomerInvoice. After creating and storing data for a VendorInvoice in the database, I want to be able to autofill the same data into a CustomerInvoice. Essentially, upon selecting a VendorInvoice option from a dropdown list in the CustomerInvoice form, the fields should automatically populate with the corresponding details from the VendorInvoice and its items. This eliminates the need for manual data entry when creating a CustomerInvoice.

In my code:

VendorInvoice = ticketInvoice & VendorInvoiceItems = ticketInvoiceItems CustomerInvoice = ctInvoice & CustomerInvoiceItems = ctInvoiceItems

If anyone could assist me in resolving this issue, I would greatly appreciate it. Thank you.

This is the HTML <select> and some ctInvoice & ctInvoiceItems fields that I want to autofill:

<form @submit.prevent="editmode ? updateCtInvoice() : createCtInvoice()">
  <div class="modal-body">
    <div class="row">

      <!-- =====VENDOR INVOICE SELECTION===== -->
      <select id="ticket_invoice_no" v-model="selectedTicketInvoiceId" @change="getRecord" name="ticket_invoice_no" type="text" class="form-control">
        <option v-for="ticketInvoice in ticketInvoices" :key="ticketInvoice.id" :value="ticketInvoice.id">{{ ticketInvoice.ticket_invoice_no }}</option>
      </select>

      <!-- =====CUSTOMER TICKET INVOICE NUMBER===== -->
      <input v-model="form.ct_invoice_no" type="text" name="ct_invoice_no" class="form-control">

      <!-- =====CUSTOMER TICKET INVOICE ITEMS===== -->
      <tbody>
        <tr v-for="(ctInvoiceItem, key) in form.ctInvoiceItems" :key="key">
          <!--Passenger Name-->
          <td>
            <input v-model="ctInvoiceItem.ct_passenger_name" size="40" type="text" name="ct_passenger_name" class="table-control form-control">
          </td>

          <!--Ticket No.-->
          <td>
            <input v-model="ctInvoiceItem.ct_ticket_no" size="24" type="text" name="ct_ticket_no" class="table-control form-control">
          </td>

          <!--Flight No.-->
          <td>
            <input v-model="ctInvoiceItem.ct_flight_no" size="7" type="text" name="ct_flight_no" class="table-control form-control">
          </td>
      </tbody>

My @change="getRecord" method:

getRecord: function(e) {
  axios
    .get("api/ticket-invoice/fetch/" + this.selectedTicketInvoiceId)
    .then(({
      data
    }) => {
      console.log(data);
      this.form = data; // assumes the data keys maps directly to the form properties!!
    })
    .catch(error => {
      console.log(error.response);
    });
}

Route:

Route::get('ticket-invoice/fetch/{ticket_invoice}', 'API\TicketInvoiceController@fetch')->name('ticket-invoice.fetch');

My fetch(){} method:

public function fetch($id) {
  $ticketInvoices = TicketInvoice::findOrFail($id);

  return response() ->json([
    'id' => '',
    'customer_id' => '',
    'ct_invoice_no' => $ticketInvoices->ticket_invoice_no,
    'ct_invoice_date' => $ticketInvoices->ticket_invoice_date,
    'ct_invoice_fares_total' => $ticketInvoices->ticket_invoice_fares_total,
    'ct_invoice_grand_total' => $ticketInvoices->ticket_invoice_grand_total,
    'ctInvoiceItems' => $ticketInvoices->ticketInvoiceItems->map(function($item) {
      return [
        // get the relevant $item->property for each key below
        'id' => "",
        'ct_invoice_id' => "",
        'ct_passenger_name' => $item->passenger_name,
        'ct_fares' => $item->fares,
        'ct_sub_total' => $item->sub_total
      ];
    }) ->all()
  ]);
}

My data() in Vue Component:

data() {
  return {
    editmode: true,
    selectedTicketInvoiceId: false,
    ticketInvoices: {},
    ctInvoices: {},
    customers: null,
    form: new Form({
      id: "",
      customer_id: "",
      ct_invoice_no: "",
      ct_invoice_date: "",
      ct_invoice_fares_total: 0,
      ct_invoice_grand_total: 0,

      ctInvoiceItems: [{
        id: "",
        ct_invoice_id: "",
        ct_passenger_name: "",
        ct_fares: 0,
        ct_sub_total: 0
      }]
    })
  };
},

When I select an option, I can see the specific data filling in my Vue Component's respective id, but the input fields are not being populated with that data. Therefore, I am unable to make changes and eventually store the updated information in the database as a CustomerInvoice.

Vue Dev Tool BEFORE SELECTING OPTION:

Vue Dev Tool AFTER SELECTING OPTION:

BUT NOT FILLING FIELDS:

Answer №1

Although I may not be well-versed in Laravel 5.7 or vue, the fundamental concept remains consistent.

1- To illustrate my approach, I will create a PHP file that queries the database with a select * statement and outputs the result in JSON format.
2- Subsequently, I will utilize ajax or fetch to retrieve this JSON data from the PHP file, which can then be used in the corresponding JavaScript file.
3 - A function will be implemented such that upon clicking a dropdown option, data will be fetched through AJAX requests, updating the dropdown options accordingly.

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

Angular utilizes ZoneAwarePromise rather than a plain String output

I expected the giver code to return a string, but it is returning ZoneAwarePromise. Within the service: getCoveredPeriod() { let loanDetails = this.getLoanDetails().toPromise(); loanDetails.then((res: any) => { const coveredPeriodStart ...

Ways to Update/Overwrite Current Information in HTML Using Vue

I have experience creating templates for Vue components using JavaScript. Imagine I have HTML that is generated on the server side with a language called UTL: <table> <tr> <td>[% example_var; %]</td> <t ...

Using AJAX to dynamically load content from a Wordpress website

Currently, I have been experimenting with an AJAX tutorial in an attempt to dynamically load my WordPress post content onto the homepage of my website without triggering a full page reload. However, for some reason, when clicking on the links, instead of ...

Encountering issue: Unrecognized parameter "id" in the "user" field of type "Query" [GraphQL, Relay, React]

We are currently setting up a query in relay. Our user database is structured like this: function User(id, name, description) { this.id = id.toString() this.name = name this.description = description } var users = [new User(1, 'abc', &a ...

Make sure to wait for the completion of the ajax request before proceeding with the continuation of the

Currently, I am utilizing jQuery ajax to validate a registration form. Below is the code snippet I am using: $("input.register_input").each(function() { name= this.name; $(".ono#"+name).html("<img src=&apo ...

Retrieving information from various datasets through inquiry

First Model const mongoose = require("mongoose"); const finalApprovalSchema = mongoose.Schema({ formId: String, designApproval: String, rejectionReason: String, date: { type: Date, default: Date.now, }, }); const FinalApproval ...

Error encountered when attempting to upload PHP file using an AJAX request

This is my HTML form validated by PHP with AJAX request. However, after submission, I encounter the following error: Notice: Undefined index: img in D:\Software Installed\xampp\htdocs\wix\users\insert_galary.php on line 12 ...

What is causing the list to not populate in this code snippet?

How can I populate file paths in a list of strings List<string> img = new List<string>(); when files are posted by the client using dropzone js? The files upload successfully but the list remains empty. Any suggestions on how to resolve this ...

Achieving consistent scroll position when utilizing the history.js library to navigate back with the click of a button

I need help implementing a feature that allows users to return to the same position on a webpage when clicking the back button. A common example is on ecommerce sites where if you scroll down, click on a product, then go back, you should be taken back to t ...

Transferring data from the server side using ejs to Ajax

I have designed a table that showcases data fetched from the server side for administrator approval. https://i.stack.imgur.com/mzDVo.png In my project, I am utilizing MongoDB, NodeJS, and Express with an EJS view. However, I stumbled upon an issue while ...

jquery makes it easy to create interactive hide and show effects

The main concept is to display the element upon clicking and hide it when there is any mouse click event. Below is the HTML code I'm using: <ul> <li> <span class="name">Author 1</span> <span class="affiliation"&g ...

ajax clock encounters net::ERR_INSUFFICIENT_RESOURCES error

I recently set up an ajax php clock, but I keep encountering numerous net::ERR_INSUFFICIENT_RESOURCES errors in my console. Can anyone shed some light on why this might be happening? Below is the code responsible for calling out the clock function: $(docu ...

Using JavaScript in PHP files to create a box shadow effect while scrolling may not produce the desired result

Issue at hand : My JavaScript is not functioning properly in my .php files CSS not applying while scrolling *CSS Files are named "var.css" #kepala { padding: 10px; top: 0px; left: 0px; right: 0px; position: fixed; background - c ...

Sequelize cannot locate the specified column in the database

click here for image description I encountered an issue where a column was not recognized after migrating with sequelize-cli. Even though all the columns are defined in the migration file, this error keeps appearing. Additionally, when trying to create a ...

Using DB::raw('The MAX function provides values ranging from 1 to 9 only)

I am encountering an issue where a specific function is only returning values between 1 and 9, even though I have a column called proformnumber with numbers ranging from 1 to 10. Strangely, the function returns 9 instead of the expected result. Interesting ...

Proper approach for mapping JSON data to a table using the Fetch API in a React.js application

Struggling to map some elements of JSON to a Table in Customers.jsx, but can't seem to figure out the correct way. How do I properly insert my Fetch Method into Customers.jsx? Specifically managing the renderBody part and the bodyData={/The JsonData/} ...

What methods can I use to ensure that a user's credentials are not shown in the URL?

My NextJS application sometimes behaves unexpectedly. Whenever I have a slow connection and the initial load time of the site is longer than usual, after trying to log in to the application, the credentials I entered are displayed in the URL. This happens ...

How can the value attribute be obtained from the click class?

$(document).on('click','.edit', function(){ var appid = $(this).getAttribute('value'); I am trying to figure out how to save the value of the "value" attribute for an image with the edit class. Can anyone help me with thi ...

Using jQuery to remove the td element from an HTML table

Hello everyone, I have a query. I am trying to remove a specific td from a table using JavaScript, but the remove() function is not working. Here is my code: $('.btnEliminarLicencia').off('click'); $('.btnEliminarLicencia&apo ...

problem decoding json data from external server

I have a custom Grease Monkey script that is responsible for collecting data from a game and sending it to my server for tracking our team's progress. This process involves multiple Ajax requests between the GM script and the game, followed by sending ...