0

Running a webpage and when I click a button, I want an existing image to be replaced without reloading the page, after a servers function is finished creating the new image server side. I am getting a 400 error though, so something is wrong before I can even print the data in routes.py to see what it's passing, meaning something is wrong with my ajax call to my flask routes.py function.

The image:

        <div class="col-6">
            <div class="card">
                <img src="{{ user_image }}" alt="User Image" id="myImage"> 
            </div> 
        </div>

At the end of my html file I have this script as an attempt to replace the existing image:

</body>
<script>
    $(document).ready(function() {
      $('#makeNewImage').click(function(){
        $.ajax({
          type: 'POST',
          url: "{{ url_for('getData') }}",
          headers: {"Content-Type": "application/json"},
          success: function(resp){
            $('myImage').attr('src', "static/img/" + resp);
          }
        });
      });
    });
  </script>
  </html>

In my flask routes.py page:

 @app.route('/getData', methods=['POST'])
 def getData():
     // generate image, save image in /static/img/filename
     return filename

Passing data and everything works when I use my original xhr function, but it isn't auto updating as it's pure JS. I receive the 200 message with this function.

function getResults() {
  let xhr = new XMLHttpRequest();
  let url = "/getData";
  let error = false;
  if (!Array.isArray(myArray) || !myArray.length) {
    alert("No items selected.")
    error = true;
  } else {
  xhr.open("POST", url, true);
  xhr.setRequestHeader("Content-Type", "application/json");
  xhr.onreadystatechange = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        console.log("I see this as an absolute win")
      }
    };
    xhr.onerror = function () {
      console.log("** An error occurred during the transaction");
    };
    param1 = document.getElementById('param1').value
    param2 = document.getElementById('param2').value
    param3 = document.getElementById('param3').value
    let data = JSON.stringify({"myArray": myArray, "param1 ": param1 , "param2 ": param2, "param3": param3});
    xhr.send(data);
    }
}

Anyone know the reason for the 400 error on my new Ajax code attempt?

john stamos
  • 1,054
  • 5
  • 17
  • 36
  • Please enable debug mode on the server itself and post the relevant response code/error and ideally `Traceback` that got generated on the server, if any. – metatoaster Apr 19 '23 at 21:57
  • 127.0.0.1 - - [19/Apr/2023 15:32:30] "POST /getData HTTP/1.1" 400 - – john stamos Apr 19 '23 at 23:18
  • You will need to enable debug mode and include more code in the flask end point as the error lies there, not in your JavaScript code - see [thread](https://stackoverflow.com/questions/14105452/what-is-the-cause-of-the-bad-request-error-when-submitting-form-in-flask-applica) about why 400 Bad Request happens in Flask. – metatoaster Apr 19 '23 at 23:21
  • Copy. How do I turn on debug mode with a local host flask instance? – john stamos Apr 19 '23 at 23:39
  • Searching online or heck here on StackOverflow would have [given you this thread](https://stackoverflow.com/questions/17309889/how-to-debug-a-flask-app) - please search first before asking. – metatoaster Apr 19 '23 at 23:46
  • Obviously I did. While attempting to get more than a 400 line out of debug (never succeeded even though flask startup has * Debug mode: on and * Debugger is active!), I came across someone else with a 400 error, and they were told they were giving a JSON when their flask function expected something else. Well I'm expecting a JSON, giving a JSON so realized I just needed a data: field in the ajax call. Now the image simply just isn't updating :/ – john stamos Apr 20 '23 at 02:03
  • 1
    Hi @johnstamos , you are missing `#` when using `$('myImage')...` just change that to `$('#myImage').attr('src', "..`. – Swati Apr 20 '23 at 16:47

0 Answers0