I’m trying to make a simple hello world app to test connecting front end and back end. The back end is a simple flask app.
This is the JS that executes on button click:
function mouseAction() {
let helloWorldButton = document.getElementById('btn')
helloWorldButton.addEventListener("click", function(){
//post request goes here
console.log("mouse clicked!")
$.post({
url: "http://localhost:5000/hello_world",
data: {},
success: function(data){
formatReturnedData(data)
},
dataType: 'string'
})
console.log(data)
console.log('hi bruh')
})
}
I know the request is received by the server because my daemon logs it:
But the ‘hi bruh’ or the ‘data’ never get printed to console, what am I doing wrong? Any help is appreciated.
3
Answers
Data only exists inside the success function
By default jquery ajax request works asynchronously. In that case as you putted your console.log after the server request console.log is executing before server response. If you put console.log inside success call back function the problem will resolve. For example
Your request is not formed properly. Your
console.log
s should be inside of your success callback function. And'string'
is not a validdataType
value.Try this instead:
For more details see the docs https://api.jquery.com/jquery.post/