get the parmeter from ajax to node.js to mongoDB - javascript

i have this problem when i try to do some test by clicking a button which call a JavaScript function that does an ajax call and pass a parameter to my node.js server(express) which save it to my mongoDB.
the problem is that all the time i see the value in the DB as null, after researching i found that the problem is how to get the parameter "name" and read it on the node.js side
i try req.body.name or req.query.name but stil nothing..
hope you can help me,
maybe its in my code or syntax problem, wait for your help
java script code :
function savePre()
{
var parameters = { name: 'test' };
$.ajax({
url: '/savePre',
type: 'POST',
data: JSON.stringify(parameters),
success: function () {},
dataType: 'json'
});
}
node.js code (in the index.js code) :
exports.savePre = function(db) {
return function(req, res) {
// Get our form values. These rely on the "name" attributes
var json = req.query.name;
// Set our collection
var collection = db.get('PresentationCollection');
// Submit to the DB
collection.insert({
"JsonToSave": json
}, function (err, doc) {
if (err) {
// If it failed, return error
res.send("There was a problem adding the information to the database.");
}
});
}
}

Your client side code can be improved without JSON.stringify:
$.ajax({
url: '/savePre',
type: 'POST',
data: parameters,
success: function () {}
});

Related

Passing a query parameter from an AJAX get call to an express route

I'm playing around with a twitter API wrapper for Node right now and am trying to figure out how to pass a query parameter from an HTML form to an AJAX get request and have that parameter then passed into my Express route, rather than just having the form action go directly to the route.
Here's my HTML code
<form id="searchTerm">
Keyword:<input id="keyword" type="text" name="q" placeholder="Keyword">
<input type="submit">
</form>
My client-side Javascript
$(document).ready(function() {
$('#searchTerm').on('submit', function() {
$.ajax({
type: 'GET',
data: q,
url: '/search/tweets/term',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
});
});
And then my Node.JS route:
// Search by keywords or phrases
app.get('/search/tweets/term', function(req, res) {
var q = req.query.q;
// Accesses the Twitter API and pulls back the respective tweets
client.get('search/tweets', {q: q, count: 100, lang: 'en', exclude: 'retweets'}, function(error, tweets, response) {
if(!error) {
res.send(tweets);
} else {
console.log(error);
res.status(500).send(error.stack);
}
});
});
I'm getting a "Query Missing Parameters" error message in my terminal whenever I input a value into the form, however. Not sure what I'm doing wrong.
UPDATE
Got it working via the following:
$(document).ready(function() {
$('#searchTerm').on('submit', function(e) {
e.preventDefault();
var q = $('#keyword').val();
$.ajax({
type: 'GET',
data: {q: q},
url: '/search/tweets/term',
success: function(data) {
console.log(data);
}
})
})
})
However, since I'm implementing e.preventDefault(), I'm losing the query parameters within my URL. Since I want to give users the ability to share URL's to specific keywords, is there any way to be able to keep these parameters intact in the URL while still getting the JSON sent client side? Or will have to just manipulate the JSON on the server side and have the data be rendered in via a template engine?
Try this
$(document).ready(function() {
$('#searchTerm').on('submit', function() {
$.ajax({
type: 'GET',
data: q,
url: '/search/tweets/term?q=',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
});
});

Third parameter of $.post() is not working

I am sending a post request to the REST web service using the following code:
<script type="application/javascript">
$(document).ready(function() {
$("#logbutton").click(function(event){
$.post(
"http://localhost:8080/CredentialsOnDemand/loginexpert/dologin",
{
ephone: $("#mobile").val(),
epassword: $("#password").val()
},
function(data) {
data = $.parseJSON( data );
$(".ray").html("$" + data.tag);
console.log( "You clicked a paragraph!" );
}
);
});
});
The web service gives a JSON response in format below:
{"tag":"login","status":true}
The call from the jquery code is running i.e. the web service is running fine, but the function that I have created to parse JSON is not working.
NOTE:
I tried to run this code without providing any value in the text field. The console displayed the json response and also console.log line. But when I again entered the values into the fields, then it didn't. I am unable to understand this thing.
Anyone having any idea?
Thanks in advance.
You could try the more verbose and detailed form using $.ajax:
$(document).ready(function() {
$("#logbutton").click(function(event) {
var req = {
ephone: $("#mobile").val(),
epassword: $("#password").val()
};
$.ajax({
url: "http://localhost:8080/CredentialsOnDemand/loginexpert/dologin",
data: req,
dataType: 'json',
type: 'POST'
}).done(function(data) {
console.log(data);
$(".ray").html("$" + data.tag);
console.log("You clicked a paragraph!");
}).fail(function(err) {
console.error(err);
});
});
});
This will be easier for you to pinpoint where the error is coming from

creating jquery custom object

In asp I have a function as:
public async Task<IHttpActionResult> updateComment(int id, Comment comment)
{
//some stuff
}
To send data to this function I have created an ojbect as (I am working with knockout.js):
var com = {
id: self.id,
description: self.description,
postedBy: self.postedById,
time: new Date($.now()),
adId: self.adId,
};
And in ajax request I am sending data as:
$.ajax({
url: '/api/Comment/updateComment',
dataType: "json",
contentType: "application/json",
cache: false,
type: 'POST',
data: { id: com.id, comment: com },
success: function (data) {
alert("done");
},
error: function () {
alert("error");
}
});
But request does not goes to above asp.net function. I got error in browser console window 404 (Not Found) . Error is because it is not receiving comment object as it was expecting. I changed ajax request method to get to see url and url is below.
Is there something wrong with my defined com function? Why its not working?
Update:
public async Task<IHttpActionResult> updateComment()
{
//some stuff
}
I changed the function as above and its working fine. So it is confirmed that is some problem with com object. Function is not receiving object as it was expecting.
Update 2:
Now I changed function parameters to:
public async Task<IHttpActionResult> updateComment(Comment comment)
{
//some stuff
}
and send data as:
data: ko.toJSON(com),
and its again working fine!
error code is 405:Method not allowed i guess this is something like, your ajax is type:"Post" request but your backend is expecting some GET requests.
Another suggestion is that you can send a stringified object with this:
data : '{ "id":"' + com.id + '", "comment":"' + com + '"}',
If you are using ajax post with two parameters class object and other type you need to create other obj like below:
Note: Make sure that all properties of com object are same like your Comment class.
var com = {
id: self.id,
description: self.description,
postedBy: self.postedById,
time: new Date($.now()),
adId: self.adId,
};
var obj = {};
obj.id = com.id;
obj.comment = com;
And pass data using JSON.Stringy(obj) like below:
data: JSON.stringify(obj),
I had tested the code it is working check below screen shot:

HttpClient PostAsync equivalent in JQuery with FormURLEncodedContent instead of JSON

I wrote a JQuery script to do a user login POST (tried to do what I have done with C# in the additional information section, see below).
After firing a POST with the JQuery code from my html page, I found the following problems:
1 - I debugged into the server side code, and I know that the POST is received by the server (in ValidateClientAuthentication() function, but not in GrantResourceOwnerCredentials() function).
2 - Also, on the server side, I could not find any sign of the username and password, that should have been posted with postdata. Whereas, with the user-side C# code, when I debugged into the server-side C# code, I could see those values in the context variable. I think, this is the whole source of problems.
3 - The JQuery code calls function getFail().
? - I would like to know, what is this JQuery code doing differently than the C# user side code below, and how do I fix it, so they do the same job?
(My guess: is that JSON.stringify and FormURLEncodedContent do something different)
JQuery/Javascript code:
function logIn() {
var postdata = JSON.stringify(
{
"username": document.getElementById("username").value,
"password": document.getElementById("password").value
});
try {
jQuery.ajax({
type: "POST",
url: "http://localhost:8080/Token",
cache: false,
data: postdata,
dataType: "json",
success: getSuccess,
error: getFail
});
} catch (e) {
alert('Error in logIn');
alert(e);
}
function getSuccess(data, textStatus, jqXHR) {
alert('getSuccess in logIn');
alert(data.Response);
};
function getFail(jqXHR, textStatus, errorThrown) {
alert('getFail in logIn');
alert(jqXHR.status); // prints 0
alert(textStatus); // prints error
alert(errorThrown); // prints empty
};
};
Server-side handling POST (C#):
public override async Task ValidateClientAuthentication(
OAuthValidateClientAuthenticationContext context)
{
// after this line, GrantResourceOwnerCredentials should be called, but it is not.
await Task.FromResult(context.Validated());
}
public override async Task GrantResourceOwnerCredentials(
OAuthGrantResourceOwnerCredentialsContext context)
{
var manager = context.OwinContext.GetUserManager<ApplicationUserManager>();
var user = await manager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError(
"invalid_grant", "The user name or password is incorrect.");
context.Rejected();
return;
}
// Add claims associated with this user to the ClaimsIdentity object:
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
foreach (var userClaim in user.Claims)
{
identity.AddClaim(new Claim(userClaim.ClaimType, userClaim.ClaimValue));
}
context.Validated(identity);
}
Additional information: In a C# client-side test application for my C# Owin web server, I have the following code to do the POST (works correctly):
User-side POST (C#):
//...
HttpResponseMessage response;
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>( "grant_type", "password"),
new KeyValuePair<string, string>( "username", userName ),
new KeyValuePair<string, string> ( "password", password )
};
var content = new FormUrlEncodedContent(pairs);
using (var client = new HttpClient())
{
var tokenEndpoint = new Uri(new Uri(_hostUri), "Token"); //_hostUri = http://localhost:8080/Token
response = await client.PostAsync(tokenEndpoint, content);
}
//...
Unfortunately, dataType controls what jQuery expects the returned data to be, not what data is. To set the content type of the request data (data), you use contentType: "json" instead. (More in the documentation.)
var postdata = JSON.stringify(
{
"username": document.getElementById("username").value,
"password": document.getElementById("password").value
});
jQuery.ajax({
type: "POST",
url: "http://localhost:8080/Token",
cache: false,
data: postdata,
dataType: "json",
contentType: "json", // <=== Added
success: getSuccess,
error: getFail
});
If you weren't trying to send JSON, but instead wanted to send the usual URI-encoded form data, you wouldn't use JSON.stringify at all and would just give the object to jQuery's ajax directly; jQuery will then create the URI-encoded form.
try {
jQuery.ajax({
type: "POST",
url: "http://localhost:8080/Token",
cache: false,
data: {
"username": document.getElementById("username").value,
"password": document.getElementById("password").value
},
dataType: "json",
success: getSuccess,
error: getFail
});
// ...
To add to T.J.'s answer just a bit, another reason that sending JSON to the /token endpoint didn't work is simply that it does not support JSON.
Even if you set $.ajax's contentType option to application/json, like you would to send JSON data to MVC or Web API, /token won't accept that payload. It only supports form URLencoded pairs (e.g. username=dave&password=hunter2). $.ajax does that encoding for you automatically if you pass an object to its data option, like your postdata variable if it hadn't been JSON stringified.
Also, you must remember to include the grant_type=password parameter along with your request (as your PostAsync() code does). The /token endpoint will respond with an "invalid grant type" error otherwise, even if the username and password are actually correct.
You should use jquery's $.param to urlencode the data when sending the form data . AngularJs' $http method currently does not do this.
Like
var loginData = {
grant_type: 'password',
username: $scope.loginForm.email,
password: $scope.loginForm.password
};
$auth.submitLogin($.param(loginData))
.then(function (resp) {
alert("Login Success"); // handle success response
})
.catch(function (resp) {
alert("Login Failed"); // handle error response
});
Since angularjs 1.4 this is pretty trivial with the $httpParamSerializerJQLike:
.controller('myCtrl', function($http, $httpParamSerializerJQLike) {
$http({
method: 'POST',
url: baseUrl,
data: $httpParamSerializerJQLike({
"user":{
"email":"wahxxx#gmail.com",
"password":"123456"
}
}),
headers:
'Content-Type': 'application/x-www-form-urlencoded'
})
})

How can we post data using meteor restivus

I am developing API using meteor restivus package and i want to post data and want to save in database. i have done following coding but not able to get posted data at api call.
// made post api using restivus
Restivus.configure({
useAuth: false,
prettyJson: true
});
Restivus.addRoute('addorder', {authRequired: true}, {
post:{
action: function (data) {
console.log(data); // undefined
return {status: "success", data: "test"};
}
}
});
above api i am calling using server side method for that i have done following coding.
Meteor.methods({
apiInsert:function (name){
this.unblock();
console.log("api insert method");
var url = "http://localhost:3000/api/addorder";
var result = HTTP.post(url,{
data: { "name": name },
headers:{
"content-type":"application/json ; charset=UTF-8",
}
});
But i am not getting posted data at api function i am getting undefined in data variable. i dont know how to retrieve posted data at api function.
Try using this.bodyParams.
post: {
action: function () {
return {status: 'success', data: this.bodyParams};
}

Categories