passing variable from jQuery ajax to nodejs - javascript

i am trying to pass a variable from jQuery to nodejs, but i am not getting the right results, nodejs returns [object Object]. how can it return a string variable on nodejs side.
$('.test').click(function(){
var tsId = "Hello World";
alert(tsId);
console.log(tsId);
$.ajax({
'type': 'post',
'data':tsId,
'url': '/test/testing',
'success': function (data) {
alert(data);
}
})
});
router.post('/testing', function(req, res) {
var tsID = req.body;
console.log("stsID "+tsID );\\ outputs [object Object]
});

I recommend you to use this way:
You should pass an object in ajax data, which contains your Hello World string.
$.ajax({
type: 'post',
data:{str:tsId},
url: '/test/testing',
success: function (data) {
alert(data);
}
});
In node.js file use this:
router.post('/testing', function(req, res) {
var tsID = req.body;
console.log("stsID "+tsID.str );
});

Try console logging tsID.data or tsID.tsId. What do you get? What do you get if you throw a debugger before your console log and write "tsID" in the console?

Related

how to pass data to ajax for an express api call

I'm developing a website with express and ejs. I got into a trouble where i need to call an api via ajax. The problem is on a button onclick i'm passing two values to ajax data. but it gives error ,i tried a lot of ways and i'm messed up. i'm a newbie , find my code below.
const parsedData = JSON.parse(localStorage.getItem('myData'));
const container = document.getElementById('s1');
parsedData.data.rows.forEach((result, idx) => {
var a = result.master_id;
var b = result.session_name;
console.log(a,b,"a","b")
var userData = {"pid":a,"session" :b};
console.log(userData,"userData");
sessionStorage.setItem("user", JSON.stringify(userData));
console.log(userData,"data for api");
const card = document.createElement('div');
card.classList = 'card';
const content = `
<div class="row">
<div class="card-body" onclick="graphApi()">
</div>
</div>
`;
container.innerHTML += content;
});
function graphApi(){
var apiValue =JSON.parse( sessionStorage.getItem("user"));
console.log(apiValue, "value from card");
$.ajax({
type: "POST",
data: apiValue,
dataType:"json",
url: "http://localhost:5000/graphFromcsv",
success: function(data) {
console.log(data,"graph api");
}
error: function(err){
alert("graph api failed to load");
console.log(err);
},
});
i'm always getting this pid in api value undefined and 400 badrequest . but if i use raw data like,
{
"pid":"WE6",
"session":"W.csv"
}
instead of apiValue my ajax is success and i'm gettig the data. i'm using this data to plot a multiple line graph. Any help is appreciated.
You need to correct data key and their value(value must be string in case of json data) and also add contentType key like
$.ajax({
type: "POST",
data: sessionStorage.getItem("user") || '{}',
dataType: "json",
contentType: "application/json",
url: "http://localhost:5000/graphFromcsv",
success: function (data) {
console.log(data, "graph api");
},
error: function (err) {
alert("graph api failed to load");
console.log(err);
},
});
Note: In backend(ExpressJS), make sure you are using correct body-parser middleware like app.use(express.json());
Let assume your apiValue contain {"pid":"WE6", "session":"W.csv" } then body: { apiValue } will be equal to:
body: {
apiValue: {
"pid":"WE6",
"session":"W.csv"
}
}
But if you use the link to the object like body: apiValue (without brackets) js will build it like:
body: {
"pid":"WE6",
"session":"W.csv"
}

Can not get item of JSON-response

I am trying to create a AJAX call - and I would like to work with the response.
This is my response I see in my browser's network console:
{
"message": "success",
"file": "dump.xml"
}
And this is what I want to do:
onComplete: function onComplete(data) {
var vm = this;
console.log(data.file);
this.$set('upload', data);
this.$set('filename', file);
this.modal.show();
}
Okay. Well - I'm getting a response and if I write data to console.log, I'm getting this:
{"message":"success","file":"dump.xml"}
But if I try to do:
console.log(data.file);
I'm getting undefined. But why?
You are receiving it as a string. You have to parse it first to JSON by:
data = JSON.parse(data);
console.log( data.file )
OTHER OPTION: Or you can define it on request, add dataType: "json" so that you will receive json.
Like:
$.ajax(
{
type: "POST",
dataType: "json",
url: url,
data: {},
success: function( response ) {}
}
I think the problem is that data is a JSON string, so it will be printed in console, but when you call data.file it will be undefined. as string doesn't have a file property.
You need to parse your data object, before accessing file property:
data = JSON.parse(data);
console.log(data.file);
Most probably your data will be a JSON string. You have parse it into an Object like below
onComplete: function onComplete(data) {
data = JSON.parse(data)
var vm = this;
console.log(data.file);
this.$set('upload', data);
this.$set('filename', file);
this.modal.show();
}

nodejs, jquery ajax, the format conversion of the transfer and receiving objects

for example
the ajax to send a obj to node js router '/test'
var obj =new object();
obj.a='a';
obj.b='b';
$.ajax({
url:"/test",
type:"POST",
data:{
obj:obj
},success:function(){
},error:function(){
}
});
the '/test' router receiving obj:
router.post('/test',function(req, res, next){
for(var key in req.body){
console.log(key);
console.log(req.body[key]);
}
res.end();
});
This object is automatically convert to a different format
{
'obj[a]':'a',
'obj[b]':'b'
}
the key is not 'a', is convert to 'obj[a]'
How can I receive or send correctly?
like this:
the console.log(req.body.obj); is:
{
a:a,
b:b
}
I think you just want to pass data: obj to $.ajax(), not data: {obj: obj}. You are the one nesting it in another object that you don't want.
$.ajax({
url:"/test",
type:"POST",
data:obj,
success:function(){
}, error:function(){
}
});
Also, note that you will need some middleware to properly parse this back into JSON on your server. Otherwise, it will just be a string.
Create your object like this:
var obj = {
a:'a',
b:'b'
};
$.ajax({
url:"/test",
type:"POST",
data:obj,
success:function(){
},error:function(){
}
});

Getting an AJAX GET request to work with Express.js

I am using node.js and Express.js on the back end, and am trying to make a server call from the client via AJAX.
So I have this POST request that works fine with AJAX:
node.js/Express.js:
app.post('/createNewThing', function(req, res) {
var userInput = req.body.userInput;
if (userInput) {
res.send('It worked!');
}
});
Client Side/AJAX request:
var userInputForm = $('#userInputForm.val()')
$.ajax({
url: "/createNewThing",
type: "POST",
data: "userInput=" + userInputForm,
dataType: "text",
success: function(response, status, http) {
if (response) {
console.log('AJAX worked!);
}
}
});
The userInputForm comes from an HTML form.
This POST request works fine. But I want to change this to a GET request. If I change app.post to app.get, and change type in the AJAX call to GET, I get this 500 error:
GET /createNewThing?userInput= 500
When you make a GET request, the data appears in the query string (of the URL in the request headers). It doesn't appear in the request body. There is no request body.
When you try to read from the request body, you are trying to access a property of an undefined object, which triggers an exception and cause an internal server error.
This answer explains how to read a query string:
var id = req.query.id; // $_GET["id"]
So
var userInput = req.query.userInput;
I think var userInputForm = $('#userInputForm.val()') will get error or get wrong data..This may be the reason for the error. Due to userInputForm may not be a string and concatenate with userInput=
Actually it is bad data.
And for the data in ajax, you should modify data from data: "userInput=" + userInputForm,
to:
data: {
userInput: userInputForm
},
dataType: "json"
And var userInputForm = $('#userInputForm.val()')
to var userInputForm = $('#userInputForm').val();
At last, you could modify as bellow, I believe it works:
var userInputForm = $('#userInputForm').val();
$.ajax({
url: "/createNewThing?userInput=" + userInputForm,
type: "GET",
success: function(response, status, http) {
if (response) {
console.log('AJAX worked!);
}
}
});

How can I properly send Objects via AJAX using bodyParser in node.js express?

I'm trying to do:
$.ajax({
type:"POST",
url:"/psychos",
data:JSON.stringify(this.psycho)
})
At server I got:
app.post("/psychos", function(request, response) {
var psychologist = request.body.psycho
console.log(psychologist)
psicologosCollection.insert(psychologist, function(error, responseFromDB) {
if (error) {response.send(responseFromDB)}
console.log("Se ha insertado: "+ JSON.strinfigy(responseFromDB))
response.send(responseFromDB)
})
})
But, the console.log() is printing undefined and got the following throw:
TypeError: Cannot read property '_id' of undefined
at insertWithWriteCommands (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/mongodb/lib/mongodb/collection/core.js:78:13)
at Collection.insert (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/mongodb/lib/mongodb/collection/core.js:30:7)
at Object.handle (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/server.js:117:25)
at next_layer (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express/lib/router/route.js:103:13)
at Route.dispatch (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express/lib/router/route.js:107:5)
at c (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express/lib/router/index.js:195:24)
at Function.proto.process_params (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express/lib/router/index.js:251:12)
at next (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express/lib/router/index.js:189:19)
at next (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express/lib/router/index.js:166:38)
at Layer.session [as handle] (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express-session/index.js:98:29)
I'm using BodyParser before:
var bodyParser = require('body-parser')
app.use(bodyParser())
psycho is actually a valid existing object. At the method where AJAX is performed a console.log(this.psycho) will print my object. What am I doing wrong?
Edit:
Even I found out I should have got:
var psychologist = request.body.psycho
at server GET route code, I can't understand how bodyParser generates an Object?
For a quite similar AJAX call I tried before:
function getSendingJSON(url,reqObject,callBack) {
$.ajax({
type: "get",
data: reqObject,
dataType: "json",
url: url,
success: function(response){
callBack(response);
}
});
}
So response was a JSON, and callback function looked similar to:
function plotReglaFalsa(respuesta) {
if (respuesta.fail) {...}
else if (respuesta.negative) {...}
....
}
Even that was purely at client side, I'm confused how to deal with Objects/JSON serialization and how bodyParser acts for it.
You have not serialized the data in your request, it's still just a JavaScript object until you serialize it as JSON:
$.ajax({
type:"POST",
contentType: "application/json",
url:"/psychos",
data: JSON.stringify( this.pyscho )
})
So call JSON.stringify in order to serialize as JSON and then the body parser has something to parse.
app.post("/psychos", function(request, response) {
//change request.body.psycho to request.body
var psychologist = request.body
console.log(psychologist)
psicologosCollection.insert(psychologist, function(error, responseFromDB) {
if (error) {response.send(responseFromDB)}
console.log("Se ha insertado: "+ JSON.stringify(responseFromDB))
response.send(responseFromDB)
})
})

Categories

Resources