D
D
damonpolt2017-07-11 18:46:45
JavaScript
damonpolt, 2017-07-11 18:46:45

How to kick data from Golang back to Js via AJAX?

Not so long ago, I began to storm Go. And while chirping with an AJAX request, I stumbled upon a problem. At the root, I have, as you might guess, index markup with Jquery AJAX.

<body>
  <button id="send">Send</button>
</body>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="  crossorigin="anonymous"></script>
<script>
  var data;
  $('#send').click(function() {
    $.ajax({
      url: "http://localhost:8080/receive",
      method: "POST",
      data : { sendedData: 'Hello'},
            success : function(data) {
                alert(data);
            },
    });
  });
</script>

Well, I send this Hello server. So far so good. Everything is displayed in the console and so on.
package main

 import (
 	"fmt"
 	"net/http"
 )

 func swap(a,b string) (string,string) {
  return b, a
}

 func receiveAjax(w http.ResponseWriter, r *http.Request) {
 	if r.Method == "POST" {
 		sendedData := r.FormValue("sendedData")
 		fmt.Println("My request is: ", sendedData)
 		a, b := swap(sendedData, "World")
 		fmt.Println(a, b)
 	}
 }

 func main() {
 	http.HandleFunc("/receive", receiveAjax)

 	http.ListenAndServe(":8080", nil)
 }

Well, anyway, why am I writing here. I want to send the result of the above checked functions back to the index file and output via alert. Google has info about connecting index markup directly to GO. But I would like to implement it without it, as I once did through echo in PHP.

In short, if someone enlightens I will be grateful!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Luzanov, 2017-07-11
@dmitry_luzanov

Two minutes of googling:

// AJAX Request Handler
func ajaxHandler(w http.ResponseWriter, r *http.Request) {
    //parse request to struct
    var d Data
    err := json.NewDecoder(r.Body).Decode(&d)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }

    // create json response from struct
    a, err := json.Marshal(d)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
    w.Write(a)
}

You most likely need it w.Write(a).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question