Alternative to jQuery Ajax Serialize function

Hello Beautiful Campers, I have this code that works with jQuery but I’ve been searching for ways to do it with Vanilla Javascript all to no avail.
Here is the code
index.html

<body>
    <h1>Metric/Imperial Converter</h1>
    <hr>

    <section class="code">
        <h3>Example Usage</h3>
        <code>/api/convert?input=4gal</code><br>
        <code>/api/convert?input=1/2km</code><br>
        <code>/api/convert?input=5.4/3lbs</code><br>
        <code>/api/convert?input=kg</code>

        <h3>Example Return</h3>
        <code>{initNum: 3.1, initUnit:'mi',returnNum:4.98895,returnUnit: 'km', string:'3.1 miles converts to 4.98895 kilometers'}</code>

        <hr>
    </section>

    <section class="form">
        <div class="test-container">
            <h3>Front-End</h3>

            <form id="form">
                <input type="text" name="input" placeholder="3.1mi">
                <input type="submit" value="Convert!" name="convert">
            </form>
            <p id='result'></p>
            <code id='jsonResult'></code>
        </div>
    </section>

    <script src="https://code.jquery.com/jquery-2.2.1.min.js"
        integrity="sha256-gvQgAFzTH6trSrAWoH1iPo9Xc96QxSZ3feW6kem+O00=" crossorigin="anonymous"></script>
    <script>
        $(function () {
            $('#form').submit(function (event) {
                event.preventDefault();
                $.ajax({
                    url: '/api/convert',
                    type: 'get',

                    data: $('#form ').serialize(),
                    success: function (data) {
                        $('#result').text(data.string || data);
                        $('#jsonResult').text(JSON.stringify(data));
                        console.log(data)
                    },
                    error: function (request, textStatus, errorThrown) {
                        alert(request.getResponseHeader('some_header'));
                    }
                });
            });
        });
    </script>

</body>

</html>

Here is the Server side

const express = require("express");
const expect = require("chai").expect;


const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.use(express.static("public"));


app.route("/")
    .get((req, res) => {
        res.sendFile(process.cwd() + '/views/index.html')
    })

app.route("/api/convert")
        .get((req, res) => {

            let { input } = req.query;
          
            res.json(input);
        })

app.use((req, res, next) => {
    res.status(404)
        .type("text")
        .send("Not Found")
})


const port = 3000;

app.listen(port, () => {
    console.log(`App is listening on port ${port}`)
})

Hello there,

What have you tried, in terms of vanilla JS? What are you struggling with?

Nowadays, it is very straight-forward to have a input[type='submit'] submit some form data, with plain-old JS.

hi, i’ve been struggling with getting data from my url. The fetch request has been the major hurdle.
After running the code below it logs “not found”

const result = document.getElementById("result");
const jsonResult = document.getElementById("jsonResult");

let form = document.getElementById("form");

document.addEventListener("DOMContentLoaded", () => {
    form.addEventListener("submit", handleForm)
})

async function handleForm(e) {
    e.preventDefault();
    let formData = new FormData(form);

    // for (let key of formData.keys()) {
    //     console.log(key, formData.get(key))
    // }
    let json = await convertJson(formData);
    let url = '/api/convert';
    let h = new Headers();
    h.append("Content-type", "application/json")
    let req = new Request(url, {
        headers: h,
        body: json,
        method: "post"
    })
    fetch(req)
        .then((res) => res.text())
        .then((data) => {
            console.log("response from data");
            console.log(data)
        })

}

function convertJson(formData) {
    let obj = {};
    for (let key of formData.keys()) {
        obj[key] = formData.get(key);
    }
    console.log(obj)
    return JSON.stringify(obj)
}

You are using the await keyword on a non-asynchronous function:

If you want an asynchronous function, you should define it as such:

async function convertJson(...

However, what you are doing is not asynchronous. So, it is unnecessary. I am not sure what environment you are coding in, but a competent text editor should warn you about such things.

In general, I avoid most of these other libraries/functions (e.g. FormData, Headers, Request) - they tend to make things more complicated than not.


Now, the docs are excellent at describing how to use fetch:

I would make what you are doing a lot neater and simpler with just:

const myJSONData = ...
const URL = '/api/convert';
const options = {
  method: 'post',
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(myJSONData)
}

const response  = await fetch(URL, options);
const data = await response.json(); // if response is JSON. .text() works too

Also, you have some logic errors here:

// server
app.route("/api/convert")
        .get((req, res) => {
// client
let req = new Request(url, {
        headers: h,
        body: json,
        method: "post"
    })

You have not defined a POST handler for that route.


Lastly, be sure to debug as much as possible for each line. Add as many console.logs as needed, and make use of the browser devtools to see what is happening in the network.

Hope this helps

1 Like

Thank you @Sky020 would work on them now

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.