Reputation: 81
I am trying to access post params in golang which are sent via jquery ajax. Maybe I am missing something obvious. Here are my code snippets
$('form').submit(function(e) {
e.preventDefault();
var jsn = {
vvv = $("#textinput").val();
};
console.log(jsn);
$.ajax({
type: "POST",
async : true,
//enctype: 'multipart/form-data',
url: "/homepage",
data: jsn,
processData: true,
contentType: "application/json",
cache: false,
}).done(function(response){
$("#resultdiv").html(response);
});
});
here is my golang code:
func MainConversion(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
text := r.FormValue("vvv")
fmt.Fprint(w, string(text))
return
})
I have tried f.formValue(), r.Form.get() . Thanks in advance
Upvotes: 0
Views: 454
Reputation: 4515
You've sent your request with a JSON body, but ParseForm
on an *http.Request
does not handle JSON. You need to read the body of the request and parse it as JSON, or don't send your body as JSON.
func MainConversion(w http.ResponseWriter, r *http.Request) {
var body = make(map[string]string)
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
text := body["vvv"]
w.Write([]byte(text))
}
Upvotes: 3
Reputation: 310
Your JS snippet contains syntax errors, so I assume no request reaches your golang API.
var jsn = {
vvv = $("#textinput").val();
};
should be:
var jsn = {
vvv : $("#textinput").val()
};
Upvotes: 0