Search code examples
javascriptjquerypapaparse

Using papaparse after loading script dynamically


ORIGINAL

I'm loading Papaparse on the fly in my Javascript app like this:

$.getScript('path/to/papaparse.js',function() {
    //below script
});

Then I get the file for parsing like this.

$('#csv_file').parse({
    delimiter: ",",
    worker: true,
    skipEmptyLines: true,
    before: function(file,inputElement) {
        console.log(file);
        console.log(inputElement);
    },
    error: function(err, file, inputElement, reason) {
        console.log('error');
        console.log(err);
        console.log(file);
        console.log(inputElement);
        console.log(reason);
    },
    step: function(results,parser) {
        console.log(results);
        console.log(parser);
    },
    complete: function(results,file) {
        console.log(results);
        console.log(file);
    }
});

None of my console.log's in the step-callback fires, but they print from the before- and complete-callbacks.

before:
    file:
        File {}
        lastModified: 1437396586321
        lastModifiedDate: Mon Jul 20 2015 14:49:46 GMT+0200 (South Africa Standard Time)
        name: "normal.csv"
        size: 254743
        type: "application/vnd.ms-excel"
        webkitRelativePath: ""
    inputElement:
        <input type="file" name="csv_file" id="csv_file" class="form-control half">
complete:
    results: undefined
    file: undefined

Can someone tell me why a) it's not returning anything in my step-callback and b) why it's returning undefined in my complete-callback?

UPDATE

I have added the SCRIPT_PATH as suggested in the comments like so:

$.getScript('path/to/papaparse.js',function() {
    Papa.SCRIPT_PATH = config.basedir + '/app/lib/papaparse/papaparse.min.js';
    // Papa script
});

And changed my before to this:

before: function(file,inputElement) {
    console.log(file);
    console.log(inputElement);
    return { action : 'continue' }
},

However still get undefined.


Solution

  • So the solution was quite simple. complete: function(results,file) and step:function(results,parser) needs to be in the config file as this is per file config.

    Obviously step wouldn't run if it is not defined per file.