How to style nested comments that pulls data from database? - ajax

I want a section to like Facebook comment system. Users will communicate each other. A user can send a post, the others can send comments.
Post
Comment1
Comment2
Comment2.1
Comment2.2
Comment2.2.1
Comment3
Comment3.1
Comment3.1.1
Firstly, I created a web service that I can pull data from a database.
I use this web service with ajax to display my data.
For displaying data, I use table, but using table is not good solution. Because my all design is floating when I open the nested comments.
Is there another suggestion instead of <td><tr> <table>?
function GetComments(postid) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "/arayuzService.asmx/GetComments",
data: '{"postid":"' + postid + '"}',
success: function (data) {
var received= jQuery.parseJSON(data.d);
var posts = received;
var strPosts = "";
$.each(posts, function (index, a) {
strPosts += '<tr><td>' + a.userId + '</td></tr>';
strPosts += "<tr><td><div id='Comment" + a.id + "'></div></td></tr>";
});
$("#postComment" + postid).html(strPosts);
},
error: function (error) {
debugger;
}
});
}

Related

What is a proper way to POST multiple sets of data through AJAX to .Net Core EF Core

I have seen numerous examples, mostly wrong or outdated concepts written a decade ago. I cant seem to find a way to submit multiple variables to the ef core database using Ajax. I can get it to work with one, but cant seem to get it to work with multiple. Not sure if I am doing something wrong? I just get a syntax error on the var dataObjects
Ajax Call
<script type="text/javascript">
$("#cosubmitbutton").click(function () {
if ($('#CompanyId').val() == "-1" || $('#CompanyId').val() == "0") {
toastr.warning("Please select company / Client!");
return false;
}
var dataObjects = {
CompanyId = $("#CompanyId").val();
TechnicalContact = $("#TechnicalContactId").val();
TCEmailAddress = $("#TCEmailAddressId").val();
NumOfWorkstations = $("#NumOfWorkstationsId").val();
NumOfUsers = $("#NumOfUsersId").val();
NumOfServers = $("#NumOfServersId").val();
NumOfFirewalls = $("#NumOfFirewallsId").val();
NumOfSwitches = $("#NumOfSwitchesId").val();
NumOfAps = $("#NumOfApsId").val();
Domain = $("#DomainId").val();
};
//ObjThreadItem = JSON.stringify({ 'ObjThread': ThreadItem});
console.log("Json Stringify CommonPostData: ", JSON.stringify(dataObjects))
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'JSON',
url: '/Onboarding/Client/CreateClientOverview',
type: "post",
data: JSON.stringify(dataObjects),
success: function (result) {
debugger
toastr.success("Information successfully updated on server!");
location.reload();
},
failure: function (response) {
debugger
console.log(response);
}
});
});
</script>
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult CreateClientOverview(ClientOverview Modal)
{
_context.ClientOverview.Add(Modal);
_context.SaveChanges();
return Json(Modal);
}

Harvest Chosen multiselect dropdownlist inconsistently populates with set value

I have a ASP.net webform populated with data from a MS SQL DB, and allows you to edit values.
The web app uses a Harvest Chosen multiselect dropdown list (max=1) to select two different persons picked from the same list of information, but on two separate controls.
When I refresh the page, sometimes both controls are populated with the correct value, sometimes neither or one are. I tested in the console and it is definitely pulling the correct information from the DB, but I must be missing something relating to how these procedures are executed. I have done this work with VB.NET and ASP controllers in the past. This is my first time using AJAX and web method functions. I believe I am missing an update somewhere, or not understanding the order in which code is executed.
I tried explicitly stating the order of operations in the .aspx page, and then doing no update triggers until after all the code for the controller had been executed, but this appears to have broken both controllers (the both end up looking like normal select controllers). Apologies if my terminology is not on point, I am very self-taught. The current state of the code where I get inconsistent application
The .aspx page is as such. Each control has a set of different parameters that affect how it is populated, and what happens when it changes.
<select class="chosen-select" multiple data-placeholder="Assign a scientist" name="ChosenScientist" style="width:800px;" id="cmbChosenScientist">
<script type="text/javascript">
handleChosenControls("select#cmbChosenScientist.chosen-select");
</script>
</select>
<select class="chosen-select" multiple data-placeholder="Assign a supervisor" name="ChosenSupervisor" style="width:800px;" id="cmbChosenSupervisor">
<script type="text/javascript">
handleChosenControls("select#cmbChosenSupervisor.chosen-select");
</script>
</select>
The aspx page passes the controller name to a function which first defines all of the parameters used by the controllers.
function defineChosenControls(controller) {
switch (controller) {
case "select#cmbChosenScientist.chosen-select":
currentData = JSON.stringify({ sqlQueryName: "studyScientist" + "/" + MainContent_txbStudy.value });
populateData = JSON.stringify({ sqlQueryName: "userList" });
changeData = JSON.stringify({ strControlName: controller, arrValues: JSON.stringify($(controller).val()), strArg1: MainContent_txbStudy.value });
break;
case "select#cmbChosenSupervisor.chosen-select":
currentData = JSON.stringify({ sqlQueryName: "studySupervisor" + "/" + MainContent_txbStudy.value });
populateData = JSON.stringify({ sqlQueryName: "userList" });
changeData = JSON.stringify({ strControlName: controller, arrValues: JSON.stringify($(controller).val()), strArg1: MainContent_txbStudy.value });
break;
}
}
The function that handles the populating the options, setting the current value, and handling changes is as follows:
function handleChosenControls(controller) {
//Purpose: Any time a Chosen control is loaded, changed, etc., this is run.
defineChosenControls(controller);
$(controller).chosen({ max_selected_options: 1 });
//Script for populating the control
$.ajax({
type: "POST",
url: "ClientToServer.aspx/GetDT",
data: populateData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
for (line of JSON.parse(response.d)) {
$(controller).append('<option value="' + line[Object.keys(line)[0]] + '">' + line[Object.keys(line)[0]] + '</option>');
}
$(controller).trigger("chosen:updated");
},
error: function (response) { console.log("ERROR: Unable to pass changed values from controller " + controller + " to server-side."); }
});
//Script for determining current value during load
$.ajax({
type: "POST",
url: "ClientToServer.aspx/GetDT",
data: currentData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
for (line of JSON.parse(response.d)) {
$(controller).val(line[Object.keys(line)[0]]).trigger("liszt:updated");
console.log(line[Object.keys(line)[0]]);
}
$(controller).trigger("chosen:updated");
},
error: function (response) { console.log("ERROR: Unable to retrieve current value of " + controller + " from server-side."); }
});
//Script for when a value in the control is changed
$(controller).on('change', function (e) {
defineChosenControls(controller);
$.ajax({
type: "POST",
url: "ClientToServer.aspx/PassJqueryControlValue",
data: changeData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
error: function (response) { console.log("ERROR: Unable to pass changed values from controller " + controller + " to server-side."); }
});
});
}
I expect both controls to have the proper value in the DB, and those values are being written in the browser console properly, but the harvest chosen controls are inconsistent.
The solution was to call the code after load.
<script type="text/javascript">
$(window).bind("load", function() {
handleChosenControls("select#cmbChosenScientist.chosen-select");
handleChosenControls("select#cmbChosenSupervisor.chosen-select");
});

Kendo UI - DataSource works when using fetch(), but not read()

I have a Kendo UI DataSource that works when I use fetch(), but when I use the exact same configurtation with read() it fails. This is a problem as I need to retrieve data more than once and I can't do that with fetch().
Here is the DataSource code -
var FieldsDataSource = new kendo.data.DataSource({
transport: {
read: {
url: "../WebServiceAddress",
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
cache: false
},
parameterMap: function() {
return "{some mapping that has been confirmed to work}";
},
schema: {
data: function (data) {
if (data && data.d) {
//execution gets to here and stops
return data.d;
}
else {
return [];
}
},
}
});
Here is the code that calls the DataSource.read() function -
function loadFields() {
FieldsDataSource.read(function() {
var data = this.data();
if (data.length > 0) {
for (var i = 0; i < data.length; i++) {
var dataitem = data[i].Key;
$("#" + dataitem + "_field").prop("checked", data[i].Value);
}
}
});
}
If I change FieldsDataSource.read(function() to FieldsDataSource.fetch(function() everything works, but that doesn't make sense as I was under the improession that read and fetch do the same thing the difference being fetch only gets data once.
What I do know is that the data is being returned from the server, I can see it in fiddler - but the execution stops in the schema section where I flagged it in my code sample.
Apologies if I am asking a really obvious question, but I'm very new to Kendo.
have a look at the kendo demo site, this post explains how to read remote data quite nicely. I beleive the schema.data requires only string value. Configure your model and parse and then just call read(), your datasource.data collection will get populated and then you can play with it.
Also note that datasource.read() is async, thefore you populatefields method should be called from complete event of the datasource, not other way around. eg you might have no data in when populating.
transport: {
read: {
url: "../WebServiceAddress",
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
cache: false,
complete : function () { }
},

how to clear a asp dropdown list and populate using ajax?

What i am trying to do is get a user to change one drop down, which then calls an ajax function which posts to the code behind (vb.net file) then clears and populates another asp dropdown list with the data returned from the function..hope i made sense
<script>
$(document).ready(function () {
$('.manuf').change(function () {
$.ajax({
type: "POST",
url: "ajax.aspx/GetModel",
data: '{' +
'ManufID:"' + $('.manuf').val() + '"' +
'}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
var data = json_parse(msg.d);
if (data.error) {
alert("Error!");
return;
}
alert(data.model);
},
error: function(msg) {
alert('Get Details Failure: ' + msg);
}
});
});
});
</script>
My bad - you can write your ajax call like this -
$.ajax({ url :"/website/myurl", type:"POST", contentType:"application/json;", dataType:"json", data : "{ 'id' : '" + $("select[id*=selCurrentManuf]").val() + "' } ",
success : function (return_data) {
var data = $.parseJSON(return_data);
// code to add the contents of data to other list
$("select[id*=selCurrentModel]").empty().append($("<option>").attr("value","0").text("Choose..."));
// for the dropdown list clear all options and add a 'choose...' as the first option
$.each(data, function (i, d) { $("<option>").attr("value", d.k).text(d.v).appendTo($("select[id*=selCurrentModel]")); });
}, error:function () {
// handle error
}
});
I assume that you know how to fetch data from the backend via ajax. Something like this -
$.ajax({ url :"/website/myurl", type:"POST", dataType:"application/json"; data:"json",
success : function (return_data) {
var data = $.parseJSON(return_data);
// code to add the contents of data to other list
}, error:function () {
// handle error
}
});
Lets say you are getting it in a variable data which is an array.
You may try something like this -
$("select[id*=selCurrentModel]").empty().append($("<option>").attr("value", "0").text("Choose..."));
// for the dropdown list clear all options and add a 'choose...' as the first option
$.each(data, function (i, d) { $("<option>").attr("value", d.k).text(d.v).appendTo($("#ddlExperience")); });
// user $.each to iterate the data object which
You may try things on these lines.... Hope this helps.

Dynamics CRM 2011 form jscript to retrieve lookup data

What are my mistakes, why do I get the "object expected" error, and, eventually, how does one debug jScript ?
I am new to Dynamics CRM and I would like to do a small customisation, which seem to require jScript. The instance (version 2011) is used mostly to manage client support.
There are 2 custom entities with relationships: FundLegalEntity --> SubFund
The Case (Incident) form is linked to the FundLegalEntity and the SubFund.
When user enters a SubFund I would like to have the FundLegalEntity filled automatically (if empty).
My question was: how do I code that ?
With the help of this great tutorial, and the very usefull oData Tool, and great help (below) from user #dub, here is my latest code:
function recalcParent()
{
var lookupValue = Xrm.Page.getAttribute("new_subfundid").getValue();
var subFundId= lookupValue[0].id;
// alert(subFundId);
var request = Xrm.Page.context.getServerUrl() +
"/xrmServices/2011/OrganizationData.svc/new_subfundSet?" +
"$select=new_LegalEntityId&" +
"$filter=new_subfundId eq guid'"+ subFundId+ "'";
// alert(request);
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: request,
async: false,
beforeSend:
function (XMLHttpRequest)
{
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success:
function (data, textStatus, XmlHttpRequest)
{
var result = data.d.results[0];
alert(result);
var parentFundLookup = [{ entityType : "new_fund", id : result.LegalEntityId, name : result.FundLegalEntity}];
// Set the value of the parent fund lookup
},
error:
function (XmlHttpRequest, textStatus, errorThrown)
{
alert('Failed');
}
});
}
I have no more errors, the first 2 alerts (commente out) are giving me correct results.
THe 3rd alert displays "object Object", and the control I expect to update is not updated.
Any hint please ? I suppose the last problem is in the var parentFundLookup = line...
I am a bit confused by all these different names.
Thanks !
Edit:
It's nearly working now: when I modify the sub-fund in the Incident, the Legal Entity gets updated with the correct legal entity name, but the text box has a strange aspect, and the icon at the left of the text box is strange as well. Here is the latest bit of code:
success:
function (data, textStatus, XmlHttpRequest)
{
var result = data.d.results[0];
//alert(result.new_LegalEntityId.Name);
var parentFundLookup = [{ entityType : "new_LegalEntity", id : result.new_LegalEntityId.Id, name : result.new_LegalEntityId.Name}];
Xrm.Page.getAttribute("new_fundlegalentityid").setValue(parentFundLookup);
},
I suspect that the problem lies in the entityType : "new_LegalEntity", but I don't know what to put in there. Any clue on this ? What does that represent ?
Here is a screenshot of the Legal Entity after the Sub-Fund is updated and the script has run.
You can use the Rest endpoint from your script to retrieve data from the organization service. Here's an example to get you started. You can also look at the SDK documentation there's a lot of useful information there.
var subfundid; // get the id from the lookup
var request =
Xrm.Page.context.getServerUrl() +
"/XRMServices/2011/OrganizationData.svc/new_subfundSet?" +
"$select=ParentId&" +
"$top=1&" +
"$filter=new_subfundId eq guid'"+ subfundid + "'";
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: request,
async: false,
beforeSend:
function (XMLHttpRequest)
{
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success:
function (data, textStatus, XmlHttpRequest)
{
var result = data.d.results[0];
var parentFundLookup = [{ entityType : "new_fund", id : result.ParentId, name : result.FundName}];
// Set the value of the parent fund lookup
},
error:
function (XmlHttpRequest, textStatus, errorThrown)
{
alert('Failed');
}
});
Since this code uses JQuery, you'll need to add the JQuery library as a web resource and include it in your form. See CRM 2011 "$ is undefined"

Resources