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?