Reputation: 61
So I just started trying out some light back-end developing for the first time using express. And I want to call a POST request from a html/js file, and I found how to do it with Jquery. However I would like to know how you can do the exact same thing in pure javascript. Here is the code I have in Jquery:
---Server---
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static("public"));
const greens = {"orange"}
app.get("/greens", (req, res) => {
res.json(greens);
});
app.post('/greens', (req,res) => {
var itemName=req.body.itemName;
console.log("name = "+itemName);
res.end("yes");
});
app.listen(3000, "localhost", () => {
console.log("the server is up and running! http://localhost:3000/greens");
});
---JS File---
$(document).ready(function(){
var itemName;
$("#submit").click(function() {
let Name = "banana";
$.post("http://localhost:3000/login",{itemName: Name}, function(data){
});
});
});
ps. The HTML code I have is only a button with the id "submit". pps. I know the code doesn't really do anything, but I just want to know how to translate the jquery to javascript, nothing else.
Solved using fetch!
fetch("http://localhost:3000/login",
{
method: "POST",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({itemName: "user"})
});
Upvotes: 0
Views: 1075
Reputation: 1083
The jQuery code can be translated to the following pure JS code:
document.getElementById("submit").addEventListener("click", () => {
let xmlHttp = new XMLHttpRequest();
let Name = "banana";
xmlHttp.open("post", "http://localhost:3000/login", true);
xmlHttp.setRequestHeader("Content-Type", "application/json");
xmlHttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xmlHttp.send(JSON.stringify({itemName: Name}));
});
As for the document ready part, you can find a pure implementation of it here: Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it
Upvotes: 1
Reputation: 454
Hope this will help you. Use as per your requirement.
SERVER
const express = require('express');
const cors = require('cors')
const app = express();
app.use(express.json());
app.use(express.urlencoded({extended: true}));
app.use(cors())
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello world');
});
app.post('/greens', (req, res) => {
const body = req.body;
console.log('BODY', body);
res.json(body);
});
app.listen(port, ()=>{
console.log(`Listening to ${port}`);
})
Frontend code:
$(document).ready(function(){
const item = $('#item');
const submit = $('#handleSubmit');
submit.click((e)=>{
e.preventDefault();
let fruitName = item.val();
debugger;
$.post( "http://localhost:3000/greens", { itemName: fruitName })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
})
})
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://code.jquery.com/jquery-3.5.0.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
<script src="main.js"></script>
</head>
<body>
<form>
<input type="text" id="item" value="" name="item"/>
<button type="submit" id="handleSubmit">Submit</button>
</form>
</body>
</html>
Upvotes: 0
Reputation: 160
There are two ways to do that. It depends if you want to use ES5 or ES6 and above.
For ES5 try to look here, it's explained quite well: https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started
For ES6 you can use the fetch-API: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Hope this tutorials will help you!
Upvotes: 1