Cant send Object with property that has array of objects - javascript

I'm trying to send an object that looks like this
var postBody = {
id: userID,
objectID: [0, 1],
objects: [
{id: 0, x: 0.33930041152263374, y: 0.08145246913580247, width: 0.0823045267489712, height: 0.30864197530864196},
{id: 1, x: 0.5277777777777778, y: 0.08453888888888889, width: 0.0823045267489712, height: 0.30864197530864196}
]
};
this is ajax call
$.ajax({
type: 'POST',
url: url,
data: postBody,
dataType: 'JSONP',
success: function(data) {
console.log(data);
},
error: function(err) {
console.log(err);
}
});
this is what it looks like on server
{ id: '583f137fc338b517ec467643',
'objectID[]': [ '0', '1' ],
'objects[0][id]': '0',
'objects[0][x]': '0.33930041152263374',
'objects[0][y]': '0.08145246913580247',
'objects[0][width]': '0.0823045267489712',
'objects[0][height]': '0.30864197530864196',
'objects[1][id]': '1',
'objects[1][x]': '0.5277777777777778',
'objects[1][y]': '0.08453888888888889',
'objects[1][width]': '0.0823045267489712',
'objects[1][height]': '0.30864197530864196' }
if I put data: JSON.stringify(postBody) this is what I get
{ '{"id":"583f137fc338b517ec467643","objectID":[0,1],"objects":[{"id":0,"x":0.5,"y":0.5,"width":0.1,"height":0.1},{"id":1,"x":0.5401234567901234,"y":0.1833043209876543,"width":0.0823045267489712,"height":0.30864197530864196}]}': '' }
And it works! but then I cannot JSON.parse() it
this is what I get when I try
TypeError: Cannot convert object to primitive value
and all that Im doing on data on backend is this
console.log(JSON.parse(req.body)); // in the first example it was the same thing but only without JSON.parse()
Anyone have an idea why this is happening here?
Even if you have a suggestion on what I could try feel free to post here, otherwise I'm gonna have to write a function for parsing these badass inputs lol.

All the parsing/stringifying is handled by Node, so don't worry about it, just pass your object as it is, and you'll be able to access its properties in req.body.
client :
$.ajax({
type: 'POST',
url: url,
data: postBody,
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function(err) {
console.log(err);
}
});
server :
console.log(req.body); //should give you [Object object]
you can then send it right back with: res.status(200).json(req.body));
and read it in your ajax callback :
success: function(data) {
console.log(data);
},

Related

Sending Array Object Data in Javascript to ASP.NET Core Controller using AJAX ()

I've tried all other solutions pertaining to the problem, but still can't find what i'm missing for my code. Here's my AJAX() Code.
var group = JSON.stringify({ 'listofusers': listofusers });
console.log("listofusers : " + JSON.stringify({ 'listofusers': group }));
(Assuming I have my listofusers object ready, and yes i've checked the console and it has data inside.)
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: "POST",
url: url,
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
//doSend(JSON.stringify(data));
//writeToScreen(JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
Here's my Server Side Controller.
[HttpPost]
public IActionResult GetMesssage(List<UserModel> listofusers)
{
var g = listofusers;
}
Just a simple fetch from the controller, so I could verify that the data from client side has really been sent.
I've tried the [FromBody] attribute, but still no luck in fetching the data from the server-side.
Here is a working demo like below:
1.Model:
public class UserModel
{
public int Id { get; set; }
public string Name { get; set; }
}
2.View(remove Content-type):
<script>
var listofusers = [
{ id: 1, name: 'aaa' },
{ id: 2, name: 'bbb' },
{ id: 3, name: 'ccc' }
];
var group = { 'listofusers': listofusers };
console.log(group);
$.ajax({
dataType: 'json',
type: "POST",
url: "/home/GetMesssage",
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
</script>
3.Console.log(group):
4.Result:
Update:
Another way by using json:
1.View(change group from JSON.stringify({ 'listofusers': listofusers });
to JSON.stringify(listofusers);):
<script>
var listofusers = [
{ id: 1, name: 'aaa' },
{ id: 2, name: 'bbb' },
{ id: 3, name: 'ccc' }
];
var group = JSON.stringify(listofusers);
console.log(group);
$.ajax({
contentType:"application/json",
dataType: 'json',
type: "POST",
url: "/home/GetMesssage",
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
</script>
2.Controller(add FromBody):
[HttpPost]
public IActionResult GetMesssage([FromBody]List<UserModel> listofusers)
{
//...
}
You can try this one.
First stringify the parameter that you want to pass:
$.ajax({
url: url,
type: "POST",
data: {
listofusers: JSON.stringify(listofusers),
},
success: function (data) {
},
error: function (error) {
}
});
Then in your controller:
[HttpPost]
public IActionResult GetMesssage(string listofusers)
{
var jsonModel = new JavaScriptSerializer().Deserialize<object>(listofusers); //replace this with your deserialization code
}
What we're doing here is passing your object as a string then deserializing it after receiving on the controller side.
Hope this helps.
I found the solution to my problem guys, but I just want a clarification that maybe there's a work around or another solution for this one.
I've studied the data passed by "JSON.stringify();" from AJAX() and it's somehow like this.
"[[{\"ID\":0,\"UserID\":1014,\"Level\":\"support\",\"Department\":\"\",\"Facility\":\"Talisay District Hospital\",\"Firstname\":\"Joseph\",\"Middlename\":\"John\",\"Lastname\":\"Jude\",\"LoginStatus\":false,\"IPAddress\":\"192.168.110.47:12347\"},{\"ID\":0,\"UserID\":1014,\"Level\":\"support\",\"Department\":\"\",\"Facility\":\"Talisay District Hospital\",\"Firstname\":\"Joseph\",\"Middlename\":\"John\",\"Lastname\":\"Jude\",\"LoginStatus\":false,\"IPAddress\":\"192.168.110.47:15870\"}]]"
to which I was wondering that if the JSON format is a factor in parsing the data from the controller side. (Which of course is stupid since there's only one JSON format. (or maybe there's another, if there is, can you please post some source for reference.))
so I tried Serializing a Dummy Data in my model in "JsonConvert.Serialize()" Method and the output JSON data is like this.
[{"ID":0,"UserID":1014,"Level":"support","Department":"","Facility":"Talisay District Hospital","Firstname":"Joseph","Middlename":"John","Lastname":"Jude","LoginStatus":false,"IPAddress":"192.168.110.47:12347"},{"ID":0,"UserID":1014,"Level":"support","Department":"","Facility":"Talisay District Hospital","Firstname":"Joseph","Middlename":"John","Lastname":"Jude","LoginStatus":false,"IPAddress":"192.168.110.47:16709"}]
and I tried sending the output JSON Data from JsonConvert.Serialize() Method to controller via AJAX() and it worked! And I feel so relieved right now as this problem was so frustrating already.
If there's something wrong with what I found, please respond with what might be wrong or correct. Thank you!

How do I get data with an Ajax rest call from an API on my HTML site

I'm trying to build an application with Javascript where I get football/soccer statistics from football-data.org and put the information I want on my HTML Page.
I have been trying to get the information, however I do not know how I should get it with an AJAX call.
$(function (){
var $players = $('#players');
$.ajax({
headers: { 'X-Auth-Token': 'MYAPITOKEN....' },
type: 'GET',
url: 'https://api.football-data.org/v2/competitions/PD/scorers',
dataType: 'json',
success: function(players) {
$.each(players, function(i, player){
$players.append('<li>name: '+ player[3] +', position: '+player.nationality+'</li>');
});
}
});
});
I want to see the player name and postion, however I get this on my html page as a :
name: undefined, position: undefined
name: undefined, position: undefined
name: undefined, position: undefined
name: undefined, position: undefined
name: [object Object], position: undefined
This is what the log says:
Console log Api call
Than you need something like this:
$(function (){
var $players = $('#players');
$.ajax({
headers: { 'X-Auth-Token': 'MYAPITOKEN....' },
type: 'GET',
url: 'https://api.football-data.org/v2/competitions/PD/scorers',
dataType: 'json',
success: function(response) {
$.each(response.scorers, function(i, scorer){
$players.append('<li>name: '+ scorer.player.name +', position: '+scorer.player.nationality+'</li>');
});
}
});
});
They have really good documentation and response example on their site (however the response is not complete, but with console.log(); you can find the missing structure): https://www.football-data.org/documentation/quickstart .
BTW why you write the nationality as a position?

Bootgrid read returned value in JSON

I'm using jQuery bootgrid to display data in table. I get data using Ajax and I return the values in JSON format. On the JSON string it comes a variable I want to read to display in other section out of the table.
Ajax function is the following:
function ajaxAction(action) {
data = $("#frm_"+action).serializeArray();
$.ajax({
type: "POST",
url: "response_pedidos.php",
data: data,
dataType: "json",
success: function(response)
{
$('#'+action+'_model').modal('hide');
$("#employee_grid").bootgrid('reload');
},
error: function (request, error) {
console.log(arguments);
}
}); }
I'm watching response from PHP page and it comes with the following format:
{"current":1,
"rowCount":20,
"total":7,
"cantidad_totales":8.5,
"id_pedido":13,
"rows":[{"id_pedidos_productos" :"57",
"cantidad":"1.5",
"descripcion":"prueba con decimales",
"nombre":"Astro naranja"},
{"id_pedidos_productos":"52",
"cantidad":"1",
"descripcion":"",
"nombre":"Gipso grande"},
{"id_pedidos_productos":"54",
"cantidad":"1",
"descripcion":"",
"nombre":"Lilis Rosita"},
{"id_pedidos_productos":"53",
"cantidad":"1",
"descripcion" :"",
"nombre":"Plumosos"},
{"id_pedidos_productos":"56",
"cantidad":"1",
"descripcion":"",
"nombre":"ROSAS BABY VENDELA"},
{"id_pedidos_productos":"55",
"cantidad":"1",
"descripcion":"",
"nombre":"Rosas rojas"},
{"id_pedidos_productos":"51",
"cantidad":"2",
"descripcion":"",
"nombre":"ROSAS ROSITAS \"MATIZADAS\"" }]}
On the page, my table looks like this, I want to display obtained value in the field below the table:
Now, what I want to do is to read returned value named: "cantidad_totales".
I would like to catch it to display in resume section of the page.
Does anyone know how can I do it ?
This is how you could handle it:
var cantidadTotales;
$('#tbl').bootgrid({
formatters:{
...
},
rowCount: [5, 10, 25],
...
labels: {
....
},
css: {
...
},
responseHandler: function (data) {
var response = {
current: data.current,
rowCount: data.rowCount,
rows: data.rows,
total: data.total,
cantidad_totales: data.cantidad_totales,
id_pedido: data.id_pedido
};
//store cantidad_totales into a variable...
cantidadTotales = data.cantidad_totales;
return response;
},
ajaxSettings: {
method: 'POST',
contentType: 'application/json'
},
ajax: true,
url: 'The_Url_To_Load_Your_Data'
}).on("loaded.rs.jquery.bootgrid", function (s) {
//Now, display the cantidad_totales in your div or whatever
$('div#YourTotalDiv').html(cantidadTotales);
});
})

Why does my JSON data with Ajax not return correctly even though the console logs it?

I am getting a number (1,2,3, etc.) based on coordinates like this:
function getNumber(lat,lng)
{
var params="lat="+lat+"&long="+lng;
$.ajax({
type: "POST",
url: "https://www.page.com/code.php",
data: params,
dataType: 'json',
success: function(data){
if (data.valid==1){
console.log(data);
$("#number").html(data.number);
} else {
console.log(data);
}
},
error: function(){
}
});
}
The problem is, when I check the console, the data is there like this:
[Object]
0 Object
lat: 100.00
long: 50.00
number: 1
etc.
Why doesn't it let me parse it?
The way I return it with POST is:
[{"valid":"1","lat":100.00,"long":50.00,"number":"1"}]
So you are returning an array?
Then you need to refer to the data by index:
data[0].valid==1

JQuery $.ajax() post - data in a java servlet

I want to send data to a java servlet for processing. The data will have a variable length and be in key/value pairs:
{ A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }
The data doesn't need to be formated this way, it is just how I have it now.
var saveData = $.ajax({
type: "POST",
url: "someaction.do?action=saveData",
data: myDataVar.toString(),
dataType: "text",
success: function(resultData){
alert("Save Complete");
}
});
saveData.error(function() { alert("Something went wrong"); });
The $.ajax() function works fine as I do get an alert for "Save Complete". My dilemna is on the servlet. How do I retrieve the data? I tried to use a HashMap like this...
HashMap hm = new HashMap();
hm.putAll(request.getParameterMap());
...but hm turns out to be null which I am guessing means the .getParameterMap() isn't finding the key/value pairs. Where am I going wrong or what am I missing?
You don't want a string, you really want a JS map of key value pairs. E.g., change:
data: myDataVar.toString(),
with:
var myKeyVals = { A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }
var saveData = $.ajax({
type: 'POST',
url: "someaction.do?action=saveData",
data: myKeyVals,
dataType: "text",
success: function(resultData) { alert("Save Complete") }
});
saveData.error(function() { alert("Something went wrong"); });
jQuery understands key value pairs like that, it does NOT understand a big string. It passes it simply as a string.
UPDATE: Code fixed.
Simple method to sending data using java script and ajex call.
First right your form like this
<form id="frm_details" method="post" name="frm_details">
<input id="email" name="email" placeholder="Your Email id" type="text" />
<button class="subscribe-box__btn" type="submit">Need Assistance</button>
</form>
javascript logic target on form id #frm_details after sumbit
$(function(){
$("#frm_details").on("submit", function(event) {
event.preventDefault();
var formData = {
'email': $('input[name=email]').val() //for get email
};
console.log(formData);
$.ajax({
url: "/tsmisc/api/subscribe-newsletter",
type: "post",
data: formData,
success: function(d) {
alert(d);
}
});
});
})
General
Request URL:https://test.abc
Request Method:POST
Status Code:200
Remote Address:13.76.33.57:443
From Data
email:abc#invalid.ts
you can use ajax post as :
$.ajax({
url: "url",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ name: 'value1', email: 'value2' }),
success: function (result) {
// when call is sucessfull
},
error: function (err) {
// check the err for error details
}
}); // ajax call closing
For the time being I am going a different route than I previous stated. I changed the way I am formatting the data to:
&A2168=1&A1837=5&A8472=1&A1987=2
On the server side I am using getParameterNames() to place all the keys into an Enumerator and then iterating over the Enumerator and placing the keys and values into a HashMap. It looks something like this:
Enumeration keys = request.getParameterNames();
HashMap map = new HashMap();
String key = null;
while(keys.hasMoreElements()){
key = keys.nextElement().toString();
map.put(key, request.getParameter(key));
}
To get the value from the servlet from POST command, you can follow the approach as explained on this post by using request.getParameter(key) format which will return the value you want.

Categories

Resources