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");
});
Related
My Ajax call is really simple as below:
function ajax(reqUrl, params , callback) {
console.log("Request URL "+reqUrl);
var cond;
cond = $.ajax({
type: 'post',
url: reqUrl,
data: params,
error:function(){ alert("some error occurred") },
success: callback
});
console.log("Server response "+cond.readyState);
}
// Call it as
var url = "/getResult";
var params = {};
params.param1 = "test1";
params.param2 = "test2";
ajax(url, params, function(returnCallback) {
console.log(returnCallback);
alert("Success");
});
That works fine in most cases. But sometimes (about 1 times in 3) it doesn't return anything to callback.
I found many questions and answers for Not working ajax in Safari but fine in chrome and FireFox. My problem is different from them, because it's fine most of the time (I don't mean it was not fine usually because when I refresh my browser, that may cause my ajax call to work).
My main question is why does my ajax call sometimes fail? I don't get any errors on my JS console. When this situation, I refresh my browser to get my ajax call to. Any Ideas?
Update:
I found that sometimes my ajax call method didn't call out because console.log("Request URL "+reqUrl); did not execute. When I don't want to refresh my browser, I clicked many times on my page's link to produce result. will something late to execute?
Finally, I found error .. Safari doesn't reload my JavaScript files again even disable Cache. So I put all of my JS code into:
$(document).ready(function(){
// start load my js functions
init();
});
to reload my JS files when my page was ready. Cheer !
I also met this problem.
When I moved all code into $(function() {}), it worked.
After that, I found I had defined a variable named key, which caused the problem.
Just rename it, all things will be running.
This seems to be a Safari issue. In this post there is a suggestion to add a beforeSend to your ajax-request.
In your case:
cond = $.ajax({
type: 'post',
url: reqUrl,
data: params,
beforeSend: function (event, files, index, xhr, handler, callBack) {
$.ajax({
async: false,
url: 'closeconnection.php' // add path
});
},
error:function(){ alert("some error occurred") },
success: callback
});
Please Test below Code. it is working fine.
$.ajax({
type: "POST",
url:'#Url.Action("getResult","Controller")',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data) {
alert("here" + data.toString());
});
This is use for MVC application.
$.ajax({
type: "POST",
url:'getResult',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("here" + data.toString());
});
For Asp.net Application :
$.ajax({
type: "POST",
url:'getResult',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("here" + data.toString());
});
if u have still the issue than please post ur complete code here. i will test and reply soon
Below is an Ajax POST variable I use to return some information to an ASP MVC3 View. However, I cannot get the .dialg() pop-up function to work. Right now you click on the icon that calls GetProgramDetails(pgmname), and nothing happens. First time using Ajax, so any suggestions would be appreciated. Thx!
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js" type="text/javascript"></script>
<script type="text/javascript">
function GetProgramDetails(pgmname) {
var request = $.ajax({
type: 'POST',
url: '/BatchPrograms/PopDetails',
data: { programName: pgmname },
dataType: 'html'
});
request.done(function (data) {
$('#data').dialog();
});
</script>
EDIT
I've updated the request.done function to include a simple alert to see if the code was being called. After stepping through with Chrome's debugger, I saw that the code inside was completely skipped over.
request.done(function (data) {
alert("HERE!");
$('#programExplanation').html(data);
});
SECOND EDIT
Here is the controller code the ajax is returning a value from:
[HttpPost]
public string PopDetails(string programName)
{
BatchPrograms batchprograms = db.BatchPrograms.Find(programName);
if (batchprograms == null) return string.Empty;
StringBuilder s = new StringBuilder();
s.Append(batchprograms.ProgramName + " - " + batchprograms.ShortDescription);
s.Append("<br />Job Names: " + batchprograms.PrdJobName + ", " + batchprograms.QuaJobName );
s.Append("<br /> " + batchprograms.Description);
return s.ToString();
}
You need to use the success method to handle the callback, like so:
var request = $.ajax({
type: 'POST',
url: '/BatchPrograms/PopDetails',
data: { programName: pgmname },
dataType: 'html'
}).success(function(data){ $('#data').dialog()} );
This will launch the dialog for you, but if you want to get the response data to work with it, you can have GetProgramDetails take a second parameter which is a callback for after the data is loaded like so:
function GetProgramDetails(pgmname, callback) {
var request = $.ajax({
type: 'POST',
url: '/BatchPrograms/PopDetails',
data: { programName: pgmname },
dataType: 'html'
}).success(callback);
}
This way after the response is received you can handle what to do with the data in your implementation of the callback, in this case it seems like you will be setting data in the dialog and launching the dialog.
Problem: Check box value display null in controller.cs. but it is working perfectly according to selection of row from jqgrid. But when I select any row and update all the field it will pass to the controller with modified value but only IsEnabled field comes null.
I have Database Field called IsEnabled which has Bit data type.
I have written following code in .cshtml
<input type="checkbox" value='Yes' offval='No' name="IsEnabled" />
I am using following code to bind check box value as per in database
grid.jqGrid('GridToForm', gsr, "#order");
I have save button. When I click on save following code will execute
$("#btnSave").click(function () {
var data = JSON.stringify($('#order').serializeObject());
var href = '#Url.Action("SaveData", "Users")';
var ajaxResponse = $.ajax({
type: "post",
url: href,
dataType: 'json',
data: data,
contentType: "application/json; charset=utf-8",
success: function (result) {
if (result.Success == true) {
alert("Success");
}
else {
alert("Error: " + result.Message);
}
}
});
Following code written in Controller.cs
(in FormValue it will show all the updated value correctly except IsEnabled, it will display always null.)
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveData(User FormValue)
{
string message = "";
return Content(message);
}
You must delete this code ( if use jquery ajax )
[AcceptVerbs(HttpVerbs.Post)]
when you use post back and send class use above code
send class with jQuery use this code:
try it:
$.ajax({
type: "post",
url: href,
dataType: 'json',
data: SON.stringify({ FormValue : { ID : $('#controlIdName').val() , Name : $('#ControlName').val() } }),
contentType: "application/json; charset=utf-8",
success: function (result) {
if (result.Success == true) {
alert("Success");
}
else {
alert("Error: " + result.Message);
}
}
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.
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"