I have a JSON string coming from my database table but it has empty root element name
{"": [
{"ID":18,"MenuName":"dsadasdasd","IsActive":"InActive"},
{"ID":17,"MenuName":"Karachi","IsActive":"Active"},
{"ID":2,"MenuName":"User Management","IsActive":"Active"},
{"ID":1,"MenuName":"Home","IsActive":"Active"}
]}
I am trying to access this JSON with below jquery ajax call method
function Get_DataTable() {
$.ajax({
url: "GridView_JqueryFunctionality.aspx/CallDataTable_EmptyRootName",
type: "POST",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.d) // showing json is fine
var MyData = $.parseJSON(data.d);
for (i = 0; i < Object.keys(MyData).length; i++) {
alert(MyData[i].ID + ' : ' + MyData[i].MenuName);
}
}
});
}
My Webmethod
[WebMethod(true)]
public static string CallDataTable_EmptyRootName(){
List<Category> Categories = new List<Category>();
clsMenu objMenu = new clsMenu();
DataTable dt = new DataTable();
objMenu.GetAllMenu(dt);
if (dt.Rows.Count > 0){
string jsonString = ConversionExtension.DataTabelToJson(dt);
return jsonString.ToString();
}else{
return "";
}
}
it is giving me undefined : undefined... Please help me. I am stuck now
Try this:
function Get_DataTable() {
$.ajax({
url: "GridView_JqueryFunctionality.aspx/CallDataTable_EmptyRootName",
type: "POST",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.d) // showing json is fine
var MyData = $.parseJSON(data.d)[""];
for (i = 0; i < MyData.length; i++) {
alert(MyData[i].ID + ' : ' + MyData[i].MenuName);
}
}
});
}
Assuming you have a variable name for your object, you can reference it with an empty string as the key.
var a = {
"": [
{
"ID": 18,
"MenuName": "dsadasdasd",
"IsActive": "InActive"
},
{
"ID": 17,
"MenuName": "Karachi",
"IsActive": "Active"
},
{
"ID": 2,
"MenuName": "User Management",
"IsActive": "Active"
},
{
"ID": 1,
"MenuName": "Home",
"IsActive": "Active"
}
]
}
console.log(a[""]);
Try running the above code notice we can still access the objects elements despite having an empty root name.
You have to access with brackets the no-name property in the root object, and then iterate over the array of items.
success: function(response) {
var data = $.parseJSON(response.d);
var list = data[""];
list.forEach(function(item, i) {
console.log(item);
console.log(item.ID, ' -> ', item.MenuName);
});
}
Related
Not getting array of data from ajax to controller.
$.ajax({
type: "POST",
url: "/Home/List",
traditional: true,
contentType: 'application/json',
data: {
"Query": JSON.stringify(Query) //change this
success: function() {}
});,
And array of Query :
0: {label: "abc:", value: "123", type: "Select"} 1: {label: "xyz",
value: "Hum", type: "text"}
Can anyone help ?
Try something like this
<script type="text/javascript">
var query=[{label: "abc:", value: "123", type: "Select"},{label: "abc:", value: "1232", type: "Select"} ];
$.ajax({ type: "POST",
url: "/Home/List",
traditional: true,
contentType: 'application/json',
data: JSON.stringify(query),
success: function (){
} });
</script>
I think something along this may work for you.
function sendarray() {
var arr = [];
var json = {
"label": 'abc',
"value": 1234,
"Name": 'Name'
};
arr.push(json);
json = {
"label": 'abc2',
"value": 1234,
"Name": 'Name2'
};
arr.push(json);
var myarray = JSON.stringify(arr);
$.ajax({
url: '/controller/GetArray',
type: 'POST',
data: { array: myarray },
success: function (data) {
//Do something
},
error: function () {
//Do something
}
});
}
then in the controller
public JsonResult GetArray(string array)
{
var obj = JsonConvert.DeserializeObject<object>(array);
return Json("");
}
This will send an string with all the data in the array to the controller, then you turn string with json format into an object list
I would like to delete certain items from a JSON object under certain conditions.
I am making two Ajax requests, one to get items from an API endpoint and save the JSON object in a variable called items. I'm using the ID of each item to make a subsequent API request.
If the second API returns a non-empty object, delete the specific item from my JSON Object. Then render the items (meaning only display items that are yet to be approved).
API Request 1
var items;
function fetchItems() {
$.ajax({
url: urlOne,
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function(data) {
items = data.d.results;
getPendingItems();
},
});
}
API Request 2
function getPendingItems() {
for (var i = items.length - 1; i >= 0; i--) {
$.ajax({
url: urlTwo + items[i].Id,
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function(data) {
if ($.isEmptyObject(data.d.results)) {
//
} else {
removeItems(i);
}
},
})
}
}
function removeItems(key) {
delete items[key];
}
My Data Structure
[
{
"Id": 1,
"Item_name": "test1"
},
{
"Id": 2,
"Item_name": "test2"
},
{
"Id": 3,
"Item_name": "test3"
},
]
However, the items are not being deleted from my JSON object. I end up rendering all the items
I am firing an ajaxcall on page load and getting an array back. Now for each element called groupId present in the array, I have to fire another ajaxcall to get the group name and group notes.
Now I need to create a final array that would have the array returned from the first ajaxcall and merged with the corresponding group name and info returned from the second call.
This is the array returned from the first ajaxcall:
[{
"customMessage": "THis is the first message",
"groupIdx": 13
}, {
"customMessage": "This is the second message",
"groupIdx": 14
}]
Which I am getting by doing:
$.ajax({
type: "GET",
url: '<html:rewrite page="/rest/pre-visit-instruction/list"/>',
dataType: "json"
}).done(function(data) {
vueInst.preVisitInstructions = data;
});
Now to this I am appending a .each function and calling another ajaxcall.
This is the final code:
$.ajax({
type: "GET",
url: '<html:rewrite page="/rest/pre-visit-instruction/list"/>',
dataType: "json"
}).done(function(data) {
vueInst.preVisitInstructions = data;
}).each(dataObj, function(j, data) {
$.ajax({
type: "GET",
url: '<html:rewrite page="/rest/group/"/>' + data.groupIdx + '/info',
dataType: "json"
}).
My question is: How do I get the data returned from the .each function and append it to the original object?
$.each() function must be inside of .done() function.
Update: According to the last comment:
You should use Array#filter.
data.data = response2.filter(function(x) {
return x.groupId === data.groupIdx;
});
Something like this:
$(function() {
var vueInst = {
preVisitInstructions: []
};
var result = [];
$.ajax({
type: "GET",
url: "https://gist.githubusercontent.com/dannyjhonston/17455e3ef90fb3cf096d1f051d4331e5/raw/ad51c85e7722a83e7085ad63e26a524b769efe50/firstData.json",
dataType: "json"
}).done(function(response1) {
$.each(response1, function(j, data) {
$.ajax({
type: "GET",
url: "https://gist.githubusercontent.com/dannyjhonston/e610dd23f830b108bc1e24c78f66b3b6/raw/54851535eedd1e94a1a944ddf3d63412e83349f8/secondData.json",
dataType: "json"
}).done(function(response2) {
data.data = response2.filter(function(x) {
return x.groupId === data.groupIdx;
});
result.push(data);
});
vueInst.preVisitInstructions = result;
});
});
$("#btnCheck").on("click", function() {
console.log(JSON.stringify(vueInst.preVisitInstructions));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="btnCheck">Check data</button>
The result should be:
[{
"customMessage": "THis is the first message",
"groupIdx": 13,
"data": [
]
},
{
"customMessage": "This is the second message",
"groupIdx": 14,
"data": [{
"groupId": 14,
"groupName": "Test 1",
"groupNotes": "THis is a note"
},
{
"groupId": 14,
"groupName": "Test 2",
"groupNotes": "THis is a note"
},
{
"groupId": 14,
"groupName": "Test 3",
"groupNotes": "THis is a note"
}
]
}
]
This question already has answers here:
How to 'output' a JavaScript variable into an HTML div
(5 answers)
Closed 5 years ago.
Consider:
$.ajax({
type: "POST",
url: "/myurl",
async: false,
data: JSON.stringify({}),
contentType: "application/json",
complete: function (data) {
var results = data["responseText"];
alert(results)
},
error: function () {
alert("Error")
}
});
The JSON returned:
{"jsonrpc": "2.0", "id": null, "result": "{\"ids\": [{\"id\": 1, \"name\": \"Messi\"}, {\"id\": 2, \"name\": \"Ronaldo\"}]}"}
How can I append the data in div like the following?
1 Messi
2 Ronaldo
Pick the ids property from your Ajax response, loop through it and prepare your required HTML structure using that info. In the end, insert this HTML string in your HTML page.
/*
$.ajax({
type: "POST",
url: "/myurl",
async: false,
data: JSON.stringify({}),
contentType: "application/json",
complete: function (data) {
var response = data["responseText"];
var insertDatas = JSON.parse(response.result);
var htmlString = "";
insertDatas.ids.forEach(function( item ){
htmlString += '<li>'+item.name+'</li>';
});//forEach()
$("#players-list").html( htmlString );
},
error: function () {
alert("Error")
}
});
*/
var response = {
"jsonrpc": "2.0",
"id": null,
"result":
{"ids":
[
{"id": 1, "name": "Messi"},
{"id": 2, "name": "Ronaldo"}
]
}
};
var htmlString = "";
response.result.ids.forEach(function(item){
htmlString += '<li>' + item.name + '</li>';
});//forEach()
$("#players-list").html( htmlString );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<ol id="players-list"></ol>
I'm trying to display the json that i get and parse it in the success function of ajax.
What I have so far:
Ajax:
data = "Title=" + $("#Title").val() + "&geography=" + $("#geography").val();
alert(data);
url= "/portal/getResults.php";
$.ajax({
url: url,
type: "POST",
//pass the data
data: data,
dataType: 'json',
cache: false,
//success
success: function(data) {
alert(data);
}
});
getResults.php (JSON output):
{
"results": [
{
"DocId": 2204,
"Title": "Lorem ipsum dolor sit amet, consectetur",
"Locations": [
{
"State": "New York",
"City": ""
},
{
"State": "New York",
"City": "New York City"
}
],
"Topics": [
3,
7,
11
],
"PublicationYear": "2011",
"Organization": "New Yorks Times",
"WebLocation": "www.google.com",
"Description": "Lorem Ipsum"
}
],
"TotalMatches": 1
}
I expect the result in data to be the the json from getResults.php but instead I get [object Object].
I have also tried the code below but get no response:
success: function(data) {
var json1 = JSON.parse(data);
alert(json1);
}
since you're telling jQuery that you want dataType:'json', the ajax function parses the JSON response into an object for you. the result object you see should be an object with data matching the JSON response from your server. if you need the string version, try JSON.stringify(), otherwise you can just use the object as is: data['results'][0]['DocId'], etc
good luck!
Here is an example for your request : http://jsfiddle.net/5y5ea98n/
var echo = function(dataPass) {
$.ajax({
type: "POST",
url: "/echo/json/",
data: dataPass,
cache: false,
success: function(json) {
alert(JSON.stringify(json));
}
});
};
$('.list').live('click', function() {
$.get("http://www.json-generator.com/api/json/get/bQxORzxQGG?indent=2", function(data) {
var json = {
json: JSON.stringify(data),
delay: 1
};
echo(json);
});
});
I tried some code relate to this and it worked successfully.
function ajaxToParseJson(){
AUI().use('aui-io-request', function(A){
A.io.request('${jsonAjaxURL}', {
dataType:'json',
method: 'post',
data: {
execute: 'JsonLogic',
numberVal:'Pass Json String Here if needed from Screen'
},
on: {
success: function()
{
var empName = this.get('responseData').name;
var id = this.get('responseData').id;
console.log("Name: "+empName);
console.log("Id: "+id);
/** Since return type of this function is bydefault Json it will return Json still if you want to check string below is the way**/
var data = JSON.stringify(this.get('responseData'));
alert(data);
}
}
});
});
}
I have an Employee Class with two fields id,name.