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,
            };
        }(this));
        alert(
            'Screen Size: ' + jscd.screen
        );


                $("#callGo").on('click', function() {
                $.ajax({
                    url: "http://localhost:9000/callme",
                    method: "POST",
                    success: function() {
                        $("#response").html(jscd.screen);
                    },
                });
            });

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

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 (
“database/sql”
“html/template”
“log”
“net/http”

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

)

// 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(127.0.0.1:3306)/test_db")
    defer db.Close()
    if err != nil {
        panic(err.Error())
    }
    if r.Method == "POST" {
        insForm, err := db.Prepare("INSERT INTO screen(screen_size) VALUES(?)")
        if err != nil {
            panic(err.Error())
        }
        insForm.Exec(jscd.screen)

    }

    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

$.ajax({
url: “http://localhost:9000/callme”,
method: “POST”,
data: {“screenSize” : jscd.screen},
success: function() {
$("#response").html(jscd.screen);
},
});

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

HTH,
Yamil

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