2

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!

David Frick
  • 641
  • 1
  • 9
  • 25
  • 1
    The content-type set in `XMLHttpRequest` is for what you send from browser not for what you receive. Returning csv is really just text and you would parse that text into array using javascript. There are libraries you can use to parse it or the basics of rolling your own parser is not difficult to research – charlietfl Aug 15 '20 at 21:39
  • I can parse it easy enough. I have that part down. Let me trying changing it to `application/json` – David Frick Aug 15 '20 at 21:43
  • 1
    When I change it to `application/json` I still seem to be getting an empty immutable dict on the backend. – David Frick Aug 15 '20 at 21:45
  • 1
    OK next issue is you can't just pass an object into request.send unless it is a FormData object....if sending json then use JSON.stringify() and use appropriate content-type – charlietfl Aug 15 '20 at 21:46
  • 1
    Side note is using more modern `fetch()` is less work and more robust than using `XMLHttpRequest ` and it is promise based – charlietfl Aug 15 '20 at 21:50
  • Hey thanks for the help. I got it working! What you said led me to here: https://stackoverflow.com/questions/20001229/how-to-get-posted-json-in-flask Is `fetch` in plain old JavaScript? I tend to see it with jquery answers which I do not use. I can not see I like `XMLHTTPRequest` because it just seems so clunky ;/ – David Frick Aug 15 '20 at 21:53
  • 2
    Yes it is a window interface in virtually all modern browsers https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API – charlietfl Aug 15 '20 at 21:55
  • Thanks. Ill check it out! – David Frick Aug 15 '20 at 21:59

0 Answers0