Home > Software design >  How to get and AJAX response using Golang with Gin Routing
How to get and AJAX response using Golang with Gin Routing

Time:10-17

Here is my code of Golang (Notice the registerNewUser in the POST ("/register") handler:

func main(){

    router := gin.Default()
    router.LoadHTMLFiles("../login.html", "../recoverPassword.html")
    router.Static("/css", "../css")
    router.Static("/img", "../img")
    router.Static("/js", "../js")
    router.GET("/", loadMainPage)
    router.POST("/register", registerNewUser)

    router.Run("localhost:8080")
}
func registerNewUser(c *gin.Context) {
    fmt.Print("Nonas")
    log.Print("Sisas")
}

Now, here is my code of javascript:

$.ajax({
                        url: "/register",
                        method: "POST",
                        data: {firstname:Firstname, lastname:Lastname, username:Username, email:Email, password:Password, country:Country},
                        beforeSend:function(){
                            $("#submit_register_form_btn").attr('disabled', true);
                            $("#submit_register_form_btn").val('Conectando...');
                        },
                        success:function(response) {
                            $('#submit_register_form_btn').removeAttr('disabled');
                            alert(response);
                        }
                    });

I need a way to return a string as response from Golang to the AJAX petition

CodePudding user response:

fmt and log print to os.Stdout and os.Stderr respectively. You need to respond to the web request.

Gin passes a *gin.Context to your handler for this purpose.

https://pkg.go.dev/github.com/gin-gonic/gin#readme-quick-start shows a very small example of returning data through the context. There are tons of other great examples in https://pkg.go.dev/github.com/gin-gonic/gin#readme-api-examples.

"Context is the most important part of gin," so read the documentation thoroughly after reviewing a few examples to wrap your head around what usage generally looks like.

Once you feel like you have your head wrapped around the quickstart, take a look at gin's Context.String . You can substitute that for the c.JSON call in the example.

  • Related