How can I pass form input from client to server in javascript? Below is the client side. I want to take a username or anything entered in textbox, and send it to server.js where it will be processed for validation. the thing is that I need the data from client.js to be stored in a variable in server.js to be able o retreive it.
var textbox;
var dataDiv;
window.onload = init;
function init(){
textbox = document.createElement("input");
textbox.id="textbox";
dataDiv = document.createElement("div");
var header = document.createElement("h1");
header.appendChild(document.createTextNode("Select User"));
var button = document.createElement("BUTTON");
button.id = "myBtn";
var textBtn = document.createTextNode("Click me");
button.appendChild(textBtn);
button.addEventListener("click", () => {
sendData();
});
var docBody = document.getElementsByTagName("body")[0];//Only one body
docBody.appendChild(header);
docBody.appendChild(dataDiv);
docBody.appendChild(textbox);
docBody.appendChild(button);
}
function sendData(){
var usrName = document.getElementById("textbox").value; //I want to send it to server.js
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var dataObj = JSON.stringify(this.responseText);
dataDiv.innerHTML = dataObj;
}
};
xhttp.open("GET", "/register", true);
xhttp.send();
}
This is the server side
var express = require('express');
var app = express();
app.get('/register', handleGetRequest); //how do I pass usrName here?
app.use(express.static('public'));
app.listen(5000);
function handleGetRequest(request, response){
var pathArray = request.url.split("/");
var pathEnd = pathArray[pathArray.length - 1];
if(pathEnd === 'register'){
response.send("{working}");
}
else
response.send("{error: 'Path not recognized'}");
}
If you use GET, you have to put the parameters in the URL.
xhttp.open("GET", "/register?usrName=" + encodeURIComponent(usrName), true);
See How to get a URL parameter in Express? for how you read the query parameter in Express.
Sending data:
function sendData(){
var usrName = document.getElementById("textbox").value; //I want to send it to server.js
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var dataObj = JSON.stringify(this.responseText);
dataDiv.innerHTML = dataObj;
}
};
xhttp.open("GET", "http://localhost:5000/register?usrName=" + encodeURIComponent(usrName), true);
xhttp.send();
}
Reading data:
function handleGetRequest(request, response){
var urlParts = request.url.split("?");
if(urlParts[0] === '/register'){
var usrName = urlParts[1].replace('usrName=', '');
response.send("{" + usrName + "}");
}
else
response.send("{error: 'Path not recognized'}");
}
Related
Success localhost response
Cannot GET /u/coupons at server
Frontend script for post
<script>
var count = document.getElementById("count");
var len = document.getElementById("length");
var pattern = document.getElementById("pattern");
document.getElementById('coupons-button').onclick = function()
{
if(count.value!=="" && len.value!=="")
{
const genReq = new XMLHttpRequest();
let url = `count=${encodeURI(count.value)}&` +
`len=${encodeURI(len.value)}&` +
`pattern=${encodeURI(pattern.value)}`;
genReq.open('POST',`/u/coupons?${url}`,true);
genReq.send();
genReq.onreadystatechange = e => {
if(genReq.readyState === 4 && genReq.status === 200){
let gen = JSON.parse(genReq.response);
if (gen.state === "SUCCESS")
{
var coupons = gen.coupons;
for(var i=0;i<coupons.length;i++)
{
var div = document.createElement('div');
var text = document.createTextNode(coupons[i]);
div.appendChild(text);
document.getElementById('coupons-check').appendChild(div);
}
} else {
var div = document.createElement('div');
var text = document.createTextNode("FAIL TO GENERATE");
div.appendChild(text);
document.getElementById('coupons-check').appendChild(div);
}
}
}
}
}
Server script
admin.post( '/u/coupons' ,(req,res)=>{
let params = getParameters(req);
CouponWorker.generateCoupons({
"len":decodeURI(params.len),
"count":decodeURI(params.count),
"pattern":decodeURI(params.pattern)
}).then((_res) =>{
console.log(_res)
if(_res.success === true)
{
res.status(200).json({
"state":"SUCCESS",
"coupons":_res.coupons
});
}
else{
res.status(200).json({"state" : "FAILED"});
}
});
});
CouponWorker
const firebase = require('./Database');
const voucher_codes = require('voucher-code-generator');
exports.generateCoupons = function(params)
{
var len = params.len;
var count = params.count;
var pattern = params.pattern;
//pattern = pattern.replace(/1/g,'#');
const cpn_db = firebase.firebase.database();
var coupons;
return new Promise((resolve,reject)=>{
coupons = voucher_codes.generate({
length:len,
count:count,
prefix:"AMP-",
pattern: '####-####',
charset:"0123456789ABCDEFGHIJKLMNOPQRSTUVXYZ"
});
if(coupons!==null)
{
for(var i =0;i<count;i++)
{
cpn_db.ref('coupons/cid-'+coupons[i]).set({
"addedOn": getDateTime(),
"code" : coupons[i],
"amount" : 20,
"expireDate" : null,
"isActive" : true,
"isDeleted":false
});
}
resolve({
"success":true,
"coupons":coupons
});
}
else
{
resolve({
"success":false
});
}
});
}
Above given snaps shows the same code running on localhost and server,
localhost working fine,giving output and saving data to firbase while server response 404 not found resource.
I can not find the reason of this error.I tried url req on postman and responses are the same as above
I need to recover the response in variable and show it
'confirmation' :()=> {
let responseJson = {};
var request = require('request');
var url = 'http://dev.exemple02.com/ws/ws_login_sh.php?username=' + username + '&password=' + password;
request(url, function (error, responseJson, body) {
console.log(responseJson);
var test = JSON.parse(body);
if(test['codeRetour']===1){
var customer=test['customer'];
var nom=customer['first_name'];
var prenom=customer['last_name'];
console.log('super !vous etes connecté'+prenom);
responseJson.displayText = 'super ! vous etes connecté'+prenom ;
response.json(responseJson);
}
});
but the response.json(responseJson); doesn't show the result
I am trying to write some items I pushed into an array into a JSON file in node.js but I can't figure out how to wait for the array to contain the items before writing the JSON file. As a result the file is always empty. Do i need to have a callback? If so, how? NB:I'm still new to node.js
This is the code below:
var getLinks = require('./news_archive/news_links.js');
var request = require('request');
var cheerio = require('cheerio');
var fs = require('fs');
var saveNews = './news_archive/news.json';
var jsonObj = [];
var i;
var number_of_links = getLinks.links.length;
for(i=0; i<number_of_links; i++){
//GET ARTICLE LINK FROM link.js
var url = "http://www.times.co.sz/"+getLinks.links[i];
request(url, function(err, resp, body){
var $ = cheerio.load(body);
//GET ARTICLE HEADLINE
var storyHeadline = $('#article_holder h1');
var storyHeadlineText = storyHeadline.text();
//GET DATE POSTED
var datePosted = $('.metadata_time');
var datePostedText = datePosted.text();
//GET ARTICLE REPORTER'S NAME
var reporterName = $('.article_metadata a');
var reporterNameText = reporterName.text();
//GET ARTICLE SUMMARY
var fullStory = $('#article_body span');
var fullStoryText = fullStory.text();
//PUSH ITEMS TO jsonObj ARRAY
jsonObj.push({
id: i,
storyHeadline: storyHeadlineText,
datePosted: datePostedText,
reporterName: reporterNameText,
fullStory: fullStoryText
})
});
} //END for LOOP
//WRITE TO news.json file
fs.writeFile(saveNews, JSON.stringify(jsonObj, null, 4), function(err) {
if(err) {
console.log(err);
} else {
console.log("JSON saved to " + saveNews);
}
});
The issue is that request is asyncronous and you cannot use syncronous loop to iterate through. You can use async lib for that
var getLinks = require('./news_archive/news_links.js');
var request = require('request');
var cheerio = require('cheerio');
var fs = require('fs');
var saveNews = './news_archive/news.json';
var number_of_links = getLinks.links.length;
var async = require('async');
async.times(number_of_links, function (i, next) {
var url = "http://www.times.co.sz/"+getLinks.links[i];
request(url, function(err, resp, body){
var $ = cheerio.load(body);
//GET ARTICLE HEADLINE
var storyHeadline = $('#article_holder h1');
var storyHeadlineText = storyHeadline.text();
//GET DATE POSTED
var datePosted = $('.metadata_time');
var datePostedText = datePosted.text();
//GET ARTICLE REPORTER'S NAME
var reporterName = $('.article_metadata a');
var reporterNameText = reporterName.text();
//GET ARTICLE SUMMARY
var fullStory = $('#article_body span');
var fullStoryText = fullStory.text();
//PUSH ITEMS TO jsonObj ARRAY
next(err, {
id: i,
storyHeadline: storyHeadlineText,
datePosted: datePostedText,
reporterName: reporterNameText,
fullStory: fullStoryText
});
});
}, function (err, res) {
// do not forget to handle error
fs.writeFile(saveNews, JSON.stringify(res, null, 4), function(err) {
if(err) {
console.log(err);
} else {
console.log("JSON saved to " + saveNews);
}
});
})
Basically,
I first initiate socket.io like this:
var io = require('socket.io')(1337);
Then, after using http to get a POST request and check some info, I try this:
var updateArray = {timer:"start"};
jsonUpdate = JSON.stringify(updateArray);
io.emit('update', jsonUpdate);
But it doesn't send the sockets, and I really can't understand the socket.io documentation sadly, so I'd be happy if someone can help me out.
Server code:
var http = require('http');
var fs = require('fs');
var io = require('socket.io')(1337);
var initialBomb = 0;
function now() {
return Math.floor(new Date() / 1000);
}
http.createServer(function (req, res) {
var body = "";
req.on('data', function (chunk) {
if (req.method == 'POST') {
body += chunk;
}
});
req.on('end', function () {
parsedBody = JSON.parse(body);
if (parsedBody.round["bomb"] == "planted") {
var rightNow = now();
var initialCheck = initialBomb + 41;
if (rightNow > initialCheck) {
initialBomb = now();
var updateArray = {timer:"start"};
jsonUpdate = JSON.stringify(updateArray);
io.emit('update', jsonUpdate);
console.log(jsonUpdate);
}
}
});
}).listen(3000);
Client Code:
<script>
var socket = io('87.98.219.48:1337');
socket.on('update', function(payload) {
var data = JSON.parse(payload);
console.log(payload);
if (data['timer'] == 'start') {
initTick = timerNow();
setTimeout(tick, delay);
}
});
</script>
If any one worked on Kinvey (Mbaas) Please help in setting up datalink project using nodeJS
I am new to nodeJS, I created an nodejs project based on kinvey sample.
Below is nodejs code sample
var configTools = require("./config");
var util = require("util");
var querystring = require('querystring');
var ServiceLink = require('./service_link');
var restify = require('restify');
var server = restify.createServer();
//Configure the server to parse the request body into req.body
server.use(restify.bodyParser({ mapParams: false }));
//insert into call chain when debugging
var debug = function(req, res, next) {
if (config.debug){
var method = req.method;
var params = req.params;
var query = req.query;
var body = req.body;
console.log("Method: " + method +
"\nParams: " + util.inspect(params, false, null, true) +
"\nQuery: " + util.inspect(query, false, null, true) +
"\nBody: " + util.inspect(body, false, null, true) + "\n");
}
if (config.debugFullRequest){
console.log(util.inspect(req));
}
return next();
}
// Verify key matches the header
var keyauth = function(req,res,next) {
var key = req.headers['x-auth-key'];
if (key != config.key) {
return next(new restify.InvalidCredentialsError("Invalid API Key"));
} else {
next();
}
}
//Router functions
var extractReq = function(req, next){
if (!req){ return new restify.InternalError("ServiceLink is having problems..."); }
var params = req.params;
var query = req.query;
var body = req.body;
var output = {query: null, params: null, body: null, route: null};
// Extract query
if (query && query !== undefined){
try {
var parsedString = querystring.parse(query);
output["query"] = JSON.parse(parsedString.query);
} catch (e){
return new restify.InvalidContentError("JSON query exception: " + e);
}
}
// Extract route
if (params && params !== undefined){
try {
var s = "";
s = params.collection;
if (params.id){
s = s + "/" + params.id;
}
output["route"] = s;
} catch (e){
return new restify.InvalidContentError("Invalid Params: " + e);
}
}
// Extract body
if (body && body !== undefined){
try {
output["body"] = body;
} catch (e){
return new restify.InvalidContentError("JSON body exception: " + e);
}
}
return output;
};
var preGet = function(req, res, next){
var data = extractReq(req, next);
if (data instanceof Error){
return next(data);
}
ServiceLink.get(data["route"], data["query"], data["body"], res, next);
};
server.get(/\/public\/?.*/, restify.serveStatic({
directory: './docs',
default: 'index.html'
}));
//For debugging we add in the debug middleware
server.get('/:stateList', keyauth, debug, preGet);
server.listen(3000, function() {
console.log('%s listening at %s', server.name, server.url);
});
if you look at the code, i have created angular front end and supply index page for routing.
my html file is loading fine, in that i will call kinvey datastore i.e stateList
like this
var promise = $kinvey.DataStore.find('stateList');
but it is giving me 500 error, when I mapped collection with datalink it is giving me error saying "_count endpoint to be implemented in the data link connector"
My datalink link is http://localhost:3000/
anyone please guide me on this mapping.
Thanks