Troubleshooting Issue: Failure of Ajax Script to Display Saved Data in Edit Function

Whenever I clicked on the Edit icon in the action column of my data tables, the saved data did not display as expected. I noticed that this issue was only occurring for file input types, while it worked properly for text input types.

In the Blade file

Add Form

<form class="form" id="add" enctype="multipart/form-data">
    Name<input type="text" class="form-control" name="name" required>
    file<input type="file" class="form-control" name="path" required>
</form>

Update form

<form class="form" id="Update" enctype="multipart/form-data">
        Name<input type="text" class="form-control" name="name" id= "editname"  required>
        file<input type="file" class="form-control" name="path" id= "editpath" required>
    </form>

To allow users to edit data in my data tables by clicking on the Edit icon under the Action Column

<div class="responsive">
     <table id="myFiles">
        <thead>
           <tr>
                 <th>File</th>
                  <th>Action</th>

                   </tr>
                       </thead>
                        <tbody>
                           @foreach($files as $f)
                              <tr>
                                <td><a href="{{ asset($f->path) }}">{{ $f->name }}</a></td>
                                                    
                               <td>
                                 <div class="topButtons">
                                   <form class="formEditDataF">
                                    <input type="hidden" name="upload_id" value="{{ $f->id }}">
                                 <button class="btn btn-info btn-sm" type="submit"><i class="bx bx-edit-alt font-medium-1"></i></button>
                                  </form>
                              </div>
                           </td>
                        </tr>
                     @endforeach
                  </tbody>
         </table>
     </div> `

For the Script file related to Edit

$('#myFiles').on('submit', '.formEditDataF', function(event){
        event.preventDefault();
        var formData = $(this).serializeArray();
        $.ajax({
            type: 'GET',
            url: "{{ route('getfile') }}",
            processData:false,
            data: formData
        }).done(function(response) {
            $('#edit_file_id').val(response.id);
            $('#editname').val(response.name);
            $('#editpath').val(response.path);


            $('#myModal2').modal('show');
    
        }).fail(function(data) {
            swal({
                type: "error",
                title: "Oops. An Error Occured",
                text: "Please try again"
            });
        });
    });

Script for Update

In my Controller

public function getFile(Request $request) {
    $data = DB::table('file.file')->where([['id', $request->file_id]])->first();
 
    return response()->json($data);
}

Answer №1

The code snippet specifies the HTML as having an id of editpath, but it is referenced in your JavaScript as $('#edit_path'). The same inconsistency exists for id="editname" and $('#edit_name').

It is suggested to use id="editpath" and reference it as $('#editpath') accordingly.

UPDATE: Identifying the issue:

$('#editpath').val(response.path);

You are trying to directly assign a value to the file input, which is considered invalid. To display the image, you need to utilize another element.

Please refer to the example snippet below for guidance on how to achieve this.

image = new Image();
image.src = 'https://cdn4.buysellads.net/uu/1/102396/1635865698-headsways.png'; //replace this with your image path
$(image).attr('id', 'image');
$(image).attr('height', '200px');
$(image).attr('width', '200px');

image.onload = function() {
    $('#img-cont').append(image);
}

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();  
    reader.onload = function (e) {
      $('#image').attr('src', e.target.result);
    };
    reader.readAsDataURL(input.files[0]);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="img-cont"></div>

FILE<input type="file" onchange="readURL(this)">

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

Verify and send form without reloading the page

I am currently facing an issue with jQuery validation and ajax form processing. My goal is to prevent a page refresh by using ajax, but I am struggling to determine the appropriate placement for the ajax code within the validation function in order to ensu ...

Creating a buffered transformation stream in practice

In my current project, I am exploring the use of the latest Node.js streams API to create a stream that buffers a specific amount of data. This buffer should be automatically flushed when the stream is piped to another stream or when it emits `readable` ev ...

What is the source of the compiler options in tsconfig.json?

Currently utilizing Typescript in NestJs, I have incorporated various packages. However, the specific package responsible for altering these settings remains unknown to me: "checkJs": false, "skipLibCheck": true Is there a method to ...

Error loading 'protobuf.js' while retrieving Firestore document

When trying to run a basic node file with Firebase and Firestore, the following code was used: const firebase = require("firebase"); const http = require('http') require("firebase/firestore"); firebase.initializeApp({ apiKey: '...' ...

Tips for extracting values from a PHP array using JavaScript

Assuming we have a PHP array named $decoded: $decoded = array( 'method' => 'getFile', 'number' => '12345' ); The data from this array will be passed to a JavaScript function called get(params). funct ...

Issue with Laravel - JavaScript not functioning properly following the passage of a parameter through the route

I am currently working on a website that will display search results from various e-marketplaces. Everything was going smoothly with the JavaScript implementation until I attempted to pass parameters through the route. Once I did that, the results stopped ...

Formik's handleSubmit function seems to be being overlooked and not executed as

I've encountered an issue while trying to validate a form before submission using formik and yup validation. The form is divided into two parts, where the first part needs to be validated before moving on to the second part. I set a state handleShow(t ...

How to simultaneously play a sound and display an alert message using JavaScript

My JavaScript code attempts to play a sound and then display an alert, but the alert always shows up first. When I click 'ok', the sound plays. How can I make it so that the sound plays before the alert appears? <script> function play() { ...

What is the proper way to type a collection and put it into action?

I am looking for a way to create an object that mimics a set. Specifically, I want the transaction id to act as a key and the transaction details as the value. To achieve this, I created the following: type TransactionDetail = { [key: TransactionId]: Tra ...

express node struggling to locate bootstrap.js file

I am working with a specific directory structure within my project: projectName | -.sencha/ | - app/ | - view | - controller | - store | - saas | - server/ | -server.js ...

Refining an array data table within a nested component

Transitioning my old PHP/jquery single-page applications to VueJS/Webpack has been a journey I'm undertaking to familiarize myself with the latter technology. It involves converting a simple table that pulls data from a JSON API and incorporates filte ...

Exploring Ajax Testing in React JS with Mocha and Sinon

Is there a way to test an ajax call in a React application? When a click event triggers a method: _search = () => { AppActions.search({ url: this.props.url, queryValue: query }) } This method then calls another method on a store ...

As I embark on building my web application using next.js, I begin by importing firebase from the "firebase" package. Unfortunately, a particular error unexpectedly surfaces in the terminal

I am currently developing a next.js web application and I have decided to utilize firebase for both database management and authentication. However, when attempting to import firebase in a specific file, I encountered the following error: Error - ./firebas ...

Using AngularJS to Bind HTML Safely: Understanding ngBindHtml and 'unsafe' HTML

I am facing an issue with displaying HTML content containing inline styling in my view. The code I currently have is: <div ng-repeat="snippet in snippets"> <div ng-bind-html="snippet.content"></div> </div> Unfortunately, all of ...

An unassigned variable automatically sets the disabled attribute to true on an input field

Is this behavior a problem or normal? Consider the following form structure: <form #form="ngForm" > <div> <label>field1</label> <input type="text" name="field1" [(ngModel)]="mainVar" [disabled]="someVar" /> ...

The alias for the last item in a nested ng-repeat loop will consistently evaluate to true

Within my code, I am utilizing two nested ng-repeat functions and I am looking to change the $last variable to something different for each level - let's say outerLast and innerLast. I attempted to achieve this by using ng-init="outerLast= $last" and ...

Continuous addition of Node structures in a tree

I am attempting to append a node tree to the DOM that has been created using createHTMLDocument. Originally, I approached it like this: (doc represents the node tree) while(doc.head.children.length > 0){ iframewin.document.head.appendChild(doc. ...

The issue with Framer motion's whileInView is that it does not animate the element when it is within the viewport in Next.js

In my current Next.js 14 project with the App Router, I decided to play around with animations using Framer Motion. One specific feature I wanted to implement was animating text elements into view as they enter the viewport. The idea is for the text to gra ...

What is the best way to retrieve the scope of ng-repeat from another directive located on the same element as ng-repeat?

Is it possible to access a property from the ng-repeat scope in another directive within the same element as the ng-repeat directive? For instance, I would like to be able to use the child.class property in this scenario: <div ng-class="{{ child.class ...

Encountering issues with fs.writeFile function in a freshly set up Vue project

After initializing a new Vue project with vue cli, I encountered an error when attempting to write files in the main.js file. Below is the code snippet that caused the issue: const fs = require('fs'); // Data to be written to the file. let dat ...