0

I am trying to create a CSV file in JS using my code table2csv. Then I want to send it to flask using an ajax request and return it back again to the client.

But as I try to send the file to server it returns the error that ajax can't find my file.

I used console.log to check if my file is created and it is. I am stuck and don't know what to do anymore, since I am pretty new to ajax requests so any help would be great.

This is my JS part and what I am doing currently:

//On Update click renders table to csv, activates the be_filter and reopens it in the filtered_file.html
var isClicked;
jQuery("#update").on('click', function(){
    var response = confirm('Are you sure you want to UPDATE rows ?');
    if(response == true){
        isClicked = $('#my_id').table2csv();
        $.ajax({
            type:'POST',
            url:"{{url_for('update_file')}}",
            data: {'data': isClicked},
            success: function(result){
                console.log(result);
            },
            error: function(error){
                console.log(JSON.stringify(error));
            }
        });event.preventDefault();
         //window.location.href='/update_file';
    }else{
        return false;
    }
});

And the flask call:

@app.route('/update_file', methods=['GET', 'POST'])
@login_required
def update_file():
    '''Opens the filtered_file page but with updated file'''
    clicked = None
    if request.method == 'POST':
        clicked = request.form['data']
        file_to_filter = pd.read_csv(clicked, sep=';', engine='python', encoding='utf_8_sig')
        table1 = update_csv(file_to_filter)
        table2 = table1.to_html(classes='my_class" id = "my_id')
        return render_template('3_filtered_file.html', data=table2)

EDIT: console.log() for the error message :

POST http://127.0.0.1:5000/update_file 500 (INTERNAL SERVER ERROR)


{"readyState":4,"responseText":"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n  \"http://www.w3.org/TR/html4/loose.dtd\">\n<html>\n  <head>\n    <title>FileNotFoundError: [Errno 2] No such file or directory: '&quot;Auftragsdatum&quot;,&quot;OrderNo&quot;,&quot;ReferenceOrder&quot;,&quot;Pos&quot;,&quot;Quantity&quot;,&quot;ArtNo&quot;,&quot;ManufactureNo&quot;,&quot;ProductName&quot;,&quot;ReferencePosition&quot;,&quot;NetPerPiece&quot;,&quot;InvoiceNo&quot;,&quot;DeliveryNoteNo&quot;,&quot;SerialNumbers&quot;,&quot;Manufacturer&quot;,&quot;CI&quot;,&quot;Type&quot;,&quot;Import_ID&quot;,&quot;State&quot;,&quot;Supplier&quot;,&quot;NetPerPieceSale&quot;,&quot;OU&quot;,&quot;Modified_Date&quot;,&quot;Added_by&quot;,&quot;Modified_by&quot;,&quot;isSupplier&quot;,&quot;isManufacturer&quot;\\n&quot;01.04.2019&quot;,&quot;7027856072&quot;,&quot;a&quot;,&quot;100&quot;,&quot;1&quot;,&quot;2099882&quot;,&quot;GS1900-24HP-EU0101F&quot;,&quot;ZYXEL GS1900-24HP 24P GbE L2 PoE Switch&quot;,&quot;CLINO&quot;,&quot;251,09&quot;,&quot;950347427&quot;,&quot;6054042579&quot;,&quot;S182L37002129&quot;,&quot;ZYXEL&quot;,&quot;sel&quot;,&quot;&quot;,&quot;&quot;,&quot;716&quot;,&quot;ALSO&quot;,&quot;&quot;,&quot;OU00100&quot;,&quot;11-11-2019 09:58&quot;,&quot;admin&quot;,&quot;&quot;,&quot;&quot;,&quot;BPT07939&quot;\\n&quot;01.04.2019&quot;,&quot;7027856072&quot;,&quot;bg&quot;,&quot;200&quot;,&quot;1&quot;,&quot;3074862&quot;,&quot;EAP225 V3&quot;,&quot;TP-LINK AC1350 WLAN Dual Band Gigabit AP&quot;,&quot;CLINO&quot;,&quot;64,56&quot;,&quot;950347427&quot;,&quot;6054042579&quot;,&quot;218B410001725&quot;,&quot;TP-LINK&quot;,&quot;sel&quot;,&quot;&quot;,&quot;&quot;,&quot;716&quot;,&quot;ALSO&quot;,&quot;&quot;,&quot;OU00100&quot;,&quot;11-11-2019 09:58&quot;,&quot;admin&quot;,&quot;&quot;,&quot;&quot;,&quot;BPT07134&quot;\\n&quot;01.04.2019&quot;,&quot;7027856072&quot;,&quot;cd&quot;,&quot;300&quot;,&quot;1&quot;,&quot;7003581&quot;,&quot;&quot;,&quot;Mautgebühr&quot;,&quot;nan&quot;,&quot;2,09&quot;,&quot;950347427&quot;,&quot;6054042579&quot;,&quot;&quot;,&quot;&quot;,&quot;sel&quot;,&quot;&quot;,&quot;&quot;,&quot;716&quot;,&quot;ALSO&quot;,&quot;&quot;,&quot;sel&quot;,&quot;11-11-2019 ...

EDIT 2 ** this is my code for **table2csv:

(function ($) {
const _trim_text = (text) => {
    return text.trim();
};
const _quote_text = (text) => {
    return '"' + text + '"';
};

function convert(tb){
    let output = "";
    let lines = [];

    $(tb).find('thead>tr').each(function () {
        let line = [];
        $(this).find('th:not(th:eq(0))').each(function () { 
            line.push(_quote_text(_trim_text($(this).text())));
        });
        lines.push(line.splice(0).toString());
    })

    $(tb).find('tbody>tr').each(function () {
        let line = [];
        $(this).find('td').each(function () {   
            if($(this).find('select').length){
                line.push(_quote_text($(this).find('option:selected').val()));
            }else if($(this).find('input').length){
                line.push(_quote_text($(this).find('input').val()));
            }
            else
            line.push(_quote_text(_trim_text($(this).text())));
        });
        lines.push(line.splice(0).toString());
    })
    output = lines.join('\n');
    return output;
};

$.fn.table2csv =  function () {
    let csv = convert(this);
    //cases = $('#out').append($("<pre>").text(csv));   
    return csv;
};

})(jQuery);

4
  • What is the issue you are facing? Commented Nov 11, 2019 at 9:43
  • can't send the csv file from JS to Flask. POST http://127.0.0.1:5000/update_file 500 (INTERNAL SERVER ERROR) - this is what I get in return. Commented Nov 11, 2019 at 9:45
  • Can you elaborate with internal server error? Can you share the error log? Commented Nov 11, 2019 at 9:46
  • I just added the first part of the error msg to the post Commented Nov 11, 2019 at 9:50

1 Answer 1

1

It seems you are you some jQuery plugin to convert table data to csv. It doesn't actually create file on you disk. When you are making the ajax POST request to server you are sending the form data. On the server side you have clicked = request.form['data'] here clicked is not the file. But your pandas read_csv expects the url or buffer type. You can get around this issue with StringIO.

@app.route('/update_file', methods=['GET', 'POST'])
@login_required
def update_file():
    '''Opens the filtered_file page but with updated file'''
    clicked = None
    if request.method == 'POST':
        clicked = StringIO(request.form['data'])
        file_to_filter = pd.read_csv(clicked, sep=';', engine='python', encoding='utf_8_sig')
        table1 = update_csv(file_to_filter)
        table2 = table1.to_html(classes='my_class" id = "my_id')
        return render_template('3_filtered_file.html', data=table2)
Sign up to request clarification or add additional context in comments.

9 Comments

thanks for your answer but I still get an error msg
What is the error message? Is it still the same error?
{"readyState":4,"responseText":"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n \"http://www.w3.org/TR/html4/loose.dtd\">\n<html>\n <head>\n <title>pandas.errors.ParserError: ';' expected after '&quot;' // - it's not the same error
it stills says : jquery.min.js:4 POST http://127.0.0.1:5000/update_file 500 (INTERNAL SERVER ERROR) but with the additional text in error msg
Can you print the data in clicked and show me that log on server side?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.