Posting javascript variable to mysql using ajax in golang

I find screen size using javascript and want this data to post mysql using ajax. But this is not working. How do I define screen size variable in new.go file? How do I post automatically created screen size information to mysql using ajax?

Here is new.html code:

Call Go
        (function (window) {

                // screen
                var screenSize = '';
                if (screen.width) {
                    width = (screen.width) ? screen.width : '';
                    height = (screen.height) ? screen.height : '';
                    screenSize += '' + width + " x " + height;

            window.jscd = {
                screen: screenSize,
            'Screen Size: ' + jscd.screen

                $("#callGo").on('click', function() {
                    url: "http://localhost:9000/callme",
                    method: "POST",
                    success: function() {

    <button id="callGo" type="submit">Call Go Code</button>
    <div id="response"></div>

When I click callGo named button then response named div success added text must be shown. But how do I do that? How do I connect ajax sending data to go backend code to insert mysql?

Here is my new.go file

package main

import (

_ ""


// Load the index.html template.
var tmpl = template.Must(template.New(“tmpl”).ParseFiles(“new.html”))

func main() {
// Serve / with the index.html file.
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if err := tmpl.ExecuteTemplate(w, “new.html”, nil); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)

// Serve /callme with a text response.
http.HandleFunc("/callme", func(w http.ResponseWriter, r *http.Request) {

    db, err := sql.Open("mysql", "root:@tcp(")
    defer db.Close()
    if err != nil {
    if r.Method == "POST" {
        insForm, err := db.Prepare("INSERT INTO screen(screen_size) VALUES(?)")
        if err != nil {


    http.Redirect(w, r, "/", 301)

// Start the server at http://localhost:9000
log.Fatal(http.ListenAndServe(":9000", nil))


You need to add the data to be sent to your ajax call

url: “http://localhost:9000/callme”,
method: “POST”,
data: {“screenSize” : jscd.screen},
success: function() {

Then in your go code, in the handleFunc take the parameters via r.Body


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