This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

oskar.villani40843
oskar.villani40843

Hi, I need to load a plain text file from the media folder into an javascript variable (that's important, NOT into the html dom) via an ajax request. This should happen when the page is opened and later via selectbox / button later. An ordinary jQuery ajax call does unfortunately not work, obviously because every call is rederictet to "page does not exist".

Anyone who knows a better solution?

Thanks in advance!

Last updated

oskar.villani40843
oskar.villani40843

Well, had to find the answer by myself. So, here is the how-to for others:

First place some javascript into your js file, that is loaded with the page or layout, like:

// the example file to read
var fName = 'readme';
var fExt = 'txt';

// the variable where the content of the file is to be loaded
var myTargetVar = '';

// now the ajax caller function
// notice that the ajax request is asyncronous
// so any further processing of 'myTargetVar' has either to be
// placed in the success: function, in a callback function,
// or in a predefined function called there 
function loadData(myFileName, myFileExt) {
    $.request('onLoadData', {                    // onLoadData is the name of a php func to call
        data: { fileToLoad: myFileName,          // fileToLoad is the $POST id, myFileName the file to load
                fileExtension: myFileExt },      // same for the file extension. Separated to show how to handle more than one argument ;)
        success: function(data) {
            myTargetVar = data.result;           // here the content of myFile is pushed into your var

            processData(myTargetVar);            // place code or functions for further processing the data here...
        } 
    }
}

// finally call the ajax caller as defined above with the filename and extension as defined at the start
loadData(fname, fExt);

Second place some php code in the Code area of your page (or layout), like:

// the 'onLoadData' is the function called by the js script above
function onLoadData()
{
    // base_path() gives back the path to your file according to the
    // installation of octobercms
    // with 'post(fileToLoad)' you get the ajax argument
    // of course you can post more than one argument

    $pathToFile = base_path('storage/app/media/' . post(fileToLoad) . '.' . post(fileExtension));

    // simple example to get the file content
    // other php processing of the file content can be placed here
    return file_get_contents($pathToFile);
}   

Ok, thats it. Just a simple example, but helpful I hope ;)

Cheers!

1-2 of 2

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.