Dan
Dan

Reputation: 1227

Get text file contents using JQuery in an external file

I have an external javascript file that I want to use to collect the contents of a number of text files. JQuery .get() seems the most obvious choice. I can make this work if the JQuery is in the page, but not when the JQuery is in the external file. I'm missing something hugely simple...and I am currently mixing normal javascript with JQuery in the same file which I fear is poor form.

All files I am trying to access are within the same file structure. Currently I have the following in my external .js:

function addPanels() {
    // eventually loop over list of local HTML files
    // and do some stuff with the results...
    fileContents = readHTMLFile();
}

jQuery(function($){
    readHTMLFile = $.get('../html/test.html', function(data) {
        alert('Loaded something');
        return(data);
    });
});

My HTML page contains the following:

<script type="text/javascript">
    $(document).ready(function(){
        addPanels();
    });
</script>

Pretty sure this is a RTFM moment so direction towards the right manual/tutorial would be great!

Dan

Upvotes: 2

Views: 18455

Answers (2)

Code-Source
Code-Source

Reputation: 2243

In your script "readHTMLFile" is not known by function "addPanels", you should put them in same level.

This script should works

<script type="text/javascript">
    (function($){
        var readHTMLFile = function(url){
            var toReturn;
            $.ajax({
                url: url,
                async: false
            }).done(function(data){
                toReturn = data;
            });
            return toReturn;
        };
        $.addPanels = function(url){
            fileContents = readHTMLFile(url);  
        };
     })(jQuery);
</script>

And in your page you can call it like that:

<script type="text/javascript">
    $(document).ready(function(){
        $.addPanels('../test/test.html');
    });
</script>

Upvotes: 4

nekman
nekman

Reputation: 1919

The jQuery.get is a asynchronous function, with a callback that executes when the server returns the requested document. Therefore, you cannot return any data from the method.

function addPanels() {
    // will not work
    fileContents = readHTMLFile();
}

...

readHTMLFile = $.get('../html/test.html', function(data) {
    // will not work
    return(data);
});

This however, will work:

var addPanelCallback = function(html) {
    // append html (or something like that)
    alert(html);
};

var addPanel = function(url) {
   $.get(url, addPanelCallback);
};

addPanel('../html/test1.html');
addPanel('../html/test2.html');

Example: http://jsfiddle.net/FgyHp/

Upvotes: 5

Related Questions