Golang : JQuery AJAX post data to server and send data back to client example
Just want to write this tutorial for fun.
In this tutorial, we will learn how to use JQuery's AJAX to post and retrieve data from web server. The main purpose here is to demonstrate how Golang receive the data posted by JQuery's AJAX and reply back.
Here we go!
package main
import (
"fmt"
"net/http"
)
func Home(w http.ResponseWriter, r *http.Request) {
html := `<head>
<script src='//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js'></script>
</head>
<html><body>
<h1>Golang Jquery AJAX example</h1>
<div id='result'><h3>before</h3></div><br><br>
<input id='ajax_btn' type='button' value='POST via AJAX to Golang server'>
</body></html>
<script>
$(document).ready(function () {
$('#ajax_btn').click(function () {
$.ajax({
url: 'receive',
type: 'post',
dataType: 'html',
data : { ajax_post_data: 'hello'},
success : function(data) {
alert('ajax data posted');
$('#result').html(data);
},
});
});
});
</script>`
w.Write([]byte(fmt.Sprintf(html)))
}
func receiveAjax(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
ajax_post_data := r.FormValue("ajax_post_data")
fmt.Println("Receive ajax post data string ", ajax_post_data)
w.Write([]byte("<h2>after<h2>"))
}
}
func main() {
// http.Handler
mux := http.NewServeMux()
mux.HandleFunc("/", Home)
mux.HandleFunc("/receive", receiveAjax)
http.ListenAndServe(":8080", mux)
}
Run this code on terminal and point your browser to http://yourserver.com:8080 and a button will appear. Click on the button and see the result on your browser and terminal output. Enjoy!
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.9k Golang : Fixing Gorilla mux http.FileServer() 404 problem
+8k Golang : Oanda bot with Telegram and RSI example
+22.7k Golang : Read a file into an array or slice example
+30.5k error: trying to remove "yum", which is protected
+5.8k Golang : How to verify input is rune?
+9.5k Golang : List available AWS regions
+31.1k Golang : Get local IP and MAC address
+6.2k Golang : Handling image beyond OpenCV video capture boundary
+30.9k Golang : bufio.NewReader.ReadLine to read file line by line
+22.4k Golang : simulate tail -f or read last line from log file example
+9.9k Golang : Text file editor (accept input from screen and save to file)
+5.7k Golang : Function as an argument type example