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};
}
Related
I'm trying to dynamically change <input type="number" name="SLACost" readonly> based on <select name="SLATerm"> option
A table (in DB) that contains:
SLATerms.
SLACost.
SLADeduction
that should be fetched in the "Add new KPI Invoice" form.
I created a function in the controller to fetch the data as json:
/**
** KPI API
**/
public function fetchSLA()
{
$kpiTerms = KPITerms::all();
return response()->json([
'SLATermData' => $kpiTerms, // SLATermData is the name that will be used in Ajax.
]);
}
created a url for ajax to fetch in the web.php as Route::get('kpi/fetch/sla', 'fetchSLA')->name('kpi.fetchSLA'); // The API for fetching SLA as json
Then went ahead and created the ajax request GET
function fetchSLA() {
$.ajax({
type: 'GET',
url: "/management/kpi/fetch/sla",
dataType: 'json',
success: function (response) {
// console.log(response.SLATermData);
$("select[name='SLATerm']").change(function() {
$("input[name='SLACost']").val(response.SLATermData);
});
}
});
}
Obviously, SLATermData will fetch the entire data as json and print it in the SLACost input, it shows as [onject object object]
I tried to do this:
$("select[name='SLATerm']").change(function() {
$("input[name='SLACost']").val(response.SLATermData.SLACost);
});
I thought that adding SLACost after response.SLATermData will do the trick.
What's missing here?
So I made an ajax request to both SLATerm and SLACost and looped through the requested data. Then I made an if statement within the loop to change the SLACost based on the SLATerm selected.
function fetchSLA() {
$.ajax({
type: 'GET',
url: "/management/kpi/fetch/sla",
dataType: 'json',
success: function (response) {
$.each(response.SLATermData, function (key, value) {
$("select[name='SLATerm']").change(function() {
if ( $("select[name='SLATerm']").val() == value.SLATerm ) {
$("input[name='SLACost']").val(value.SLACost);
}
});
});
}
});
}
And here is the Laravel controller for the API:
/**
** KPI API
**/
public function fetchSLA()
{
$kpiTerms = KPITerms::get(['SLATerm' => 'SLATerm', 'SLACost' => 'SLACost']);
return response()->json([
'SLATermData' => $kpiTerms, // SLATermData is the name that will be used in Ajax.
]);
}
Now That I got it working, I'm trying to figure out how to clean the code.
As CBroe mentioned in the comments:
you should rather change your API - requesting all the data over and
over again
Which I am trying to do.
I am using Yii2 framework I need to send an array containing id of person and an array of id of groups from client to server.
I got the data from a Select2 component using jQuery. Then the server will response so the client can show it in a form. I mean it is not a Create or Update button of Yii2.
The client side send this json object:
var jsonData = {
persons: 111,
groups: [222, 333]
};
$.ajax({
url: "/persons/persons?idsGroups=",
data: jsonData,
dataType: 'json',
success: function(res) {
console.log(JSON.stringify(res, null, 4));
}
});
From ther server I need to get the groups but it doens't work:
public function getMyGroups($groups) {
return $groups;
}
My browser shows:
error{"readyState":4,"responseText":"Bad Request (#400): Invalid data received for parameter \"groups\".","status":400,"statusText":"Bad Request"}
But if I change the getMyGroups function to get the persons variable, it works:
public function getMyGroups($persons) {
return $persons;
My browser shows:
111
So what this error means? I think I am sending data in a wrong way but I don't know how to fix it.
I resolved in this way using this help: https://api.jquery.com/jquery.post/
var jsonData = {
'persons': 111,
'groups[]': [222, 333]
};
$.post("/persons/persons", jsonData)
.done(function(data) {
console.log("Data loaded: " + data);
});
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:
I'm trying to get all my posts from the database to be displayed with the help of ajax or getjson but can't get it to work. Using mvc web api and I have a view where I want to display it. There is a method working called post so nothing wrong with my routing etc.
Code for my views js-script, I want to display all posts with the help of my mvc api controller and ajax in a div called #userMessage.
$(document).ready(function() {
$('#btnGetPosts').click(function() {
jQuery.support.cors = true;
var recieverID = $('#RecieverID').val();
$.ajax({
url: "/api/Posts/GetPosts" ,
//data: (?)
type: "GET",
dataType: "jsonp",
error: function(request, status, error) {
alert(request.responseText);
},
success: function(data) {
alert(data);
}
});
});
});
my controller method to get all the posts
// GET: api/Posts
public IEnumerable<Post> GetPosts()
{
//querystring is made to get the recieverID, it's also reachable in the view. //("#RecieverID")
string querystring = HttpContext.Current.Request.QueryString["Username"];
// Converts Username querystring to a user-id
int id = UserRepository.GetUserId(querystring);
// uses linq to get a specific user post (all posts)
var userPost = PostRepository.GetSpecificUserPosts(id);
return userPost;
}
my PostRepository.GetSpecifiedUserPosts method in my repository
public List<Post> GetSpecificUserPosts(int user)
{
using (var context = new DejtingEntities())
{
var result = context.Posts
.Where(x => x.RecieverID == user)
.OrderByDescending(x => x.Date)
.ToList();
return result;
}
Try this
$(document).ready(function() {
$('#btnGetPosts').click(function() {
jQuery.support.cors = true;
var recieverID = $('#RecieverID').val();
$.ajax({
url: "/api/Posts/Posts" ,
data: {
username: recieverID
},
type: "GET",
dataType: "jsonp",
error: function(request, status, error) {
alert(request.responseText);
},
success: function(data) {
alert(data);
}
});
});
});
and in code behind,
public IEnumerable<Post> GetPosts(string username)
{
// Converts Username querystring to a user-id
int id = UserRepository.GetUserId(username);
// uses linq to get a specific user post (all posts)
var userPost = PostRepository.GetSpecificUserPosts(id);
return userPost;
}
You use wrong url. Try send ajax request to '/api/Posts'.
Also you can add routing attribute to the action [Route('/api/Posts/GetPosts')] and send request to '/api/Posts/GetPosts'.
See Calling the Web API with Javascript and jQuery and Routing in ASP.NET Web API.
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 () {}
});