duney
duney

Reputation: 157

Read text from a txt file using javascript and display in a bootstrap modal dialog (via knockout binding)

I'm trying to write a function which will read data from a .txt file (which for the moment, is residing in the root directory of website) and then display it in a modal dialog box. I feel like I'm almost there as the file is being recognised when I debug the the modal, but it doesn't display anything:

HTML Button:

<button class="btn btn-mini btn-success" 
        data-toggle="modal" 
        data-target="#openLog" 
        data-bind="click: GetLog">
        Start
</button>

Knockout.js vm:

GetLog = function () {
    dataServices.getLog();
}

HTML Modal:

<div class="modal fade" id="openLog" tabindex="-1" role="dialog" aria-labelledby="openLogLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="openLogLabel">Today's Log</h4>
            </div>
            <div class="modal-body" id="logText">
                <script>
                    window.onload = function () {
                        dataServices.getLog();
                    }
                </script>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

Javascript (dataServices.js)

getLog = function() {
    return $.ajax({
        url: 'Text.txt',
        dataType: 'text',
        success: function (text) {
            getLog.logContents = text;
            $("#logText").text(text);
        }
    })
};

The Javascript picks up the filename ok, but returns no text so the modal popup is just blank. Can anyone please assist regarding where I'm going wrong with this? thanks.

Upvotes: 1

Views: 2237

Answers (1)

Jonas Sciangula Street
Jonas Sciangula Street

Reputation: 1892

You should use an observable

var vm = {
  observable: ko.observable(''),
  getLog: function() {
      var self = this;
      return $.ajax({
          url: 'Text.txt',
          dataType: 'text',
          success: function (text) {
              self.observable(text);
          }
      })
  }
};
ko.applyBindings(vm);
vm.getLog();

And in the html you should call it...

<div class="modal-body" id="logText">
    <span data-bind="text: observable"></span>
</div>

Upvotes: 1

Related Questions