Get value in Json with ajax [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have an API that returns JSON like this:
[{
"Code": "001",
"Name": "xyz",
"Members": [{
"FullName": "User1"
}]
}, {
"Code": "002",
"Name": "asd",
"Members": [{
"FullName": "User2"
}]
}]
I want to replace Name and member in my label matching with "Code" and i want to do that with ajax. How can achieve the matching with Code?
This is my implementation:
$('#btnFind').on('click', function () {
var Code = $("#input_edit_code").val();
$.ajax({
type: "get",
url: "/mvc/ComplaintHandlerSquadGetListPage",
success: function () {
alert();
},
error: function (ex) {
alert(ex.title);
}
});
})

You can use javascript's filter and map Array's functions.
Let's pretend you store the code typed by the user inside this codeNumber var
var codeNumber = '002';
Your array of members:
var members = [{"Code":"001","Name":"xyz","Members":[{"FullName":"User1"}]},{"Code":"002","Name":"asd","Members":[{"FullName":"User2"}]}];
A function to filter your array by Code :
var byCode = function(member) {
return member.Code === codeNumber;
};
A function to get the name of the filtered member :
var getName = function(member) {
return member.Name;
};
You get the member's name
var memberName = members.filter(byCode).map(getName).toString();
console.log(memberName);

I don't believe AJAX and simple JSON alone can do what you want.
JSON is a way to structure objects - JavaScript Object Notation. It only structures data.
AJAX is an Asynchronous means of making an HttpRequest. It asks a server for something.
If you use AJAX to ask for a JSON file. You will get the JSON data.
I believe you have two options:
Use AJAX to request the data from the server. The server will then have to load the JSON file, find the correct data and return the correct data to AJAX.
Use AJAX to get the JSON data. Find the correct data with JavaScript.

Inside the success handler, you can compare something like this:
success: function(response) {
// yourObject that matches the code
var yourObject = response.filter(function(item) {
return item.Code === Code
});
// wherever you want to show this name
$("body").text(yourObject.Name);
}

$.ajax({
type: "get",
url: "/mvc/ComplaintHandlerSquadGetListPage",
success: function (result) {
jQuery(result).each(function(i, item){
if(item.Code == Code)
{
$('#myid').text(item.Name);
}
},
error: function (ex) {
alert(ex.title);
}
});

Related

Return list of list from Python to JS

I am doing some calculation on my python code. As a result, I get list of list similar to what I have here
data = [
[{"Count": 33874, "range": "-10"}, {"Count": 19961, "range": "-9"}],
[{"Count": 46831, "range": "8"}, {"Count": 62326, "range": "9"}]
]
I want to return this to my JS? I am currently using jsonify({"list":data}) but this does not work.
My python code
#app.route('/readRatingFiles', methods = ['POST'])
def get_post_MlModel():
data = compute()
return jsonify({"list":data})
My JS code
$.post("/readRatingFiles", {
}).done(function(data) {
indexGot = data.index
textDict[indexGot] = data.results;
});
Your AJAX call was malformed.
Look again at what you're returning: jsonify({"list": data}). The callback function returns the JSON object, but you never get the key. data in the callback is not the same as the data variable in Python. The correct way should be:
$.post("/readRatingFiles", {
}).done(function(response) {
data = response['list'];
indexGot = data.index;
textDict[indexGot] = data.results;
});
Not entirely sure what the rest of your JavaScript code means, but I trust you know what you're doing. :P

pass array of numbers from ajax to controller

I know this is a popular topic and I've tried all of the solutions I could find already out there to no avail. I've used all the solutions included for this questions: Pass a List from javascript to controller. I've simplified my test to ridiculously simple. I get into the controller but my controller input param is {int[0]}. I confirmed my array data looks good in the JavaScript and ajax call.
Can anyone please tell me what I am missing?
JavaScript Code
var selectedIds = [];
selectedIds.push(565);
selectedIds.push(573);
selectedIds.push(571);
// selectedIds = [565, 573, 571]
$.ajax({
type: "POST",
traditional: true,
dataType: "json",
data: { "ids": JSON.stringify(selectedIds) },
//data: { "ids": selectedIds},
//data: { ids: selectedIds},
url: "api/services/getbuildingsbyid",
success: function (result) {
return result;
}
});
Controller Code
[HttpPost]
public bool GetBuildingsById(int[] ids)
{
var lookAtIds = ids; // {int[0]}
return true;
}
By using JSON.stringify(selectedIds) you are turning an array of int into a string representation of said array.
The AJAX POST ends up like so:
{ "ids": "[565, 573, 571]" }
instead of
{ "ids": [565, 573, 571] }
If instead you just use the variable for the data, that should resolve the issue:
data: { "ids": selectedIds },
Edit-
Working backwards, by setting a variable to the data we can see the following:
var data = {"ids": JSON.stringify(selectedIds)}
typeof(data["ids"]) // string
data["ids"][0] // '['
data = {"ids": selectedIds}
typeof(data["ids"]) // object
data["ids"][0] // 565
I use:
public ActionResult GetBuildingsById(String selectedIds)
{
// this line convert the json to a list of your type, exactly what you want.
IList<int> Ids = new JavaScriptSerializer().Deserialize<IList<int>>(selectedIds);
return Content(ids[0].ToString());
}
This will take you selectedIds = [565, 573, 571]
and create the list of your type List

Setting up a Todo List server

I'm fairly new to Javascript, Node.js and JSON. I'm supposed to build some sort of Todo list application, where the user sends his todo to a server. I've already created the HTML and Javascript to execute the basic operation without the server.
I'm using the following program/languages in order to complete my assignment:
Vagrant (various NPM modules)
VirtualBox
Javascript (jQuery)
Currently i'm trying to send the data via the following lines of code:
//Create (simplified) "task"
item["id"] = task.dataset.id;
item["taskname"] = task.dataset.taskname;
item = JSON.stringify(item);
//Send code
$.ajax({
url: '/addtodo',
type: 'post',
dataType: 'json',
success: function (data) {
console.log(data);
},
data: item
});
Where as on the receiving side, I try to receive the data using the following lines of code:
app.post("/addtodo", function (req, res) {
var newTodo = req.body;
fs.writeFile("Somefile.json", JSON.parse(newTodo), function(err) {
if(err) {
res.json({"message":"Storing data failed"});
} else {
res.json({"message":"Data stored successfully"});
}
});
});
My objective is to get something like this in "Somefile.json"
[{
"id" : 2,
"taskname" : "Example task 2",
},
{
"id" : 2,
"taskname" : "Example task 2",
},
]
For now I get either errors or it changes the Somefile.json into [object Object].
Anyone care to explain what I did wrong and how I should fix it
Edit:
If I do not use JSON.parse i get : [object Object]
If I use JSON.stringify I get {"{\"id\":\"6\",\"taskname\":\"1234\"}":""}
Instead of the
JSON.parse(newToDo);
Use
JSON.stringify(newToDo);
This function will convert the object into a string and will give you the desired output.

How to manipulate JSON object to remove root key within Javascript?

I have a json url that returns data in the format
{
"photos" : [
{
"id": 1, "image":"https://path/to/my/image/1.jpg"
},
{
"id": 2, "image":"https://path/to/my/image/2.jpg"
}
]
}
I'm using the json in a javascript function, and need to manipulate it to remove the root key. i.e. I want something that looks like
[
{
"id": 1, "image":"https://path/to/my/image/1.jpg"
},
{
"id": 2, "image":"https://path/to/my/image/2.jpg"
}
]
I've been hacking around with various approaches, and have referred to several similar posts on SO, but nothing seems to work. The following seems like it should.
var url = 'http://path/to/my/json/feed.json';
var jsonSource = $.getJSON( url );
var jsonParsed = $.parseJSON(jsonSource);
var jsonFeed = jsonParsed.photos
What am I doing wrong?
A couple of issues there.
That's invalid JSON, in two different ways. A) The : after "photos" means that it's a property initializer, but it's inside an array ([...]) when it should be inside an object ({...}). B) There are extra " characters in front of the images keys. So the first thing is to fix that.
You're trying to use the return value of $.getJSON as though it were a string containing the JSON text. But $.getJSON returns a jqXHR object. You need to give it a success callback. That callback will be called with an object graph, the JSON is automatically parsed for you.
Assuming the JSON is fixed to look like this:
{
"photos": [
{
"id": 1,
"image": "https://path/to/my/image/1.jpg"
},
{
"id": 2,
"image": "https://path/to/my/image/2.jpg"
}
]
}
Then:
$.getJSON(url, function(data) {
var photos = data.photos;
// `photos` now refers to the array of photos
});

The confuse about use jquery $.ajax to read javascript file

suppose I have a config javascript file:
window.Config = {};
Config.UI = {
"Area": {},
"Layer": {},
"Sprites": {},
"Audio": {}
};
Config.UI.Area = {
"prop": {
"uuid": {
"_type": "string",
},
"frame": {
"_type": "rect",
"_value": {
"x": "0",
},
"_aka": "frame"
},
"zIndex": {
"_type": "string",
}
},
then I want use $.ajax to read this file:
$.ajax({
url:'js/config.js',
success:function (data, textStatus) {
console.log(data);
}
})
the question is how can I get some key's value in the config,by use the data $.ajax return?
like the "Config.UI" or the 'uuid' in ui.area.prop?Or can I convert them to json?
Rather than use AJAX, why not just insert a script?
var script = $('<script>');
script.attr('type', 'text/javascript');
script.attr('src', 'js/config.js');
script.bind('load', function() {
// use window.Config
});
script.appendTo('head');
icktoofay has a good suggestion, and the issue with the jQuery.ajax call looks to be a missing dataType: 'script' option which will evaluate the response and should give you object access. You might want to look into jQuery.getscript() as well.
I find it very useful and powerful to store data on the server as javascript objects and read them using Ajax. And it is very easy to do. Let me give you an example from an educational application I have written.
This is an example table of contents file (l1contents.js) that I would store on the server:
{
title : "Lesson 1",
topics : [
{name : "Topic 1", file : "l1t1data.js" },
{name : "Topic 2", file : "l1t2data.js" },
]
}
This is the javascript code I use to process the file:
$.ajax({
url : contentsFileName, // would be set to 'l1contents.js'
dataType : 'text', // yes this is correct, I want jquery to think this is text
cache : false,
success: function(data) {
var contentsObj = eval('(' + data + ')');
var lessonTitle = contentsObj.title;
for (var i = 0; i < contentsObj.topics.length; i++) {
var topic = contentsObj.topics [i];
// process topic.name and topic.file here
}
}
});
Obviously, this is simplified, but hopefully you get the idea. I simply use eval to set the object. And note that I don't even need any javascript code defining the structure of contentsObj. (I, of course, do have extensive comments defining the structure of my objects, but they are simply comments, not code.)
if your json file contains json data than you can use parseJSON() , toJSON() method.
and another solution is use eval(), this conver json data to javascript object so you can easly get a value by giving key.

Categories