Can't send JSON to server, but ajax call is working - javascript

I have the following code:
serverside.js:
var express = require('express');
var app = express();
app.post('/LEDon', function(req, res) {
var obj = res;
console.log('LEDon button pressed!');
// Run your LED toggling code here
});
app.listen(1337);
clientside.js:
$('#ledon-button').click(function() {
var test = "123";
$.ajax({
type: 'POST',
url: 'http://localhost:1337/LEDon',
data: JSON.stringify(test),
contentType: 'application/json'
});
});
view.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button id='ledon-button'>LED on</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script src='clientside.js'>
</script>
</body>
</html>
Nothing happens when I click the button. But if I remove some lines from clientside.js it works:
$('#ledon-button').click(function() {
var test = "123";
$.ajax({
type: 'POST',
url: 'http://localhost:1337/LEDon',
});
});
But this way no JSON-file is being sent. I tried looking at tutorials but found nothing. What am I missing?

So this is how I solved it:
clientside:
function getData(number) {
var teamId = number; // in data!!
$.ajax({
type: "POST",
url: "http://localhost:80/getdata",
crossDomain:true,
dataType: "json",
data:JSON.stringify(teamId)
}).done(function ( data ) {
var myJSON = JSON.stringify(data);
}
server side:
var express = require('express');
var app = express();
// Load the http module to create an http server.
var http = require('http');
const mysql = require('mysql');
app.post('/getdata', function(request, response) {
var store = '';
var query;
var query2;
// First you need to create a connection to the db
const con = mysql.createConnection({
host: 'db.host.net',
user: 'dbuser',
password: 'mypw',
database: 'dbname',
});
request.on('data', function(data) {
store += data;
query = "regular db query";
con.connect((err) => {
if (err) {
console.log('Error connecting to Db');
return;
}
console.log('Connection was established');
});
con.query(query, (err, rows) => {
if (err) throw err;
// handling query stuff
query2 = "regular db query";
// getting db query
con.query(query2, (err, rows2) => {
// handling query stuff
if (err) throw err;
myJSON = {
"var1": "data1",
"va2": "data2"
}
console.log("\nThe JSON resultset: " + JSON.stringify(myJSON));
response.end(JSON.stringify(myJSON));
con.end();
});
});
console.log("DB connection ended");
});
request.on('end', function() {
response.setHeader("Content-Type", "text/json");
response.setHeader("Access-Control-Allow-Origin", "*");
});
}); app.listen(80);
Let me know if something is unclear or can be done better.

Related

How can I put input value to the JSON in node.js file

I was making the TODO list web application.
This is the 'todo.html' code below :
<html>
<head>
<title>My TODO List</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="main.css">
<script>
$(document).ready(function() {
$("#submit").click(function() {
var bla = $('#item').val();
$("#todo").append("<li class='todoVal'>" + bla + "</li>");
});
// $(document).click(function(e) {
// if (e.target.className == 'todoVal') {
// var t = e.target.innerText
// $(e.target).remove();
// $("#completed").append("<li class='completedVal'>" + t + "</li>");
// }
// });
$(document).click(function(e) {
if (e.target.className == 'completedVal') {
$(e.target).remove();
}
});
jQuery.fn.single_double_click = function(single_click_callback, double_click_callback, timeout) {
return this.each(function() {
var clicks = 0,
self = this;
jQuery(this).click(function(event) {
clicks++;
if (clicks == 1) {
setTimeout(function() {
if (clicks == 1) {
single_click_callback.call(self, event);
} else {
double_click_callback.call(self, event);
}
clicks = 0;
}, timeout || 500);
}
});
});
}
$(document).single_double_click(function(e) {
if (e.target.className == 'todoVal') {
var t = e.target.innerText
$(e.target).remove();
$("#completed").append("<li class='completedVal'>" + t + "</li>");
}
}, function(e) {
if (e.target.className == 'todoVal') {
$(e.target).remove();
}
});
$("#clear").click(function() {
$("li").remove();
});
});
</script>
</head>
<body>
<div id="addItem" class="box">
Task:
<input id="item" type="text" name="add_item" />
<button id="submit" type="button">Add</button>
<button id="clear" type="button">Clear All</button>
</div>
<div id="todo" class="box">
<h4>TODO:</h4>
<ul></ul>
</div>
<div id="completed" class="box">
<h4>Completed:</h4>
<ul></ul>
</div>
</body>
</html>
And this is the 'app.js' file below :
var express = require('express');
var app = express();
var cors = require('cors');
var bodyParser = require("body-parser");
// middleware
app.use(cors());
app.use(bodyParser.json());
var tasks = [];
// This will serve the HTML page todo.html
app.get('/', function(req, res) {
res.sendFile('todo.html', {
root: __dirname
});
});
// GET all tasks
app.get('/tasks', function(req, res) {
res.set('Content-Type', 'application/json')
res.status(200).send(tasks);
});
// POST to add a task
app.post('/task', function(req, res) {
res.set('Content-Type', 'application/json')
/* HELP ME HERE */
// returns 201 on success
res.status(201);
});
// DELETE a task
app.delete('/task', function(req, res) {
/* HELP ME HERE */
// returns 204 on success
res.status(204);
});
// DELETE all tasks
app.delete('/tasks', function(req, res) {
/* HELP ME HERE */
// returns 204 on success
res.status(204);
});
//
// Listen for HTTP requests on port 3000
app.listen(3000, function() {
console.log("listening on port 3000");
});
I want to pass the text box value to the JSON filter by 'TODO' and 'COMPLETED'.
If I add a new TODO list, it goes to the JSON and if the value goes to COMPLETED, it also goes to the JSON
This is the sample JSON result I want:
{"TODO" : [ "Go to market", "Eat dinner with Daniel"], "COMPLETED" : [ "Wash dishes", "Go to gym and Workout" ]}
This is just an example so you guys can just change the format.
Feel free to give me feedback from everything it's always welcome. btw I just started studying how to code
Thank you for spending time on this even if you didn't help me and have a great day!
What you have to do is simply make an Ajax Call to Nodejs APIs. For example,to '/task' and pass the input field value as params in json format then simply fetch them on in Nodejs as req.params.yourjsonKeys.
var inputData = $("#items").val();
$.ajax({
url: "/tasks",
type: "POST",
data: {params: inputData},
dataType: "html",
success: function(data){
if(data.code === 200){ // the response key 'code' from Nodejs
alert('Success');
}
}
});
Next, once you have the params, all you have to do is write it into your file using file system like so:
Create a javascript object with the table array in it
var obj = {
table: []
};
Add some data to it like
obj.table.push({id: req.params.id , square: req.params.square});
Convert it from an object to string with stringify
var json = JSON.stringify(obj);
//use fs to write the file to disk
var fs = require('fs');
fs.writeFile('myjsonfile.json', json, 'utf8', callback);
if you want to append it read the json file and convert it back to an object
fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
if (err){
console.log(err);
} else {
obj = JSON.parse(data); //now it an object
obj.table.push({id: 2, square:3}); //add some data
json = JSON.stringify(obj); //convert it back to json
fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back
}});
Complete Code:
// POST to add a task
app.post('/task', function(req, res) {
res.set('Content-Type', 'application/json')
var obj = {
table: []
};
obj.table.push({id: req.params.id , square: req.params.square});
var json = JSON.stringify(obj);
var fs = require('fs');
fs.writeFile('myjsonfile.json', json, 'utf8', callback)
fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
if (err){
console.log(err);
} else {
obj = JSON.parse(data); //now it an object
obj.table.push({id: 2, square:3}); //add some data
json = JSON.stringify(obj); //convert it back to json
fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back
// returns 201 on success
res.json({
code: 201,
message: 'Success'
});
}});
});

Ajax GET Requests With wildcards

I'm trying to send an Ajax request in HTML to fetch an object in a JSON file. here is my code in HTML:
<!DOCTYPE html>
<html>
<head>
<title>JSON Server Test</title>
<script type="text/javascript">
var findData = (id) => {
$('.submit-button').on('click', (e) => {
e.preventDefault();
console.log('submit button pressed');
var data = {};
data.title = "title";
data.message = "message";
$.ajax({
type: 'GET',
data: JSON.stringify(data),
contentType: 'application/json',
url: 'localhost:3000/people?id=' + id,
success: (data) => {
console.log('success');
console.log(JSON.stringify(data));
}
});
});
};
</script>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
var findData = (id) => {
$('.submit-button').on('click', (e) => {
e.preventDefault();
console.log('submit button pressed');
var data = {};
data.title = "title";
data.message = "message";
$.ajax({
type: 'GET',
data: JSON.stringify(data),
contentType: 'application/json',
url: 'localhost:3000/people?id=' + id,
success: (data) => {
console.log('success');
console.log(JSON.stringify(data));
document.getElementById('final-data').innerHTML
= JSON.stringify(data);
}
});
});
};
</script>
<input id="input" type="number">
<button class="submit-button"
onclick="findData(getElementById('input').value)">Find
Person</button>
<p id="final-data"></p>
</body>
</html>
And here is my NodeJS code:
const express = require('express');
var app = express();
app.get('/', (req, res) => {
res.sendFile(__dirname + "/" + "index.html");
});
app.listen(4000, () => {
console.log('Listening on port 4000');
});
The actual server itself is running on a localhost on port 3000 using a json-server on a cmd.
json-server --watch db.json
The problem is when I actually press the "Submit" button in the frontend, nothing gives back a response. No console logging, no actual change in the paragraph element in the HTML, nothing.
EDIT: I did manage to do it, it works, but one more thing: I am getting an array with the data, but I want to break it so I get every property alone. How do I do that?

Ajax post response returns empy object

I have recently started using Node.js and jQuery and I can't figure out what's wrong in my project.
I have a client application that sends a post request to a node js server; this server gets the datas from the post and performs a query; finally it should send back to the client a json containing the informations retrieved from the previous query. The problem is that the response sent by node js is an empty object( {} ) and I don't know why.
Here my source code:
Node JS:
var http = require("http");
var url = require('url');
var querystring = require('querystring');
var express = require('express');
var cookieParser = require('cookie-parser');
var mysql = require('mysql');
var con = mysql.createConnection({
host: "",
user: "",
password: "",
database : ''
});
var app = express();
app.use(express.static(__dirname + '/public'))
.use(cookieParser());
app.post('/search',function(req, res) {
if (req.method == 'POST') { //PUT Only
var body = '';
req.on('data', function (data){body += data;});
req.on('end', function () {
var post = querystring.parse(body);
console.log("Dati in ingresso > " + JSON.stringify(post));
//res.writeHead(200, {'Content-Type': 'text/plain'})
query("SELECT Nome FROM Mood WHERE Nome LIKE \'" + post.data + "%\'",res);
});
}else{
console.log("Not POST request")
res.end();
}
});
var query = function(q,res) {
var results = {};
con.query(q, function (err, result, fields) {
if (err) throw err;
results = JSON.stringify(JSON.parse(JSON.stringify(result))[0].Nome);
console.log("Risultati query: ");
console.log(results);
});
res.json(results);
res.end();
}
app.listen(8888);
Client:
$("document").ready(function () {
$('#search-box').on('input propertychange', function(e){
var input = $(this).val();
var array = ['prova1','prova2','prova3'];
var ul = $('#results-options ul');
$.ajax({
type: "POST",
url: "/search",
data: {data : input},
contentType: "application/json",
success: function(d) {
console.log(d);
console.log(JSON.stringify(d));
console.log(JSON.parse(d));
},
error: function(d) {
console.log("Error");
}
});
$('#results-options').show();
});
$("#results-options").on('click',function (e) {
$('this').show();
e.stopPropagation();
})
$(document).on('click', function(){
$('#results-options').hide();
})
});
As I stated above, your query function is sending back a response before the query to the database has finished. That's why it is coming back empty. I moved the res.json(results); res.end(); code inside the callback of the DB query.
var query = function(q,res) {
var results = {};
con.query(q, function (err, result, fields) {
if (err) throw err;
results = JSON.stringify(JSON.parse(JSON.stringify(result))[0].Nome);
console.log("Risultati query: ");
console.log(results);
// I moved the code here
res.json(results);
res.end();
});
// Your old code
// res.json(results);
// res.end();
};

How call a service wrote with node js form angular

I've wrote this service using node, it works but i don't know how to call it from an angularjs controller, i nedd to call the post method
this is the service:
var app = require('express')();
var http = require('http').Server(app);
var mysql = require('mysql');
var bodyParser = require("body-parser");
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'repositorio',
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/',function(req,res){
var data = {
"error":1,
"Usuarios":""
};
connection.query("SELECT * from usuario",function(err, rows, fields){
if(rows.length != 0){
data["error"] = 0;
data["Usuarios"] = rows;
res.json(data);
}else{
data["Usuarios"] = 'Usuarios no encontrados..';
res.json(data);
}
});
/*var data = {
"Data":""
};
data["Data"] = "Welcome to Book Store DEMO...";
res.json(data);*/
});
app.post('/usuario',function(req,res){
var Email = req.query.correo;
var Password = req.query.contrasena;
var Nombres = req.query.nombres;
var Apellidos = req.query.apellidos;
var Usuario = req.query.usuario;
var data = {
"error":1,
"Usuario":""
};
console.log("Email: "+Email+" Password "+Password+" Nombres "+Nombres+" Apellidos "+Apellidos+" Usuario"+Usuario);
if(!!Email && !!Password && !!Nombres && !!Apellidos && !!Usuario){
var user ={usu_correo: Email,usu_contrasena: Password,usu_nombres:Nombres,usu_apellidos: Apellidos,usu_usuario:Usuario}
connection.query('INSERT INTO usuario SET ?',user,function(err, rows, fields){
if(!!err){
data["Usuario"] = "Error Adding data";
}else{
data["error"] = 0;
data["Usuario"] = "Usuario adicionado con éxito";
}
res.json(data);
});
}else{
data["Usuario"] = "Please provide all required data";
res.json(data);
}
});
http.listen(8080,function(){
console.log("Connected & Listen to port 8080");
});
and this is me trying to connect it with angular, i need help please
var app = angular.module('el_acorde_web', []);
app.controller('usuarioscontroller', function($scope, $http)
{
$scope.usuario = {};
$scope.usuario.correo = "davidstl5#gmail.com";
$scope.usuario.nombres = "David Fernano";
$scope.usuario.apellidos = "Sotelo";
$scope.usuario.contrasena = "lakjsdlfkja";
$scope.usuario.usuario = "davidstl5";
$scope.registrar = function(){
$http.post('http://localhost:8080/usuario', $scope.usuario)
.success(function(data)
{
alert(data);
})
.error(function(data)
{
alert('Error:' + data);
});
}
});
Your code looks fine, can I see the HTML code where you are calling the registrar function? Looks like you only have to add the ng-click directive if everything else is working, and for a best practice I would create a factory or a service and call a function there that interacts with the Node app.
I found the solution!
Chrome is the problem we install https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en
and then use:
$scope.registrar = function(){
alert("Entre");
/*$http.post('http://localhost:8080/usuario', $scope.usuario)
.success(function(data)
{
alert(data);
})
.error(function(data)
{
alert('Error:' + data);
});*/
var datos = {correo: $scope.usuario.correo, contrasena: $scope.usuario.contrasena,
nombres:$scope.usuario.nombres, apellidos: $scope.usuario.apellidos,
usuario: $scope.usuario.usuario};
var request = $http({
method: "POST",
url: "http://localhost:8080/usuario",
data: datos,
headers: { 'Content-Type': 'multipart/form-data', 'Authorization': 'Basic ' + btoa(datos),
'Access-Control-Allow-Origin': "*"}
});
request.success(
function( data ) {
alert(data);
}
);
request.error(
function( data ) {
alert(data);
}
);
}
and everything works!

how can i send html form data to node.js server by making ajax call?

I want to send form data to node.js server using Ajax and I am fallowing the below approach to send data.
I am not getting how receive it in node.js server program I am not using express framework for node.js
client.HTML
<script>
function myFunction() {
var region = document.getElementById("region").value;
var os = document.getElementById("os").value;
var data = {};
data.region = region;
data.os = os;
$.ajax({
type: 'post',
datatype: 'jsonp',
data: JSON.stringify(data),
contentType: 'application/json',
url: 'http://127.0.0.1:8083/', //node.js server is running
success: function(data) {
alert("success");
}
});
</script>
<form>
<select id="region" name="region" class="region"></select>
<select id="os" name="os" class="os"></select>
<input type="button" value="search" class="fil_search" onclick="myFunction()"/>
</form>
server.js
var http = require('http');
var fs = require('fs');
var url = require('url');
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert')
var ObjectId = require('mongodb').ObjectID;
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var result1=[];
var result2=[];
var result3=[];
var result4=[];
var result5=[];
var result6=[];
var result7=[];
var i=0;
var region;
var os;
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect("mongodb://192.168.1.22:27017/test", function(err, db) {
if(err) { return console.dir(err); }
else {
app.get('/',function(req, res) {
var url_parts = url.parse(req.url, true);
var url_parsed = url.parse(req.url, true);
"i want data here from ajax to perform"
console.log("connected");
var instance = db.collection('instance');
var region = db.collection('region');
region.findOne(({$and: [{"region_name": region_name},{"os_type": os}]}), function(err, result){
if(err){
throw(err);
}
else{
console.log(region);
var newr = result.inst_name;
instance.find({ "inst_id": { "$in": newr } }).toArray(function(err, resultn){
if(err){
throw(err);
}
else{
var len=resultn.length;
console.log(resultn);
console.log(len);
for(var i=0;i<len;i++)
{
result1[i]=resultn[i].inst_type;
result2[i]=resultn[i].vcpu;
result3[i]=resultn[i].memory_gib;
result4[i]=resultn[i].storage;
result5[i]=resultn[i].phy_processor;
result6[i]=resultn[i].clock_spd;
result7[i]=resultn[i].netwk_pef;
}
var wstream = fs.createWriteStream('myOutput.txt');
wstream.write(result1.toString()+"~"+result2.toString());
//var str = "Hi man"
res.writeHead(200, {'Content-Type':'text/html'});
//res.end(url_parsed.query.callback+'("'+resultn.toString()+'")');
res.end(url_parsed.query.callback+'("'+result1.toString()+"~"+result2.toString()+"~"
+result3.toString()+"~"+result4.toString()+"~"+result5.toString()+"~"+result6.toString()
+"~"+result7.toString()+'")');
}
});
}
});
}).listen(process.env.PORT || 8083);
}
});
I am not getting how to receive data in node.js server program and after receiving data I want process on that data and send back processed data to same HTML page.
If you have app.use(bodyParser.urlencoded({ extended: true })); in your server.js file then using bodyParser you can retrieve data from ajax as given below:
app.post('/', function(req, res) { //your ajax should also post to url: '/'
var region = req.body.region,
os = req.body.os;
// ...
});

Categories

Resources