Utilize Laravel 8 and Vue Js to dynamically showcase retrieved data in input fields

I am facing a challenge with my Laravel 8 registration form using Vue js. Before submitting the form, I need to verify if the referring user exists in the database. If the user is found, I want to dynamically display their full name in an input field upon @change event.

Below is the Vue component structure:

<template>
    <div>
    <h2>TESTING</h2>    

    <form @submit.prevent="submit" > ;
            <input type="text" class="form-control" v-model="form.ucode" @change="getUser()">
            <input type="text" class="form-control" v-model="form.uname">
    </form>
    </div>
    
    
</template>

<script>
export default {
    data: function(){
        return{
            form:{
                ucode: "",
                uname: "",
            }, 
            
        }
    },
    methods:{
        getUser(){
           axios.get('api/checkUser?ucode=' + this.form.ucode).then(res=>{
               this.form.uname = res.data.first_name
           })
        }   
    }
}

This is how my ResellerController and API route are set up:

Route::get('/checkUser', [ResellerController::class, 'show']); 

public function show()
    {
        $ucode = request('ucode');
        $user = DB::table('resellers')->where('username', $ucode)->select('id', 'first_name')->get();
        return response()->json($user); 
    }

The controller seems to be working fine as it returns the correct JSON data:

[{"id":1,"first_name":"William Hardiev"}]

However, during testing, the 'uname' field remains undefined:

form:Object
   ucode:"williambola_05"
   uname:undefined

If anyone can provide some assistance with this issue, I would greatly appreciate it!

Answer №1

The issue you are encountering is with the JSON response received from the server. The server is sending a JSON Array, while your JavaScript code is expecting a JSON object.

To handle this situation, you can make the following adjustments:

<template>
  <div>
    <h2>TESTING</h2>

    <form @submit.prevent="submit">
      <input
        type="text"
        class="form-control"
        v-model="form.ucode"
        @change="getUser()"
      />
      <input type="text" class="form-control" v-model="form.uname" />
    </form>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data: function() {
    return {
      form: {
        ucode: "",
        uname: ""
      }
    };
  },
  methods: {
    getUser() {
      axios.get("api/checkUser/?ucode=" + this.form.ucode).then(res => {
        this.form.uname = res.data[0].first_name;
      });
    }
  }
};
</script>

Alternatively, you can modify the server query to return a single JSON object instead of an array. This change should allow your JavaScript code to function correctly:

$user = DB::table('resellers')
->where('username', $ucode)
->select('id', 'first_name')
->first();

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

Is Ember CLI experiencing issues due to the latest Ember Data update?

Greetings! I am a beginner with Ember and recently encountered some warnings after upgrading to the latest version of Ember Data: Update: I have two identical versions of my app, one built without ember-cli and the other with ember cli. Both applications ...

Transmit information via ajax and receive responses in json format

Looking to send a string and receive JSON format in return. The current method is functional but lacks the ability to return JSON code. $.ajax({ url: "getFeed.php", type: "post", data: myString }); Attempts to retrieve JSON string result in ...

Passing an event from Electron's IPC renderer to Vuex

Greetings, fellow developers! I'm currently working on an app that involves multiple windows. My App is built using Vue + Electron technology stack. One of the key features I am trying to implement is triggering actions in Electron to open a popup, fo ...

Best method for reverting react-native to previous version

Here's the dilemma I'm facing: I had a functional version of a react-native project that was running smoothly and committed to my git repository. Deciding to upgrade from react-native 0.26.3 to 0.28 led me into a tangled web of dependencies, so ...

Tips for incorporating theme colors in the "color" prop when employing MaterialUI components

Trying to utilize the colors from my Mui palette as values for the color property in this way: For example: <Tabs indicatorColor="primary.mainGradient" > <Tab /> </Tabs> However, this approach does not seem to wo ...

Ensure that a div with fluid width remains consistently centered within another div

I have a bunch of boxes filled with content. The number of boxes in each row varies depending on the width of the browser window. Is there a way to ensure that all the boxes are always horizontally centered on the page? For guidance, you can check out th ...

The function toDataURL() in Canvas is storing images in low resolution

I created a unique polygonal background generator using HTML5 canvas which can be found at the following link: http://codepen.io/rfalor/pen/LhinJ Here is the important part of the code: var canvas = document.getElementById("canvas"); var ctx = c ...

Vue-Router does not currently have built-in support for the dynamic import() function

Encountering an issue with the code below indicating "unexpected token import": const Router = new VueRouter({ routes: [ { path: '', component: () => import('pages/landing/landing') } ] }) A solution that is currently ...

Decoding deeply nested JSON data using JavaScript

After browsing through countless threads on the topic, I have yet to find a solution. I successfully parsed a JSON response that looks like this: { "1": { "id": "1", "name": "Fruit", . . . "entities": { ...

Update the WooCommerce shopping cart page automatically upon product removal

After trying to solve the issue of refreshing the cart page in WooCommerce when a product is removed, I came across this helpful question on Stack Overflow: Refresh the page after product remove from cart Woocommerce. Following the provided code snippet th ...

Observing the completion of a subscriber function

Is there a more streamlined way to determine if the subscriber has finished executing or return something and catch it up-stream? Consider the following code snippets: this._subscriptions.push(this._client .getCommandStream(this._command) // R ...

Restangular: Avoiding empty parameter being passed

In my AngularJS application using RestAngular, I have the following controller method: $scope.findFriend = function (name, type, limit) { return FriendSearch.getList({ name: name, type: type, limit: limit ...

Fill the angular ui-bootstrap popover with content

Can anyone help me with populating an angular ui bootstrap popover? My goal is to populate the popover with a collection of actor names. Below is the code snippet: <div class="container" ng-if="radioModel=='Search for Actor'"> <p> ...

Obtain the actual file path from a JSON response

I have set up a local express server to serve a JSON file, but I am facing an issue with displaying image files located in a local folder. The image paths are included in the JSON object that I want to display in my DOM. However, the response I receive inc ...

Retrieving Information from Ajax Call Using Python

I am struggling to figure out how to retrieve data from an Ajax request in my JavaScript code within a Python Flask application. The Ajax request I am working with does not involve jQuery. I have attempted using request.form.get() and request.get_json() i ...

Attempting to retrieve XML/JSON

I am struggling with extracting the first 15 words from a file using the API. I have attempted to do it with both XML and JSON, but keep encountering this error: XMLHttpRequest cannot load No 'Access-Control-Allow-Origin' header is present on th ...

Javascript: A guide on passing an object through multiple nested functions

Hey fellow developers, I'm facing a challenge in my code and seeking advice from the experts out there. I'm attempting to retrieve JSON data from a specific URL, as shown below, and utilize it in a React component outside of the getWeather() fun ...

Understanding the order in which Laravel matches routes is essential to properly configure

Scenario 1: web.php: Route::get('foo/{id}', function () { return 'Route 1'; }); Route::get('foo/bar', function () { return 'Route 2'; }); Route::get('foo/bar', function () { return 'Route ...

Modify the website address and show the dynamic content using AJAX

$(function(){ $("a[rel='tab']").click(function(e){ //capture the URL of the link clicked pageurl = $(this).attr('href'); $("#Content").fadeOut(800); setTimeout(function(){ $.ajax({url:pageurl+'?rel=tab&apo ...

Guide to Appending "Z" to a Date String Using Moment.js in JavaScript and Node.js

I am struggling to format my date to include the "Z" letter at the end. Despite numerous attempts, I have been unsuccessful. The desired format is "YYYY-MM-DDT00:00:00.000Z," but currently it does not include the Z How can I add the Z using moment? It&ap ...