Parse the text file to extract its data and display that data in a table using Yii2 framework

Below is the javascript code used in my form:

$('#idOfButton').click(function(){
var id = $('#input').val(); 
    $.get('index.php?r=tbltime/get-file',{ id : id },function(data){
        var data = $.parseJSON(data);
        alert(data);
    });
});

This is the controller code for the view:

public function actionGetFile($id)
{
    $id = file_get_contents($id);
    echo Json::encode($id);

}

The structure of my table in the form view:

<table id="sampleTbl", class="table table-striped table-bordered">
    <thead>
        <tr id="myRow">
            <th>BIB</th>
            <th>Time Start</th>
            <th>Time End</th>
        </tr> 
    </thead>
    <tbody></tbody>
</table>

Content of the text file:

202#00:00:00.000000#00:02:13.045000
764#00:03:12.037300#00:04:12.123000
223#00:04:50.011000#00:05:12.045000

I'm looking to display the content of my text file into the table, however, the alert function to show the file content is not working. Can anyone provide assistance?

Answer №1

It seems that the file_get_contents function is unable to read your file because it is not located at C:\fakepath\dataimport.txt. If you wish to read a file from the D:/ disk, make sure to provide the full path to the file directory like this:

file_get_contents('FULL PATH TO THE FILE DIRECTORY'.$id)
. However, hardcoding values in your script may cause issues when moving the code to a server.

To access a file from the C:\ disk, you can simply copy the file from disk D:\ to C:\fakepath\dataimport.txt.

In your controller, after the line echo Json::encode($id);, add the line Yii::app()->end(); to prevent rendering any view files in that action.

Update

There are three possible scenarios:

First scenario: This scenario involves displaying a file that you are already aware of and have control over. Simply copy the file into your project folder and provide a relative path for the function to read. This method will work even when deploying the project on other servers.

Second scenario: If the file comes from an end user, you must first upload the file using PHP and then send the file content to your Ajax script.

Third scenario: You can use JavaScript to read the file's content and display it in the view. Check out this example:

Answer №2

When your alert appears, what is the response code of the AJAX GET request? If there are any errors, please include them here.

UPDATE: It seems that in the input where you are providing the file name, only the file name itself is present and not the full path to the file. To fix this issue, you need to adjust your action by adding the path prefix to the file_get_contents method:

public function actionGetFile($id)
{
    $fileContent = file_get_contents('D:/'.$id);
    echo Json::encode($fileContent);
    Yii::app()->end();
}

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

Having difficulty extracting information from a Json string stored in the SQL Server database

I need to extract the fileDisplayNames from a specific data set column that contains JSON strings. select id_ref id, JSON_VALUE(cast(data_map as varchar(max)),'$.dataMap."4805".fileDisplayName') Attachments, data_map dataa from action_data wher ...

Issues have arisen with Google Maps functionality following the API integration, resulting in a blank grey

I am experiencing an issue with Google Maps where it is displaying a grey box or sometimes showing nothing/white. I have tried various solutions found online but none of them have worked for me. Does anyone have a solution? I even attempted to change the ...

Ditch the if-else ladder approach and instead, opt for implementing a strategic design

I am currently working on implementing a strategic design pattern. Here is a simple if-else ladder that I have: if(dataKeyinresponse === 'year') { bsd = new Date(moment(new Date(item['key'])).startOf('year&apos ...

What steps should be taken to make mocha utilize the HTTP response?

Every time I make an http call, the function it returns causes my comparison to fail because [Function] is never equal to the value I want. Is there a way to make my assert statement consider the true/false flag within it? # test/helloWorld.js const othe ...

Is there a way to customize the ::selection style using mui createTheme?

I'm looking to globally change the color and background color of ::selection in my app. Can anyone advise on how to achieve this using createTheme()? ...

Retrieving JSON data from PHP using jQuery

I've been struggling with this issue for two whole days now, and I feel like I've hit a dead end in trying to solve it on my own. Here's the situation: I have two pages - one that contains a form with an address field that gets auto-filled ...

Tips for customizing the appearance of a redux-tooltip

After implementing the redux-tooltip from this GitHub repository, I wanted to customize its styling to better align with my application's design. However, I realized that the Tooltip-Component's divs do not have any identifiers or class names, ma ...

The button I have controls two spans with distinct identifiers

When I press the player 1 button, it changes the score for both players. I also attempted to target p2display with querySelector("#p2Display"), but it seems to be recognized as a nodeList rather than an element. var p1button = document.querySelector("# ...

Utilizing Node.js and Node-Postgres: Organizing Database Queries in Models

In order to enhance the efficiency of my code, I am looking to modularize my queries by organizing them into functions with appropriate names for their tasks. Instead of cluttering up the req, res functions (controllers), I aim to encapsulate them in a se ...

The useEffect hook is failing to resolve a promise

I have received a response from an API that I need to display. Here is a snippet of the sample response (relevant fields only): [ { ...other fields, "latitude": "33.5682166", "longitude": "73 ...

How to Integrate a Third Party API with PrestaShop

Currently, I am integrating ERPNext with Prestashop by utilizing the JSON API. For instance, my goal is to transfer transactions and other data from Prestashop to ERPNext every time a client makes a purchase on Prestashop. Essentially, I am looking to imp ...

Implementing auto-suggest functionality in a React-Bootstrap Select component

I am seeking to create a specialized react select component that can search through a constantly updating list pulled from a server api in JSON format. I am currently exploring other options aside from React-select because it is not compatible with my proj ...

Using compressed JSON in Flask's jsonify()

When using Flask, the jsonify() function is a handy tool that generates a JSON object from Python variables: from flask import Flask, jsonify app = Flask(__name__) @app.route("/") def json_hello(): return jsonify({x:x*x for x in range(5)}), 200 if _ ...

I encountered an issue with the onclick event in JavaScript

I have been struggling with an issue for some time now and I just can't seem to figure out what I am doing wrong. Here's the problem - when I click on a link on my website, a calculator should pop up. Then, when I click the off button on the calc ...

Is it possible to execute an onClick event and a <NavLink to="/Scooters"> simultaneously?

Is it feasible in React to both filter my database and redirect to another route upon clicking the search button? I am currently employing <BrowserRouter>. It would also be advantageous if this redirection could occur directly from the onClick even ...

What is the best way to ensure that all components within a Container automatically inherit its calculated width?

Check out my tab panel setup on Sencha fiddle. The buttons are dynamically added to a tabs container with a layout of hbox within a vbox. The width of the tabs container is determined by the flex property. I attempted to set each button's width to &a ...

"Learn the steps to toggle a sub menu using an onclick event and how to hide it using another

I created a sidebar navigation that displays submenus on mouseover, but I want them to open on click and close when clicking on the same tab. Please take a look at my code on this CodePen link. Thank you. <nav class="navigation"> <ul class="mai ...

Identify the location of the mouse and activate a specific function based

Tracking the x-coordinate of the mouse is crucial in this scenario. When the mouse approaches a specific threshold (250px) towards the left edge of the window, it should trigger the function "openNav." The function should close when the mouse moves away fr ...

Searching for key names in JSON using PHP

Here is the JSON Data I am working with: "12-305":[{"catid":"12","fname":"SALADS","ord":"0","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"6","Valid":"0","Phone":"1","Web":"1","ovalue":"All Salads","id":"305","icon":"","price": ...

How to eliminate looping animations with jQuery

While looping through items, I am encountering an issue where an animation triggers when the loop returns to the first div. I simply need a way to switch between divs without any animations on a set interval. $(document).ready(function () { function s ...