Answer the question
In order to leave comments, you need to log in
Execute/call function from Go file on click on html button?
Hello. I am learning how to create web applications in Golang.
By default, html buttons can perform JS functions.
How to call a function from Go code when a user clicks a button on a website?
Of course, first rummaged through the internet. It all comes down to AJAX or Rest api. But there is no information on the question asked. Basically everything about creating and testing the server and just water about the possibilities. No specifics.
Those. for the sake of accuracy of the example:
in main.go, in the page function, there is a conditional function foo() that processes the data on the page and outputs it.
There is a button in html that, when clicked, executes this function foo()
A bunch of answers are abstract: use AJAX or Rest API. I did not find any materials on specific tasks using these resources. Only the general plan of work.
Thank you.
Answer the question
In order to leave comments, you need to log in
Your algorithm will be something like this...
When you click on the button, a function will be called (the button's onClick event handler).
In this function, you will make an HTTP AJAX request to your server where your Go software is running.
In main.go, you start an HTTP server that will accept the request from your JavaScript function, process it, and respond.
Let's analyze the simplest option with the GET method to make it easier for you to test.
On the server (your computer), run main.go with something like this
package main
import (
"fmt"
"net/http"
)
func helloHandler(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "hello\n")
}
func main() {
http.HandleFunc("/hello", helloHandler)
http.ListenAndServe(":8081", nil)
}
const req = new XMLHttpRequest();
const url='http://127.0.0.1:8081/hello';
req.open("GET", url);
req.send();
req.onreadystatechange=(e)=>{
console.log(req.responseText)
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question