How do I send data from Plain Old Javascript to Flask and get CSV data back using XMLHTTPRequest?

Viewed 471

I am stuck on an issue. I am hoping to send data back to my Flask backend using Plain Old Javascript's XMLHTTPRequest object. I hope to get CSV data in String format back.

function ajax_request() {
  const request = new XMLHttpRequest();
  let csrf_token = '{{ csrf_token() }}';

  let json_data = {
    'data' :[]
  };
  json_data['data'].push(data);


  // Define what happens on successful data submission
  request.addEventListener('load', function(event) {
     console.log("This Worked");
   });

  // Define what happens in case of error
  request.addEventListener('error', function(event) {
    alert('Error: AJAX request failed.');
    console.log(request.responseText);
  } );

  // Open our request and set the headers.
  request.open("POST", "/my-route", true);
  request.setRequestHeader("X-CSRFToken", csrf_token);
  // Add the required HTTP header for form data POST requests
  request.setRequestHeader('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
  request.send(json_data);
}

This seems fair enough. I am not sure whether I can send json with the x-www-form-urlencoded format. I might need json instead but am unsure if that then means the response needs to be json, which is not what I want. I keep trying to play around with this and getting nowhere

My app.py is

@dashboard_blueprint.route('/my-route', methods=["GET", "POST"])
def my_page():
    # If the user is changing the variables / giving us data
    if request.method == "POST":
        print(request.form)
        json_data = request.form.get('data')
        # parse on json data
        csv_data = ....
        return csv_data
    else:
        print(form.errors)

I tried request.json, request.data and some other combinations. What is odd is that I can get it to work when I do not pass any variables to get the new CSV data but just make the request for CSV data without any variables. So I seem quite stuck. Any advice is appreciated!

0 Answers
Related