S
S
sdima752021-04-22 22:42:49
AJAX
sdima75, 2021-04-22 22:42:49

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")
 
}


search.go - the logic of what to do after receiving the data. (so far just a template, there is a minor problem, but mostly works)
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)
}

main.html - start page
<!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>


main.js - script for processing forms after clicking (here is the main problem)
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); 
});


main2.js - trial js that works without a "click" (through it I tried to understand where the problem is)
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);


And so in order:
1 - Start the server and go to main.html. We enter the data and click on the button and see the result. The request did not go away and, oddly enough, the line console.log("s: ", s); (main.js file) didn't work (no console output).
6081d10b33b00946884638.png

6081d1145f7c8507257266.png

2 - however, if you use the main2.js script, which is without pressing, then everything seems to work. The data has been sent and the server has processed and returned it.
Although, for some reason, in the search.go file, the output fmt.Println("body: ", err) is "nil", but the "body" variable contains the decoded request body (application/json), judging by the documentation.
6081d126d4984261617321.png

6081d12e6c9fb815067381.png

Please help me solve the problem. I google, yandex, youtube “shoveled” for 2 days and I can’t understand what the problem is ...

I will be grateful to you in advance for your answer!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sdima75, 2021-04-23
@sdima75

Solution:

// Bind the call to the variable 'e'
mybutton.addEventListener("click", (e) => {
   // Add this line!
   e.preventDefault();
/* ... the rest is the same ... */

The saddest thing is that I saw a similar solution on the Internet last night. But apparently I was very tired (my brains were "boiling") and I had various errors due to - "e" when I decided to try these different options in javascript.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question