Here is my code:
function CreateNodeFolder() {
$.ajax({
type: "POST",
async: true,
url: "Default.aspx/GetJson",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (msg) {
eval("var dataobj=" + msg.d);
for(var i=dataobj.length-1; i>=0;i--) {
$("#MainTree").jstree("create_node",$('#A'),"inside",{ data:dataobj[i].TableName,attr : { id : dataobj[i].TableName } },false,false);
}
},
error: function (err) {
alert(err);
},
});
}
function CreateChildNode() {
$("#MainTree").jstree("create_node",$('#'+NodeClickName+''),"inside",{ data:"C",attr : { id : "C" } },false,false);
}
I have a root node which haves ID = "A", first I create node from JSon data. After that, when I use double click event to call CreateChildNode. It doesn't create child node for nodes I create from JSon. It only creates for root node. Please help me to find out why child node can't be created for nodes loading from JSON data.Here is code for calling
double click event.
(#MainTree).jstree({..}).bind("dblclick.jstree", function (event) {
var node = $(event.target).closest("li");
NodeClickName = node[0].id;
inty3 = setInterval(CreateChildNode, 50);
});
Here is how I created root node:
$("#MainTree,#SubTree").jstree({
"json_data": {
"data": [{ "data": 'Select node', "state": 'open', "attr": { "id": 'A' } }],
},
"plugins": ["themes", "json_data", "ui", "dnd", "crrm", "contextmenu"],
})
Related
I'm using ajax and javascript for a game and I created a server using json-server where I keep a db.json file with words that the user can input and become available in the game.
db.json
This is what the json file looks like
{
"words": [
{
"cuvant": "cuvant",
"id": 1
},
{
"cuvant": "masina",
"id": 2
},
{
"cuvant": "oaie",
"id": 3
},
{
"cuvant": "carte",
"id": 4
},
{
"cuvant": "fmi",
"id": 5
},
{
"cuvant": "birou",
"id": 6
},
{
"cuvant": "birou",
"id": 7
},
{
"cuvant": "canapea",
"id": 8
},
{
"cuvant": "pasare",
"id": 9
I managed to get the POST request (adding the words to the db.json) using this:
function addWord() {
var word = document.getElementById("input-name").value;
var info = {
cuvant: word
}
$.ajax({
url:'http://localhost:3000/words',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(info),
succes: function(info) {
console.log(info)
},
error: function(error) {
console.log(error);
}
})
}
This is what I tried for the GET request
But I'm not sure if it's correct.
And I also need a way to get only the value hold by the cuvant key and add it into an array.
window.onload = function() {
function gett() {
$.ajax({
url: 'http://localhost:3000/words',
type: 'GET',
dataType: 'json',
contentType: "application/json",
succes: function(data) {
console.log(data);
},
error: function(data) {
console.log(data)
}
})
.done(function(){
console.log("Over")
})
}
}
I think your code is correct. It was just missing the "s" on "success":
window.onload = function() {
function gett() {
$.ajax({
url: 'http://localhost:3000/words',
type: 'GET',
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data)
}
})
.done(function(){
console.log("Over")
})
}
}
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"
}
]
}
]
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);
});
}
I'm using the following function to load a DataTables table with data from the server. I would like to reload the table with different parameters on a click event only i cant work out how to do this. If i call reload it just reloads with the original parameters if i reinitialise the whole table it throws an error as the table already exists.
I have been looking into fnServerParams but cant work out if it would help or not.
If anyone can point me in the correct direction that would be great.
function LoadRiskProfileModalTable(userId, teamId, riskProfileClass) {
var params = {
userId: userId,
teamId: teamId,
riskProfileClass: riskProfileClass
};
var data = JSON.stringify(params);
//if (!$.fn.DataTable.isDataTable("#riskProfileTable")) {
var table = $("#riskProfileTable").DataTable({
"bProcessing": true,
"sAjaxSource": "WFMHome.aspx/GetRiskProfileDrillThroughDatatable",
"fnServerData": function (sSource, aoData, fnCallback) {
//aoData.push(JSON.stringify(params));
$.ajax({
"dataType": 'json',
"contentType": "application/json; charset=utf-8",
"type": "POST",
"url": sSource,
"data": data,
"success": function (msg) {
var json = jQuery.parseJSON(msg.d);
fnCallback(json);
$("#riskProfileTable").show("fast", function () { $('#riskProfileTableLoading').hide("fast") });
},
error: function (xhr, textStatus, error) {
if (typeof console == "object") {
appendAlert("errorAlertPlaceholder", xhr.responseText, 1, "danger");
console.log(xhr.status + "," + xhr.responseText + "," + textStatus + "," + error);
}
}
});
},
"columns": [
{ "data": "CaseHandler" },
{ "data": "caseAreaText" },
{ "data": "RiskProfileText" },
{ "data": "PassChecks" },
{ "data": "F1Checks" },
{ "data": "F2Checks" },
{ "data": "F3Checks" },
{ "data": "CurrentChecks" }
]
});
//}
//else {
// $('#riskProfileTable').DataTable().ajax.reload();
// }
};
If you just want to replace the data you have now by the data coming from the server, try to replace the success method by:
"success": function (msg) {
var json = jQuery.parseJSON(msg.d); //I assume it's the data set
var table = $("#riskProfileTable").DataTable();
table.rows.clear(); //clear the current data
table.rows.add(json).draw();
$("#riskProfileTable").show("fast", function () { $('#riskProfileTableLoading').hide("fast") });
},
I am populating a JSTree view with ajax commands. My current JS code is as follows
$(document).ready(function() {
$("#navigation").jstree({
"json_data": {
"ajax": {
"url": function (node) {
var nodeId = "";
var url = "";
if (node == -1) {
url = "#Url.Action("BaseTreeItems", "Events")";
} else {
nodeId = node.attr('id');
url = "#Url.Action("EventTreeItems", "Events")" +"?selectedYear=" + nodeId;
}
return url;
},
"dataType": "text json",
"contentType": "application/json charset=utf-8",
"data": function(n) { return { id: n.attr ? n.attr("id") : 0 }; },
"success": function() {
}
}
},
"themes": {
"theme": "classic"
},
"plugins": ["themes", "json_data", "ui"]
});
});
I would like to eliminate the if statement from the "ajax" property and fill it with the JSON data that is coming from the server. The JSON data looks like this
[{"data":{"title":"2012","attr":{"href":"/Events/EventList?selectedYear=2012"}},"attr":{"id":"2012","selected":false,"ajax":"/Events/EventTreeItems?selectedYear=2012"},"children":null,"state":"closed"},.....]
How can I feed the "ajax" property from the json into the "ajax" property in the JSTree?
For future reference I fixed it by doing the following
.jstree({
"json_data": {
"ajax": {
"url": function (node) {
var url;
if (node == -1) {
url = "#Url.Action("BaseTreeItems", "Events")";
} else {
url = node.attr('ajax');
}
return url;
},
"dataType": "text json",
"contentType": "application/json charset=utf-8",
"data": function(n) { return { id: n.attr ? n.attr("id") : 0, ajax: n.attr ? n.attr("ajax") : 0 }; },
"success": function() {
}
}
},