Answer the question
In order to leave comments, you need to log in
Why can't I send ajax request to Fiber web framework?
Hello. I'm not a programmer, but I'm coding for myself.
Problem - I can not send a POST (JSON) request to the server.
What I want to do is a server on Fiber that receives a POST request (JSON, XMLHttpRequest) 2 parameters from the html page and after processing the server returns one line.
I use Fiber because, somehow, I made a small static site for myself, and everything was clear in the “examples” there. In a word, ctrl + C - ctrl + V, slightly corrected, fiddled with html, js, css and everything started! :-)
main.go - server start (there seem to be no problems here)
package main
import (
"github.com/gofiber/fiber"
"github.com/gofiber/fiber/middleware/logger"
)
func main() {
app := fiber.New()
app.Use(logger.New())
app.Static("/", ".")
app.Get("/", func(c *fiber.Ctx) error {
return c.SendFile("./main.html")
})
app.Post("/search", PostTodo)
app.Listen(":3003")
}
package main
import (
"fmt"
"github.com/gofiber/fiber"
)
type Response_JSON struct {
Name string `json:"name"`
Surname string `json:"surname"`
}
func PostTodo(c *fiber.Ctx) error {
type request struct {
Name string `json:"name"`
Surname string `json:"surname"`
}
var body request
err := c.BodyParser(&body)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"error": "Cannot parse JSON",
})
}
fmt.Println("body: ", err)
todo := Response_JSON{
Name: body.Name,
Surname: body.Surname,
}
fmt.Println("todo: ", todo)
my_request := "<div>" + todo.Name + "</div>"
my_request = my_request + "<hr><div>" + todo.Surname + "</div>"
return c.SendString(my_request)
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Proba</title>
</head>
<body>
<div class="container">
<div class="logo">
<h1>Proba</h1>
</div>
<form action="/search" class="search_form" method="POST">
<div class="search">
<input type="text" id="search_name" value="" name="search_name" placeholder="Search name...">
<input type="text" id="search_surname" value="" name="search_surname" placeholder="Search surname...">
<input type="submit" id="send" class="search_button" value="Go">
</div>
</form>
<div id="result" class="result">
</div>
</div>
<script src="main.js"></script>
</body>
</html>
let mybutton = document.getElementById("send");
mybutton.addEventListener("click", () => {
let name = document.getElementById("search_name").value;
let surname = document.getElementById("search_surname").value;
let s = {};
s.name = `${name}`;
s.surname = `${surname}`;
let search_json = JSON.stringify(s);
console.log("s: ", s);
console.log("name: ", name);
console.log("surname: ", surname);
console.log("search_json ", search_json);
let request = new XMLHttpRequest();
request.open('POST','/search');
request.setRequestHeader('Content-type', 'application/json');
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200)
document.getElementById("result").innerHTML=request.responseText;
}
request.send(search_json);
});
let user = {
name: "Ivan",
surname: "Ivanov"
};
console.log("user:", user);
let json = JSON.stringify(user);
console.log("json:", json);
let request = new XMLHttpRequest();
request.open("POST", "/search");
request.setRequestHeader('Content-type', 'application/json');
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200)
document.getElementById("result").innerHTML=request.responseText;
}
request.send(json);
Answer the question
In order to leave comments, you need to log in
Solution:
// Bind the call to the variable 'e'
mybutton.addEventListener("click", (e) => {
// Add this line!
e.preventDefault();
/* ... the rest is the same ... */
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question