I'm trying to send data to the controller using this AJAX call of type POST but it's sending null values to the controller. Through this code I want to make new records in the Microsoft Dynamics 365 CRM database.
var formdata = new FormData();
var rowCount = $(".newRow").length;
var projectarray = [];
var datearray = [];
var amountarray = [];
for (var i = 0; i < rowCount; i++) {
projectarray[i] = $("#ProjectType_" + i).val();
datearray[i] = $("#ClaimExpenseDate_" + i).val();
amountarray[i] = $("#Amount_" + i).val();
}
formdata.append("projectarray", projectarray);
formdata.append("datearray", datearray);
formdata.append("amountarray", amountarray);
$.ajax({
url: "#Url.Action("SetClaimDetails", "Claim")",
type: "POST",
data: formdata,
processData: false,
contenttype: false,
success: function (data) {
debugger;
window.location.href = "ess/claim";
alert("Submit Successful!");
},
error: function (err) {
window.location.href = "";
alert("Submit Failed!");
}
});
Here is my controller method which is storing null values instead of the values passed by the AJAX call. And because of this I'm not able to create new records in the database.
public ActionResult SetClaimDetails(string projectarray, string datearray, string amountarray)
{
try
{
Entity item = new Entity("bam_expenseclaims");
item["bam_expdate"] = Convert.ToDateTime(datearray);
item["bam_amount"] = amountarray;
item["bam_project"] = new EntityReference("new_project", Guid.Parse(projectarray));
globalService.Connection.Create(item);
}
catch (Exception ex)
{
XmlConfigurator.Configure();
ILog log = LogManager.GetLogger("TechnicalErrorAppender");
log.Error(string.Empty);
throw ex;
}
return View(Constant.CLAIMPATH);
}
Related
Function which is use to take input data from HTML
function saveclickdata()
{
var allData = {
InvNo:document.getElementById('TbInvNo').value,
GrossSale:document.getElementById('TbOrderTotal').value,
discount:document.getElementById('TbDiscount').value,
CusCash:document.getElementById('TbCash').value,
CusBal:document.getElementById('TbBalance').value,
};
$.ajax({
url: "\Controllers\POSController.cs\SaveData",
type: 'POST',
data: allData,
success: function (res) {
alert("success");
},
error: function (err) {
alet("Error");
}
});
Api which is in controller used to post data
[HttpPost]
JsonResult SaveData(POSMater collection)
{
if (collection.InvNo.ToString() == null)
{
var LocalInvNo = (from b in db.TblPOSMasters select b).FirstOrDefault();
int MaxInvNo = Convert.ToInt32(LocalInvNo) + 1;
collection.InvNo = MaxInvNo;
TblPOSMaster master = new TblPOSMaster();
master.InvNo = collection.InvNo;
master.AddBy = 1;
master.AddDate = DateTime.Now;
master.CashStatus = "A";
master.CompId = 1;
//master.CreditAmt = collection.CreditAmt;
//master.CrCardNo = collection.CrCardNo;
master.CusCash = collection.CusCash;
master.CusId = 1;
master.GrossSale = collection.GrossSale;
db.TblPOSMasters.Add(master);
db.SaveChanges();
}
else
{
return Json(collection);
}
return Json(collection);
}
What should i do? My html button working properly but still not able to call api
I think you ought to use forward slashes (/) in your URL
Hy.
I want to make dropdownlist cascadin. select dropdownlist and send editorfor.but
Cannot set property 'value' of null error .
I would like to send a value to editorfor a value of dropdownlist.
Can you help me?
public JsonResult GetPrice(string log)
{
int id = 1;
HomeController.sqlconnection con = new HomeController.sqlconnection();
string FIRMA = "select t.FIRMA,t.donem FROM dbo.TBLFRM as t where t.ID=" + id + "";
SqlCommand cmd = new SqlCommand(FIRMA, con.connect());
SqlDataReader rdrr = cmd.ExecuteReader();
rdrr.Read();
string firma = rdrr["FIRMA"].ToString();
string donem = rdrr["DONEM"].ToString();
ExtreModel item = new ExtreModel();
item.ItemList = new List<ExtreModel>();
string urun = "select P.PRICE from DBO.LG_" + firma + "_PRCLIST as p,DBO.LG_" + firma + "_ITEMS as I WHERE P.CARDREF=I.LOGICALREF AND P.CARDREF=" + log + "";
SqlCommand cmdd = new SqlCommand(urun, con.connect());
SqlDataReader rdr = cmdd.ExecuteReader();
rdr.Read();
string PRICE = rdr[0].ToString();
con.connect().Close();
return Json(PRICE, JsonRequestBehavior.AllowGet);
}
<script>
$("#LOGI").change(function () {
var select = $(this);
var cityname = select.val();
if (cityname != "") {
$.ajax({
method: "GET",
url: '/Mobil/GetPrice' + '?log=' + cityname,
beforeSend: function () {
}
}).done(function (result) {
document.getElementById("fyt").value = result.PRICE;
});
} else {
}
});
</script>
The problem seems coming from this return statement:
return Json(PRICE, JsonRequestBehavior.AllowGet);
This statement returns plain string value which doesn't contain PRICE property, so result.PRICE contains null value and causing null property assignment error message. If you want to return the price value, simply use this inside done function:
document.getElementById("fyt").value = result;
or in jQuery version:
$('#fyt').val(result);
But if you still want to return PRICE property, specify it inside JSON data:
return Json(new { PRICE = PRICE }, JsonRequestBehavior.AllowGet);
And the AJAX callback should be look like this:
$("#LOGI").change(function () {
var cityname = $(this).val();
if (cityname != "") {
$.ajax({
type: "GET",
url: '/Mobil/GetPrice',
data: { log: cityname }
}).done(function (result) {
$("#fyt").val(result.PRICE); // now the price property should exist
});
} else {
// do something else
}
});
this is my scenario. As I am new to Microsoft Dynamics coding, need a solution for my code.
I have two entities named Acc and Con, where Acc is parent and Con is child entity of Acc.
I have created a lookup field of Acc in Con entity along with fields with similar datatype in the two entities.
So, whenever a change in parent record is made in the fields and saved, the changes should be done automatically in the corresponding fields of the child record.
The part I get the error is to update but am able to retrieve the code. So the record fails to update.
The error I get now is
ReferenceError: FetchRecordsCallBack is not defined at Object.GetRecs.jQuery.ajax.success
Your answers and suggestions are requested and welcome. :) Here below is my code.
function accupdate() {
debugger;
var PrvdLocData;
var name;
var age;
var sex;
var address;
var phonenumber;
var degree;
var sslcpercentage;
var hscpercentage;
var ugpercentage;
var PrvdLocData = new Array();
var EmpId = Xrm.Page.data.entity.getId();
//parent fields
if (Xrm.Page.getAttribute("new_name").getValue() != null) {
name = Xrm.Page.getAttribute("new_name").getValue();
}
if (Xrm.Page.getAttribute("new_age").getValue() != null) {
age = Xrm.Page.getAttribute("new_age").getValue();
}
if (Xrm.Page.getAttribute("new_sex").getValue() != null) {
sex = Xrm.Page.getAttribute("new_sex").getValue();
}
if (Xrm.Page.getAttribute("new_address").getValue() != null) {
address = Xrm.Page.getAttribute("new_address").getValue();
}
if (Xrm.Page.getAttribute("new_phonenumber").getValue() != null) {
phonenumber = Xrm.Page.getAttribute("new_phonenumber").getValue();
}
if (Xrm.Page.getAttribute("new_degree").getValue() != null) {
degree = Xrm.Page.getAttribute("new_degree").getValue();
}
if (Xrm.Page.getAttribute("new_sslcpercentage").getValue() != null) {
sslcpercentage = Xrm.Page.getAttribute("new_sslcpercentage").getValue();
}
if (Xrm.Page.getAttribute("new_hscpercentage").getValue() != null) {
hscpercentage = Xrm.Page.getAttribute("new_hscpercentage").getValue();
}
if (Xrm.Page.getAttribute("new_ugpercentage").getValue() != null) {
ugpercentage = Xrm.Page.getAttribute("new_ugpercentage").getValue();
}
var context = Xrm.Page.context;
var serverurl = context.getClientUrl();
var ODatapath = serverurl + "/XRMServices/2011/OrganizationData.svc";
var retrieveResult = new XMLHttpRequest();
var dtqeurl = ODatapath + "/new_conSet?$select=new_name,new_YourAge,new_YourSex,new_HomeAddress,new_Contact,new_DegreeType,new_SSLCPercent,new_HSCPercent,new_conId,new_UGPercent&$filter=new_AccName/Id eq guid'" + EmpId + "'";
GetRecs("PrvtLoc", dtqeurl);
function GetRecs(entity, url) {
jQuery.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: url,
async: false,
beforeSend: function XMLHttpRequest(XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
if (data && data.d != null && data.d.results != null) {
AddRecordsToArray(data.d.results, entity);
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
// alert("Error : has occured during retrieval of the records ");
}
});
}
function AddRecordsToArray(result, entity) {
$.each(result, function () {
if (entity == "PrvtLoc")
PrvdLocData.push(this);
});
}
if (PrvdLocData.length > 0) {
for (i = 0; i < PrvdLocData.length; i++) {
//Object Assigning
var crmobject = new Object();
//Variable declaration for Child entity's primarykey (ID)
var childId = PrvdLocData[i].new_conId;
//Setting child entitiy's value with parent entity's variable
crmobject.new_name = name;
crmobject.new_YourAge = parseInt(age);
crmobject.new_YourSex = sex;
crmobject.new_HomeAddress = toString(address);
crmobject.new_Contact = parseInt(phonenumber);
crmobject.new_DegreeType = degree;
crmobject.new_SSLCPercent = sslcpercentage;
crmobject.new_HSCPercent = hscpercentage;
crmobject.new_UGPercent = ugpercentage;
// update starts...
var serverUrl = Xrm.Page.context.getClientUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var crmobject = new Object();
// Specify the ODATA entity collection
var ODATA_EntityCollection = "/new_conSet";
var jsonEntity = window.JSON.stringify(crmobject);
//Asynchronous AJAX function to Create a CRM record using OData
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection + "(guid'" + childId + "')",
data: jsonEntity,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
},
success: function (data, textStatus, XmlHttpRequest) {
alert("updated");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("fail to update");
}
});
}
}
}
crmobject.new_name = name;
crmobject.new_YourAge = parseInt(age);
crmobject.new_YourSex = { Value: sex };
crmobject.new_HomeAddress = address;
crmobject.new_Contact = parseInt(phonenumber);
crmobject.new_DegreeType = { Value: degree };
crmobject.new_SSLCPercent = parseFloat(sslcpercentage).toFixed(2);
crmobject.new_HSCPercent = parseFloat(hscpercentage).toFixed(2);
crmobject.new_UGPercent = parseFloat(ugpercentage).toFixed(2);
I have a 'ng-grid' table that have 2 types of data source. One is from my database using a function called getContributors(), and another one is from a list of api(s).
The getContributors function is like the default function in the ng-grid tutorial.
function getContributors() {
var deferred = $q.defer();
$http.get(contributorsFile)
.then(function(result) {
contributors = result.data;
deferred.resolve(contributors);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
My method for loading the multiple api data is to load the database data first, and then after all the database data is all loaded it will make a request to the api using a parameter from the database data
var ajax_wait_count = 0;
gridService.getContributors().then(function(data) {
// Looping each data with angular.forEach()
angular.forEach(data, function(value, key){
var this_uid = value['uid'];
// if(ajax_wait_count==0)
// {
$timeout(function(){
$.ajax({
url: "<?php echo $glob_base_url; ?>api/getrank.php",
type: 'POST',
data: { id: this_uid },
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success: function (json) {
// do stuff with json (in this case an array)
// json = jQuery.parseJSON(json);
data[key]['ranked_tier'] = json;
// console.log(json);
},
error: function () {
// alert("Error");
}
});
$.ajax({
url: "<?php echo $glob_base_url; ?>api/getlevel.php",
type: 'POST',
data: { id: this_uid },
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success: function (json) {
// do stuff with json (in this case an array)
// json = jQuery.parseJSON(json);
data[key]['level'] = json['level'];
// console.log(json);
},
error: function () {
// alert("Error");
}
});
$.ajax({
url: "<?php echo $glob_base_url; ?>api/getsummonercreate.php",
type: 'POST',
data: { id: this_uid },
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success: function (json) {
// do stuff with json (in this case an array)
// json = jQuery.parseJSON(json);
if (json != 0) {
var date_c = json[0]['create_date'];
date_c = date_c.replace(' ', 'T');
new_date = new Date(date_c);
// console.log(json);
var datestring = new_date.format("yyyy-mm-dd HH:MM:ss");
data[key]['summoner_create_date'] = datestring;
}
else if (json == 0) {
data[key]['summoner_create_date'] = "";
}
},
error: function () {
// alert("Error");
}
});
$.ajax({
url: "<?php echo $glob_base_url; ?>api/getlastplayed.php",
type: 'POST',
data: { id: this_uid },
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success: function (json) {
// do stuff with json (in this case an array)
// json = jQuery.parseJSON(json);
if (json != "null" && json != null) {
var datedatas = json;
var datearray = [];
var thedatestr = "";
var loopidx = 1;
now_date = new Date();
now_date.setHours(0);
now_date.setMinutes(0);
now_date.setSeconds(0);
now_date.setDate(now_date.getDate() - 2);
next_date = new Date();
next_date.setHours(23);
next_date.setMinutes(59);
next_date.setSeconds(59);
// next_date.setDate(next_date.getDate());
angular.forEach(datedatas, function (value3, key3) {
datearray[key3] = parseInt(value3['createDate']);
});
datearray.sort();
datearray.reverse();
var count_played_today = 0;
angular.forEach(datearray, function (value2, key2) {
if (loopidx == 1) {
thedatestr = value2;
}
date_compare = new Date(parseInt(value2));
if (date_compare.getTime() >= now_date.getTime() && date_compare.getTime() < next_date.getTime()) {
count_played_today++;
}
loopidx++;
});
// var date_c = json[0]['create_date'];
// date_c = date_c.replace(' ','T');
var dateinsert = parseInt(thedatestr);
new_date = new Date(dateinsert);
// console.log(json);
var datestring = new_date.format("yyyy-mm-dd HH:MM:ss");
data[key]['last_played_date'] = datestring;
this_date = new Date();
date_diff = dateDiff(new_date.toString(), this_date.toString());
data[key]['last_played_date_qty'] = date_diff.d + " days " + date_diff.h + " hours " + date_diff.m + " minutes";
data[key]['count_played'] = count_played_today;
}
else if (json == "null" || json == null) {
data[key]['last_played_date'] = "";
data[key]['last_played_date_qty'] = "";
data[key]['count_played'] = 0;
}
},
error: function () {
// alert("Error");
}
});
},1500);
ajax_wait_count=0;
// }
ajax_wait_count++;
});
$scope.myData = data;
});
Now, the problem that emerges is :
The loading time for the api data is very long, and because of ajax asynchronous request, I can't make a loading function to delay the data
It appends the api data after the database data, which sometimes confuses the user whether the data is loaded or not
Sometimes in Chrome, the request is too much and it returns "err_insufficient_resources"
My question is,
Can my method of loading the api data be changed so it will make the loading time much faster and more efficient?
To make users less confused about the high amount of data, how can I make the progressbar (angular progress bar) wait for the database data + the api (AJAX) data?
Thank you in advance
This is my action in controller. Which return a List> converting into DataSourceResult.and also Serializing into Json.
[HttpPost]
public ActionResult GetMissingShiftData([DataSourceRequest]DataSourceRequest request)
{
DataTable dtResponse = new DataTable();
var dynamicList = new List<dynamic>();
var myMainList = new List<List<dynamic>>();
List<DataSourceResult> viewResultList = new List<DataSourceResult>();
string RigNumber = string.IsNullOrWhiteSpace( resultData.Filter.SelectedRig.RigNumber) || resultData.Filter.SelectedRig.RigNumber == "ALL" ? "" : resultData.Filter.SelectedRig.RigNumber;
DataSet response = MissingShiftsReportData.GetData(Convert.ToDateTime(resultData.Filter.DateStart), Convert.ToDateTime(resultData.Filter.DateEnd), ConnString, RigNumber);
foreach (DataTable dt in response.Tables)
{
dtResponse = dt;
string[] columnNames = dtResponse.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray();
foreach (DataRow dr in dtResponse.Rows)
{
dynamic myObj = new ExpandoObject();
var p = myObj as IDictionary<string, object>;
Regex rgx = new Regex("[^a-zA-Z0-9]");
for (int i = 0; i < columnNames.Length; i++)
{
string name = dr.Table.Columns[i].ColumnName.Replace(" ", String.Empty);
name = name.Replace(".", String.Empty);
name = name.Replace("(", String.Empty);
name = name.Replace(")", String.Empty);
name = rgx.Replace(name, "");
p[name] = dr[i];
}
dynamicList.Add(p);
}
myMainList.Add(dynamicList);
}
DataSourceResult viewResult = myMainList.ToDataSourceResult(request);
string JsonViewData = JsonConvert.SerializeObject(viewResult.Data);
return new ContentResult { Content = JsonViewData, ContentType = "application/json", ContentEncoding = Encoding.UTF8 };
}
And this is the async call I am doing with Jqery.while I am trying to bind a data source it shows "data[0].Data" is "undefined". How can I make use of 'data'.
$.ajax({
url: "GetMissingShiftData",
type: "post",
datatype: 'json',
success: function (data) {
var list = data[0].Data;
var dataSource = new kendo.data.DataSource({
data: data[0].Data
});
dataSource.read();
return false;
},
error: function (msg) {
toastr.error("Error: " + msg.statusText);
}
});
You are serializing an array (the Data property) and don't need to use the Data field at the client-side:
$.ajax({
url: "GetMissingShiftData",
type: "post",
datatype: 'json',
success: function (data) {
var dataSource = new kendo.data.DataSource({
data: data
});
dataSource.read();
return false;
},
error: function (msg) {
toastr.error("Error: " + msg.statusText);
}
});