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:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Call Go</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
(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>
</html>
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))
}