Arrays in AJAX request JSON object data - javascript

I am sending a request to a Node/Express server using jQuery thats data is a JSON object containing an array:
var data = {
"name": "James Jamesy",
"children": [
{
"name": "Tiny James",
"age": "4"
},
{
"name": "Little James",
"age": "6"
},
{
"name": "Graham",
"age": "8"
}
]
}
var request = $.ajax({
method: 'PUT',
url: apiPath + 'updateuser',
data: data,
dataType: 'json'
});
The request itself is working fine, however the server is reporting the data as:
{
name: 'James Jamesy',
'children[0][name]': 'Little James',
'children[0][age]': '4',
'children[1][name]': 'Medium James',
'children[1][age]': '6',
'children[2][name]': 'Graham',
'children[2][age]': '8'
}
Now I've figured out that I can get my desired result by instead stringifying the children array:
var data = {
"name": "James Jamesy",
"children": JSON.stringify([ ... ])
}
And then JSON.parse()ing it on the server.
However I am hoping someone can explain why the array is converted as it is in the request, and whether I should be handling this a different way? As in this instance converting the single array is fine, but going forward I might have semi-complex objects I'm looking to send to the server.
Thanks in advance!
EDIT: Additionally and strangely(?), if I send the JSON result back as the passed JSON, it works perfectly:
res.json(JSON.parse(req.body.categories));
The browser logs out the object and I can manipulate it perfectly fine.

You weren't passing a JSON string through ajax which is why you couldn't handle the data on the back end.
var data = {
"name": "James Jamesy",
"children": [
{
"name": "Tiny James",
"age": "4"
},
{
"name": "Little James",
"age": "6"
},
{
"name": "Graham",
"age": "8"
}
]
}
var request = $.ajax({
method: 'PUT',
url: apiPath + 'updateuser',
data: JSON.stringify(data),
contentType: 'application/json', // for request
dataType: 'json' // for response
});

Related

How to add data into json-server database

This is my json-server database.
{
"users": {
"sarahedo": {
"id": "sarahedo",
"name": "Sarah Edo",
"avatarURL": "https://pluralsight.imgix.net/author/lg/6f77d113-ea36-4592-814d-9d4acb32f231.jpg",
"answers": {
"8xf0y6ziyjabvozdd253nd": "optionOne",
"6ni6ok3ym7mf1p33lnez": "optionOne",
"am8ehyc8byjqgar0jgpub9": "optionTwo",
"loxhs1bqm25b708cmbf3g": "optionTwo"
},
"questions": ["8xf0y6ziyjabvozdd253nd", "am8ehyc8byjqgar0jgpub9"]
},
}
I need to add new ID in "questions": ["8xf0y6ziyjabvozdd253nd", "am8ehyc8byjqgar0jgpub9"]
but I can't access it in fetch URL.
I tried to check the URL in browser "HTTP://localhost:3000/users/sarahedo"
I get empty object for some reason {}
I want to know how can I add new data to it using fetch POST.
The reason that you get an empty object from http://localhost:3000/users/sarahedo is that you've defined your data in .json file incorrectly. If you correct your .json file with the below data, you'll see your user obj by hitting http://localhost:3000/users/sarahedo in the browser.
{
"users": [
{
"id": "sarahedo",
"name": "Sarah Edo",
"avatarURL": "https://pluralsight.imgix.net/author/lg/6f77d113-ea36-4592-814d-9d4acb32f231.jpg",
"answers": {
"8xf0y6ziyjabvozdd253nd": "optionOne",
"6ni6ok3ym7mf1p33lnez": "optionOne",
"am8ehyc8byjqgar0jgpub9": "optionTwo",
"loxhs1bqm25b708cmbf3g": "optionTwo"
},
"questions": [
"8xf0y6ziyjabvozdd253nd",
"am8ehyc8byjqgar0jgpub9"
]
}
]
}
You can either use below code for adding new data, using fetch POST:
async function postData(url = '', data = {}) {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
return response.json()
}
For more detailed info about fetch POST, check this out: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#supplying_request_options

my JSON is not practical and I want to change it, how can I do so?

Problem: my JSON isn't practical and I want to change it. As you can see my JSON looks strange, but somehow it's valid JSON (checked with JSONLint). I have input fields which are in containers with their own unique id (they increment). I was wondering if it's possible to send the data inserted into the input fields together so when I fetch it, it will stay together.
how my JSON looks like right now:
{
"main_object": {
"id": "new",
"formData": {
"language": "nl_NL",
"getExerciseTitle": "ExampleForStackOverflow",
"question_takeAudio_exerciseWord[0": "ExampleForStackOverflow",
"Syllablescounter[0": "Example",
"Syllablescounter[1": "Example1",
"question_takeAudio_exerciseWord[1": "SecondExampleForStackOverflow",
"Syllablescounter[2": "Second",
"Syllablescounter[3": "Example"
}
}
}
what I am looking and hoping to achieve:
{ "main_object":
{
"id": "new",
"formData": [
{
"language": "nl_NL",
"getExerciseTitle": "ExampleForStackOverflow",
"Word": "ExampleForStackOverflow",
"Syllables":["Example", "Example1"]
},
{
"Word": "SecondExampleForStackOverflow",
"Syllables": ["Second", "Example"]
}
]
}
};
https://jsfiddle.net/StackOverflowAccount/sa2eowhh/ I have a fiddle so you can see what I mean. When you click on the green + button it adds a whole field. This is a container that has an ID, I am trying to keep everything with the same ID with each other in the JSON file, so when I fetch it to my front-end it "knows" which syllables are part of the exercise word.
I have an ajax call which I think causes my JSON file to look like what I have right now.
my ajax call:
function saveExerciseAjaxCall() {
$("#my_form").on("submit", function(event) {
event.preventDefault();
$.ajax({
url: 'saveJson.php',
type: 'POST',
data: {
id: getUrlParameter('id'),
formData: JSON.parse('{"' + decodeURI($('#my_form').serialize()).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}')
},
dataType: 'json',
}).done(function(response) {
});
});
}
Thanks!

Display json response in ajax jquery,

The JSON Response I'm getting,
{
"user_data": {
"id": 22,
"first_name": xxx,
"last_name": xxx,
"phone_number": "123456789",
},
"question_with_answers" : [
{
"id": 1,
"question_name": "Features of our project that you like (select one
or more):",
"answers": [
{
"id": 19,
"question_id": 1,
"customer_id": 22,
"option": "Location",
},
{
"id": 20,
"question_id": 1,
"customer_id": 22,
"option": "Architecture",
},
]
},
{
"id": 2,
"question_name": "Features of our project that you DID NOT like
(select one or more):",
"answers": [
{
"id": 22,
"question_id": 2,
"customer_id": 22,
"option": "Location",
},
]
},
{
"id": 3,
"question_name": "How soon are you looking to buy a new home?",
"answers": [
{
"id": 24,
"question_id": 3,
"customer_id": 22,
"option": "Immediately",
}
]
}
]
}
So that is how JSON response looks like, now I need to display data using jquery
My js code
function openModal(Id){
var CustomerId = Id;
$.ajax({
type : 'get',
url: 'customer-details',
data: {
'CustomerId':CustomerId
},
success: function(data)
{
//what I have to do here
}
})
}
The output I want is,
first_name : xxx
last_name : xxx
phone_number : 123456789
1.Features of our project that you like (select one or more):
ans: Location, Architecture
2.Features of our project that you DID NOT like (select one or more)
ans: Location
3.How soon are you looking to buy a new home?
ans: Immediately
Thats how my output should look like from above json response,Is it possible to get above output using that Json response I got
There are two variable that I have passed from backend like user_data and question_with_answers
In success handler first of all make your json into a array using
var obj = JSON.parse(data);
Now in data you have array of your response and you can use this like
obj.first_name
obj.last_name
Note:- may be you have issue in JSON.parse so use first
var data = json.stringify(data)
after that use Json.parse function and use above data variable
this data
You have to set the dataType in the $.ajax call, set it to dataType:"json"...
After that, you got on the data variable in the success the json object and you can access it like data.user_data or data.id or data.first_name.
If you dont define the json as dataType, it will not work properly.
Addition
If you want to display the content of "question_with_answer" you have to iterate trough it, like ....
for (i in data.question_with_answer) { alert(data.qestion_with_answer[i]); }

JSON data logging to buffer and PUT to server

I have a javascript function which generates JSON data at every certain second and then PUT it to a cloud server. Now I don't want to POST in realtime, rather I want to log this data in a buffer and say after n number of data log I will PUT to cloud. For example I want to log 50 data point in 10 second and then with timestamp I will PUT to a server
Now JSON data is passed through var fromDatan. JSON data format is
{"values": [ { "at": "2014-08-17T12:00:00Z", "value": "15" }]}
This is a single instance which is passing through say var fromDatan and being PUT in cloud.
Now I want to log say n number of JSON data. ie.
{ "values": [ { "at": "2014-08-17T12:00:00Z", "value": "15" }, { "at": "2014-08-18T12:00:00Z", "value": "20" }, { "at": "2014-08-19T12:00:00Z", "value": "25" } ] }
And then I will PUT to cloud. This is my PUT code for real time which is working:
$.ajax({
url: "https://abcd.com",
headers: {
"X-API-KEY": "23dq3dq3ddbb16a7956e6f7a",
"Content-Type": "application/json"
},
type: "PUT",
data: fromDatan,
dataType: "JSON",
success: function(fromData, status, jqXHR) {
alert(JSON.stringify(fromData));
},
error: function(jqXHR, status) {
alert(JSON.stringify(jqXHR));
}
});
So please let me know how to do this. Help me out
the code that runs every second should do:
fromDatan.values.push({
at: timestamp,
value: value
});
if (fromDatan.values.length >= 50) {
$.ajax( {
...
});
fromDatan.values = [];
};

JSONP Object Error

I am trying to make a cross domain request to send/recieve some data. I can't get past the object error. Before I was getting the No Transport Error but adding Query.support.cors = true; solved this issue.
var url = "http://CROSSDOMAINSERVER:PORT/Service1.svc/GetDataUsingDataContract";
$.ajax({
type: 'GET',
url: url,
data: 'tool=1&product=Some%20Product&details=9&bogus=should%20not%20pass%20validation',
datatype: "jsonp",
contentType: "application/json",
success: function (response) {
alert(response.data);
},
error: function (error) {
alert(error.statusText);
}
});
If I type the url out in a browser:
http://CROSSDOMAINSERVER:PORT/Service1.svc/GetDataUsingDataContract?&tool=1&product=Some%20Product&details=9&bogus=should%20not%20pass%20validation
I get the correct response.
{"d":{"__type":"ClientSideData:#ProdResourceToolService","details":"9","product":"Some Product","result":"1","site":"Somewhere, SD","systime":"2\/6\/2013 2:50:20 PM","team":"0000000000","tool":"1","user":"username"}}
When I use ajax it does not submit it to the database or return data, just object error. Does anyone have any suggestions on how to get around this?
I should also specify if I remove http://CROSSDOMAINSERVER:PORT/ from var url when debugging locally I get the correct json response. Why does cross domain not work?
This is your current response:
{
"d": {
"__type": "ClientSideData:#ProdResourceToolService",
"details": "9",
"product": "Some Product",
"result": "1",
"site": "Somewhere, SD",
"systime": "2/6/2013 2:50:20 PM",
"team": "0000000000",
"tool": "1",
"user": "username"
}
}
This is a valid JSON string. However, its not valid JSONP. If possible, make your service wrap the json in a function:
responseFunc({
"d": {
"__type": "ClientSideData:#ProdResourceToolService",
"details": "9",
"product": "Some Product",
"result": "1",
"site": "Somewhere, SD",
"systime": "2/6/2013 2:50:20 PM",
"team": "0000000000",
"tool": "1",
"user": "username"
}
});
And in your $.ajax() call, add a property: jsonpCallback: 'responseFunc'.
Also, I would suggest passing the data as an object:
data: { tool: 1, product: 'Some Product' } //etc...
If you can access the service from the serverside without any issues you could create a httphandler (.ashx for example) and let it generate the JSON for you. Then you wouldn't have to deal with the cross domain issues on the client side.

Categories

Resources