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() {
}
}
},
Related
I have a view and tried to show it directly in a popup by clicking from a webgrid... I get the following error:
jquery-3.2.1.min.js:4 GET http://localhost:54751/Facturas/Save/4176?_=1534975761119 500 (Internal Server Error)
My JS code:
<script>
$(document).ready(function () {
var oTable = $('#myDatatable').DataTable({
"ajax": {
"url" : '/Facturas/GetEmployees',
"type" : "get",
"datatype" : "json"
},
"columns": [
{ "data": "id_docto", "autoWidth": true },
{ "data": "id_Proveedor", "autoWidth" : true},
{ "data": "Nombre_Archivo", "autoWidth": true },
{ "data": "Ruta_Docto", "autoWidth": true },
{ "data": "id_tipo_docto", "autoWidth": true },
{ "data": "Estatus", "autoWidth": true },
{ "data": "Fecha", "autoWidth": true },
{
"data": "id_Proveedor", "width": "50px", "render": function (data) {
return '<a class="popup" href="/Facturas/Save/' + data + '">Editar</a>';
}
},
{
"data": "EmployeeID", "width": "50px", "render": function (data) {
return '<a class="popup" href="/Facturas/Delete' + data + '">Borrar</a>';
}
}
]
})
$('.tablecontainer').on('click', 'a.popup', function (e) {
e.preventDefault();
OpenPopup($(this).attr('href'));
})
function OpenPopup(pageUrl) {
debugger;
var $pageContent = $('<div/>');
$pageContent.load(pageUrl, function () {
$('#popupForm', $pageContent).removeData('validator');
$('#popupForm', $pageContent).removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse('form');
});
$dialog = $('<div class="popupWindow" style="overflow:auto"></div>')
.html($pageContent)
.dialog({
draggable : false,
autoOpen : false,
resizable : false,
model : true,
title:'ActualizaciĆ³n de Datos',
height : 550,
width : 600,
close: function () {
$dialog.dialog('destroy').remove();
}
})
debugger;
$('.popupWindow').on('submit', '#popupForm', function (e) {
var url = $('#popupForm')[0].action;
$.ajax({
type : "POST",
url : url,
data: $('#popupForm').serialize(),
success: function (data) {
if (data.status) {
$dialog.dialog('close');
oTable.ajax.reload();
}
}
})
e.preventDefault();
})
$dialog.dialog('open');
}
})
</script>
My C# code:
[HttpGet]
public ActionResult Save(int id)
{
try
{
using (SiniestrosEntities dc = new SiniestrosEntities())
{
var v = dc.CAT_Doctos_Proveedores.Where(a => a.id_Proveedor == id).FirstOrDefault();
return View(v);
}
}
catch (Exception e)
{
return View("Login");
}
}
Does anyone have an idea why it does not return my view "Save" to my Popup?
I'm trying pushing json inside of array, but when i send the params with Ajax it put 0 instead of Array...
Not really sure how do i get rid of it..
If anyone have any idea how to fix that I'll really appreciate it!
var $selector = $(this).find('.button-selector');
var $element = $(this).find('.button-type');
var $attr = $(this).find('.selector ul li.active').attr('type');
var $text = $(this).find('textarea').val();
var $buttons = [];
$selector.each(function(){
var $titleBtn = $(this).find('input[name=button-title]').val();
if($attr == 'block'){
var $payload = "";
var $value = $element.find('.block-select select').val();
if($value == 1) {
$payload = "JOIN_CONVERSATION_"+story_id+"";
} else if ($value == 2) {
$payload = "NEXT_BITE_"+story_id+"";
} else if ($value == 3) {
$payload = "INSTANT_ARTICLE_"+story_id+"";
}
button = {
"type": "postback",
"title": $titleBtn,
"payload": $payload
};
$buttons.push(button)
} else if($attr == 'url') {
var $url = $element.find('.url-select input[type=url]').val();
var $webView = $element.find('.url-select select').val();
button = {
"type": "web_url",
"url": $url,
"title": $titleBtn,
"webview_height_ratio": $webView
};
$buttons.push(button)
}
});
$.ajax({
async: false,
type: 'POST',
url: '/variable',
dataType: 'json',
data: {
"element":{
"notification_type": notification_type,
"message": {
"attachment": {
"type": "template",
"payload": {
"template_type": "button",
"text": $text,
"buttons": $buttons
}
}
}
}
}
});
The output for buttons is:
"buttons"=>{"0"=>{"type"=>"postback", "title"=>"rwerwe", "payload"=>"JOIN_CONVERSATION_256"}}
Intead of:
"buttons"=>[{"type"=>"postback", "title"=>"rwerwe", "payload"=>"JOIN_CONVERSATION_256"}]
I hope this should fix your case.
You need to use JSON.stringify to first properly serialize your object to JSON, and then specify the contentType: "application/json" so your server understands it's JSON and deserialize it back. This should do the trick:
var jsonData = {
"element":{
"notification_type": notification_type,
"message": {
"attachment": {
"type": "template",
"payload": {
"template_type": "button",
"text": $text,
"buttons": $buttons
}
}
}
}
};
$.ajax({
async: false,
type: 'POST',
url: '/variable',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(jsonData)
});
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") });
},
guys i know its dummy questions but i spent hours on this and cant reach .. I am trying to pass a JSON array to JSP via an AJAX call in another JS file. It is giving me a 404 error. Any help would be appreciated. Here is my code:
function GridLibrary(fileName) {
this.fileName = fileName;
}
GridLibrary.prototype = {
setFileName : function(fileName) {
this.fileName = fileName;
},
getFileName : function() {
return this.fileName;
}
};
GridLibrary.prototype.display = function() {
$.ajax({
url : this.getFileName(),
dataType: "json",
error : function(that, e) {
console.log(e);
},
success : function(data) {
alert("found");
}
});
};
var Json = [{
"id": 1,
"name": "name1",
"age" : 10,
"feedback": "feedback1"
}, {
"id": 2,
"name": "name2",
"age" : 90,
"feedback": "feedback2"
}, {
"id": 3,
"name": "name3",
"age" : 30,
"feedback": "feedback3"
}, {
"id": 4,
"name": "name4",
"age" : 50,
"feedback": "feedback4"
}];
new GridLibrary(Json).display();
You need to have a valid url to send the values to the backend:
function GridLibrary(url, data) {
this.url = url;
this.data = data;
}
GridLibrary.prototype = {
setData: function(data) {
this.data = data;
},
getData: function() {
return this.data;
},
setUrl:function(url){ this.url = url; },
getUrl:function(){ return this.url; },
display : function() {
$.ajax({
url: this.getUrl, // <----the url where you want to send the data
data:this.getData, //<----should be the array data
dataType: "json",
contentType:"application/json", // <----add this contentType
error: function(that, e) {
console.log(e);
},
success: function(data) {
alert("found");
}
});
}
};
var url = '/url/to/send',
data = [{}....];
new GridLibrary(url, data).display();
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"],
})