insert javascript variable to mysql in go

I have javascript variable which is named x and I want this x variable’s value to insert mysql using golang. When I run this code then undefined x error shown. How do I insert javascript variable to mysql?

package main

import (
    "database/sql"
    "fmt"
    "net/http"

    _ "github.com/go-sql-driver/mysql"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, `<!DOCTYPE html>
            <html>
            <head>
                <meta charset="utf-8" />
                <meta http-equiv="X-UA-Compatible" content="IE=edge">
                <title>Page Title</title>
                <meta name="viewport" content="width=device-width, initial-scale=1">

            </head>
            <body>

<script>

var x=5;    

</script>
</body>
</html>`)

        db, err := sql.Open("mysql", "root:@tcp(127.0.0.1:3306)/test_db")
        defer db.Close()
        if err != nil {
            panic(err.Error())
        }
        insForm, err := db.Prepare("INSERT INTO number(number_position) VALUES(?)")
        if err != nil {
            panic(err.Error())
        }
        insForm.Exec(x)

    })
    http.ListenAndServe(":8080", nil)
}

A JavaScript variable (var x=5;) inside a text blob is not a variable to Go. You can not access it from Go code.

What are you trying to do? Will x always be 5? Why?

Use html/template package.

https://golang.org/pkg/html/template/

I don’t think this answers the question. But of course the question is not clear.

Oh, you are right, I thought he wants to generate HTML/Javascript :smiley:

@bashgaa, you have to send your stuff from browser to some endpoint in go either as form submit or AJAX query.

This is client server communication, you can’t do it all in one place.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.