Good night everyone.
I've seen this question answered in other posts, but no answer works for me, I'm new in ajax/json and I'm a bit lost.
I have this ajax call that returns me a JSON array:
$.ajax({
type: "GET",
url: common.RestURL.index,
dataType: 'json'
}).done(parameters => {
//Fill parameters
drawSettings(parameters);
}).fail(function (jqXHR, textStatus, error) {
showMsg(jqXHR.responseJSON.message,
"Error",
"error");
});
This is the exact json object to return:
"config": [
{
"configDescription": "description1",
"configValue": "value1",
"configKey": "key1",
"idCompany": "company1",
"appConfigurationId": "config1",
"configType": "List"
},
{
"configDescription": "description2",
"configValue": "value2",
"configKey": "key2",
"idCompany": "company2",
"appConfigurationId": "config2",
"configType": "Date"
},
{
"configDescription": "description3",
"configValue": "value3",
"configKey": "key3",
"idCompany": "company3",
"appConfigurationId": "config3",
"configType": "String"
},
{
"configDescription": "description4",
"configValue": "value4",
"configKey": "key4",
"idCompany": "company4",
"appConfigurationId": "config4",
"configType": "Boolean"
}]
So when the ajax call gets the json array, it calls another method that works with each of the objects in the array, but when I try to create each object, they are created empty and I can't find the problem, this is the function I'm talking about:
function drawSettings(parameters) {
if (!$.isArray(parameters)) {
parameters = [parameters];
}
//Fill params in div
$.each(parameters, function (key, value) {
//Parameter to draw
console.log("value .........................." + value.configDescription);
let param = new Parameter(value);
console.log("objetooo ------------ " + param.configDescription);
The Parameter class is a simple class with the attributes of the json ojects and the logs show the attributes with "undefined" value.
Can please someone help me understand and solve the problem?
Thanks to everyone in advance!
Related
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!
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
});
I'm trying to make a graph. S I need to send an ajax request, select some rows from database, then return the result. I did it. And here is the output:
success : function (data) {
console.log(data);
}
To make that graph, I need to convert my current output to this structure: (this structure is the one I should pass it to the library which draws the graph)
var json = [
{
"adjacencies": [
{
"nodeTo": "graphnode15",
"nodeFrom": "graphnode0",
"data": {}
},
{
"nodeTo": "graphnode16",
"nodeFrom": "graphnode0",
"data": {}
},
{
"nodeTo": "graphnode17",
"nodeFrom": "graphnode0",
"data": {}
}
],
"data": {
"$color": "#83548B",
"$type": "circle"
},
"id": "12",
"name": "sajad"
}
];
I've tested all of these:
console.log(data);
console.log([data]);
console.log(JSON.stringify(data));
console.log("["+JSON.stringify(data)+"]");
But none of them isn't expected structure for the library which draws the graph. Anyway, Does anybody know how can I make expected structure?
JSON.parse(data) will do this.
Try:
json =[]
json.push(data)
send this json to the graph
Maybe this should work
success : function (data) {
var json = [JSON.parse(data)];
console.log(json);
}
This is my first question to StackOverflow. I think answer is not so complicate, but I am very new to Javascript.
I have a JQuery AJAX function that parses this JSON object:
{
"Users":[
{
"key":"1",
"label":"Tom Clancy"
},
{
"key":"12",
"label":"Steve Martin"
}
]
}
and should obtain the same result as:
var sections = [{
key: 1,
label: "Tom Clancy"
}, {
key: 12,
label: "Steve Martin"
}
];
I'm able to iterate through JSON element, but i don't know how to go on.
Can you provide suggestions?
EDIT: i can't still get it work...this is my code:
var sections=[
{key:1, label:"Section A"},
{key:2, label:"Section B"},
{key:3, label:"Section C"},
{key:4, label:"Section D"}
];
$.ajax({
url: '/WebOffice/ListaUtenti',
type: "POST",
dataType: 'json',
success: function (data)
{
console.log( "success" );
sections = data.Users;
}});
scheduler.createTimelineView({
name: "matrix",
x_unit: "day",
x_date: "%d %M",
x_step: 1,
x_size: 15,
y_unit: sections,
y_property: "section_id"
});
The jquery ajax call doesn't assign the new value to sections (the call state is success, verified) and so scheduler still shows the original sections. Where i'm wrong?
thanks
I will explain you the process. Go to any online JSON formatter, may be this one and pretty print your JSON. It will appear as.
{
"Users":[
{
"key":"1",
"label":"Tom Clancy"
},
{
"key":"12",
"label":"Steve Martin"
}
]
}
So Users is an array of objects. Users[0] is first object and Users[1] is second object.
So you can iterate the JSON easily and obtain the result you want.
Live demo : http://jsfiddle.net/sbymr/
See the console for the output.
I must be thick because I cannot for the life of me get jQuery autocomplete to work. I have searched for many many examples, and it seems that most of them use an older version of jQuery. I found one fairly good example directly from the jQuery UI site: http://jqueryui.com/demos/autocomplete/#remote-jsonp So I modeled mine after that example. When I type in my input box, the little autocomplete box pops underneath the input box, but there is nothing in the autocomplete box. My data is not being loaded correctly by jQuery.
My datasource is a URL that returns JSON data. Example:
[{
"pk": 1,
"model": "concierge.location",
"fields": {
"online": false,
"link": "",
"email": "",
"address": "TBA"
}
}, {
"pk": 2,
"model": "concierge.location",
"fields": {
"online": false,
"link": "",
"email": "",
"address": "UB 2008"
}
}]
My Javascript code:
$(document).ready(function() {
$("input#id_location_address").autocomplete({
max: 10,
source: function(request, response) {
$.ajax({
url: "/concierge/autocomplete/locations/",
dataType: "json",
data: request,
success: function( data ) {
console.log( data )
response( data, function(item) {
return { label: item.address, value: item.address }
});
}
});
}
});
});
So when I console.log(data) in Firebug, it shows the object with all the data in tact. I think I am not accessing the 'address' properly in my Javascript code. See really, I just want the 'address' to pop up in the autocomplete box. How do I do this?
Thanks in advance,
Chris
I figured it out. Needed to loop through the array of json objects and then put the data into an array. I got the idea of returning an array from the defualt jQuery UI example http://jqueryui.com/demos/autocomplete/#default
$('input#id_location_address').keyup( function() {
$("input#id_location_address").autocomplete({
source: function(request, response) {
$.ajax({
url: "/concierge/autocomplete/locations/",
dataType: "json",
data: request,
success: function( data ) {
// loop through data and return as array
items = new Array();
for(item in data) items.push( data[item].fields.address );
response( items );
}
});
}
});
});
Try:
response($.map(data, function(item) {
return {
label: item.fields.address, // item.FIELDS ;)
value: item.fields.address
}
}));
Indeed, response expects an array as argument. $.map iterates over the data items and forms a new array of the return value from the passed mutator method. Once done, $.map returns the new array which will be the argument of response().
try
response($.map(data, function(item) {
return {
label: item.fields.address,
value: item.fields.address
}
}));
see the source of this demo