node.js parse array from jquery ajax - javascript

I'm creating an application in node which will get the array sent from jquery Ajax, here is my code:
Ember.$.ajax
({
type:"PUT",
url:"http://localhost:3000/ids/",
data:
{
ids:[29,12,43],
},
dataType: 'json',
});
Here is my node.js code:
router.put('/ids/', function(req, res)
{
var data = req.body;
console.log(data);
console.log(data.ids);
});
The result is:
{ 'ids[]': [ '29', '12', '43' ] }
undefined
I've also tried to iterate over it, but the code:
for (var key in data) {
if (data.hasOwnProperty(key)) {
console.log(key + " -> " + data[key]);
}
}
Is not working also. What can I do in that case?

The 'ids[]:' does not look like the correct format for a key in JSON - are you sure this is what the console is printing?
In any case, if the data you are receiving is coming in as a string (even when the string looks like JSON) - you could try and parse it into JSON object. Here is an example for your case:
router.put('/ids/', function(req, res)
{
var data = req.body;
//if the string is a properly formatted JSON, this should pass:
var dataJSON = JSON.parse(data);
console.log(data);
//then see if this gives you what you expect
console.log(dataJSON);
console.log(dataJSON.ids);
});
Give it a try and let me know if this helps.
UPDATE:
Seeing that the data you receive is not a well-formatted JSON, try changing the PUT request into something like this:
Ember.$.ajax
({
type:"PUT",
url:"http://localhost:3000/ids/",
data: JSON.stringify({'ids':[29,12,43]}),
dataType: 'json',
});
Give it a try and let us know what the console is printing on the server and if the problem persists.

Related

POST request in JSON using $.ajax()

My backend API accepts data in JSON format, such as:
{ "article_id" = 1 }
In the front-end, I tried to add the following javascript to a button:
function articleIsSelected(id) {
let data = '{"article_id":' + id + '}';
$.ajax({
url:"https://www.myurl.com",
data: data,
type: "post",
contentType: "application/json",
success: function () {
alert("Selection succeeded!");
},
error: function () {
alert("Selection failed.");
},
});
}
It returns that the request was successful, but my database is not updated. There is something wrong with the data format. Instead of trying to hard code the data in JSON format, one should sign the value to "article_id" and then JSON encode it with JSON.stringify(data).
The data is not proper JSON, change it to:
let data = {"article_id": id};
And make sure you encode it:
JSON.stringify(data)

Yii2 and Ajax: How to send JSON object of arrays?

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);
});

My Json get cut off when sent with Ajax

I'm using angular to save new data on the database, I take the data from my inputs, put it in a object and I convert it to a Json, I send it by POST, but my JSON gets cut off and I have no clue why is it happening.
var myJson = angular.toJson(myObject);
$http({
method: 'POST',
url: 'http://url/file.php',
data: {
'data': myJson
}
})
.success(function (data){
console.log(data);
})
My file.php has a var_dump($_POST) in it, and it shows that:
[
{
"uuid":"56456456456456456456465456"
},
{
"store_name":"",
"store_email":"",
"store_facebook":"",
"contact_name":"John Doe",
"contact_email":"email#email.com",
"contact_facebook":"http://localho
Angular's http post method sends whatever data it is passed to. You should check your generated json data after
var myJson = angular.toJson(myObject); using console.log(myJson);
and that itself must be cut off.

Issue with JSON.stringify adding a extra \ and "" to my Json object

Hi I am creating using Javascript an array of object with a key and a value using the following code.
ValuesArray.push({ key: $(this).attr('someattribute'), value: $(this).val() });
As a result I have am array of object like this:
key:29; value: 'Country'
Key:12; value: '4,3,5'
when I am trying to stringify it and send that JSON in a post I am having a wrong formatted JSON with \ and " in places that I dont want so when I try to desirales that JSON as a JObject on codebehind with C# I am having trouble. How can I create a clean JSON using the stringify
var jObject = JSON.stringify(ValuesArray);
My JSON now which is wrong is:
{
"JObject": "[{\"key\":\"29\",\"value\":\"Country\"}, {\"key\":\"30\",\"value\":\"4,3,5\"}]"
}
I would like to have a JSON object like this
{
"JObject": [{"key":"29","value":"Country"},{"key":"30","value":"4,3,5"}]
}
without the quotes around the [] and the character \
Any good idea to solve it.
Thank you
More detail this how I am sending the JSON to my API
this is how I am sending the JSON to my Web API:
function PostAPIRequest(address) {
var jObject = JSON.stringify(ValuesArray);
var responseJson = null;
$.ajax({
url: address,
type: 'POST',
dataType: 'json',
data: { JObject: jObject },
success: function (data) {
responseJson = data
ProcessDataResponse(responseJson);
//TODO: REFRESH THE DATA GRID
},
error: function (xhr, ajaxOptions, thrownError) {
//TODO redirect to the error page and send error email there.
alert(xhr.status);
alert(thrownError);
}
})
}
and this how I am receiving it in my API controller
...
// POST api/datavalues/5
public string Post(int id, JObject value)
{
var temp = value;
...
It looks like you are placing a string as the value in your map. You should do something like:
var objMap = {"JObject" : ValuesArray};
var json = JSON.stringify(objMap)
What's happening is you are double json encoding your values array - note that your "invalid" JSON value is actually a JSON string rather than the array that you want.
EDIT
It looks like you are sticking in JSON strings of maps into an Array and then stringifying that. Here's a jsfiddle that should help you get what you are looking for - http://jsfiddle.net/4G5nF/
In your post request, try this
var jObject = {"JObject" : ValuesArray};
$.ajax({ url: address,
type: 'POST',
dataType: 'json',
data: jObject,
success: function (data) { .. }});
Note the change in the data attribute. That is a value that is automatically JSONified for you.
const config = {a: 1, b: 2}
console.log(JSON.stringify(JSON.stringify(config)))
"{\"a\": 1, \"b\": 2}"
May be you have an old prototype library.
As I remove it, bug has disappeared

Working with POSTed json objects in Django

I am trying to figure out how to deal with POSTed json objects in Django. I'm POSTing a json object to the server and want to use it like a python dictionary.
here is my js:
$.post(
"/projects/vote/",
obj,
function(data) {
//alert("Data Loaded: " + data);
alert(data["msg"]);
});
What I am returning (end of django view):
return HttpResponse(json.dumps(foo), mimetype="application/json")
where
foo = {"msg": str(postdata)}
In other words, I'm POSTing a json object to the server, and alerting the string of the python object I get on the server so I can see what's going on.
If my obj is:
var obj = {
'bulk': false,
'data': {
'chosen': '14',
'proj1': '15',
'proj2': '14',
'proj3': '16',
'more': false,
},
'data2': [
{
'a': 'apple'
},
{
'b': 'banana'
},
],
}
I get this in return:
<QueryDict: {u'data[proj3]': [u'16'], u'data[proj2]': [u'14'], u'data[chosen]': [u'14'], u'data[proj1]': [u'15'], u'bulk': [u'false'], u'data2[0][a]': [u'apple'], u'data[more]': [u'false'], u'data2[1][b]': [u'banana']}>
How come the structure of the json obj and python dict don't align? And how do I get the structure to be the same? e.g. instead of data2[0][a], I would get data2 as the key to another dictionary
How I'm getting postdata:
# django version 1.4
postdata = request.POST.copy()
You may post json as plain string using JSON.stringify like this:
$.post(
"/projects/vote/",
{msg: JSON.stringify(obj)},
function(data) {
//alert("Data Loaded: " + data);
alert(data);
});
Thus on server side you should just extract 'msg' from request.POST:
def view(request):
return HttpResponse(request.POST['msg'], mimetype="application/json")
Note, that JSON.stringify is not supported by default in some browsers and you may want to use json lib: https://github.com/douglascrockford/JSON-js
You don't show how you're getting postdata from the POST, but you should be using request.body (request.raw_post_data in versions before 1.4).
You did not post JSON data. Set the dataType parameter to json:
$.post(
"/projects/vote/",
obj,
function(data) {
//alert("Data Loaded: " + data);
alert(data["msg"]);
},
'json'
);
The server can simply return a string, and the js can be written like this:
$.post(
"/projects/vote/",
obj,
function(data) {
data=eval('(' + data+ ')');//get the json object from string.
//alert("Data Loaded: " + data);
alert(data["msg"]);
});
Hope this helpful.

Categories