Reputation: 177
I have a golang API for saving and retrieving the data from the form. Saving the data filled in the HTML form is okay. Means it will save the data in database of mongodb successfully but in case of retrieving the data it will retrieve the data on the basis of the email filled in the field of the html form is successful but it shows the data in the terminal of the ubuntu. Below is the code I'm trying for this:-
Html form index.html file
<form id="form1" method="post">
<input id= "firstname" type="text" name="FirstName" placeholder="Enter your firstname"><br><br>
<input id= "lastname" type="text" name="LastName" placeholder="Enter your lastname"><br><br>
<input id= "email" type="text" name="Email" placeholder="Enter your email"><br><br>
<input id= "mobile" type="text" name="Mobile" placeholder="Enter your mobile"><br><br>
<button id= "button1" class="button" name="button" type="button" value="Submit">Submit</button>
<button id= "button2" class="button" name="button" type="submit" value="Search">Search</button>
</form>
Ajax in index.html is :-
$(document).ready(function(){
//IT will save the data
$('#button1').on('click', function(e){
button=this.value;
console.log(button);
e.preventDefault();
if (button === "Submit") {
var FirstName =$("#firstname").val(),
LastName =$("#lastname").val(),
Email =$("#email").val(),
Mobile =$("#mobile").val();
console.log(FirstName);
$.ajax({
url:"/login",
type:"POST",
data: {'button':button, "first":FirstName, "last":LastName, "email":Email, "mobile":Mobile},
success: function(results) {
console.log(results);
$('#response').html(results);
}
});
}
});
// This will search and I want the result in the success
$('#button2').on('click', function(e){
button=this.value;
console.log(button);
e.preventDefault();
var Email =$("#email").val();
$.ajax({
url:"/get-data",
type: "GET",
data:{'button':button,"email":Email},
success: function(results){
console.log(results)
$('#response').html(results);
}
});
});
});
Main.go file
import (
"fmt"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"html/template"
"log"
"net/http"
"encoding/json"
)
type USER struct {
FirstName string `json:"FirstName,omitempty"`
LastName string `json:"LastName,omitempty"`
Email string `json:"Email,omitempty"`
Mobile string `json:"Mobile,omitempty"`
}
func login(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method)
if r.Method == "GET" {
t, _ := template.ParseFiles("index.html")
t.Execute(w, nil)
} else {
r.ParseForm()
fmt.Println(r.Form)
if r.Form["button"][0] == "Submit" {
fmt.Println(r.Form)
session, err := mgo.Dial("mongodb://127.0.0.1:27017/user")
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
c := session.DB("user").C("profile")
doc := USER{
FirstName: r.Form["first"][0],
LastName: r.Form["last"][0],
Email: r.Form["email"][0],
Mobile: r.Form["mobile"][0],
}
err = c.Insert(doc)
if err != nil {
panic(err)
}
fmt.Println("FistName:", r.Form["first"][0])
fmt.Println("LastName:", r.Form["last"][0])
fmt.Println("Email:", r.Form["email"][0])
fmt.Println("Mobile:", r.Form["mobile"][0])
}
}
}
func AllData(w http.ResponseWriter, r *http.Request){
fmt.Println("method:", r.Method)
if r.Method == "GET" {
r.ParseForm()
fmt.Println(r.Form)
if r.Form["button"][0] == "Search" {
fmt.Println(r.Form)
fmt.Println(r.Form["email"][0])
session, err := mgo.Dial("mongodb://127.0.0.1:27017/user")
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
c := session.DB("user").C("profile")
result := Users{}
err = c.Find(bson.M{"email": r.Form["email"][0]}).All(&result)
fmt.Println(result)
b, err := json.MarshalIndent(result, "", " ")
if err != nil {
panic(err)
}
fmt.Printf("%s\n", b)
}
}
}
func main() {
http.HandleFunc("/login", login)
http.HandleFunc("/get-data", AllData)
err := http.ListenAndServe(":9090", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
What should I do for receiving the data from golang to the ajax GET
method request click on the button search and result will display in the success function of the ajax. Thank you in advance.
Upvotes: 2
Views: 8878
Reputation: 12685
Send the response header of Data
function in json format and write the response of json which can be received in success of $.ajax
func AllData(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method)
if r.Method == "GET" {
// your code ....
b, err := json.MarshalIndent(result, "", " ")
if err != nil {
panic(err)
}
fmt.Printf("%s\n", b)
// set header to 'application/json'
w.Header().Set("Content-Type", "application/json")
// write the response
w.Write(b)
}
}
}
Also there is an error in your code where you are returning from handler func AllData
either create a middleware if you wants to do some modification in result or remove the return part of handler AllData
Upvotes: 1