How do I update foreign key with odata json - dynamics-crm

Expected behavior: User clicks on Register button and record is created in related entity. This has worked up til now but now we have requirement to update the foreign key based on a lookup on the current form. How do I accomplish this? The pasted code below throws error in browser "Error on the creation of record; Error – Bad Request"
// JScript source code
CreateButton = function () {
var fieldTable = crmForm.all.new_registerbutton_d;
var html = "<TABLE border=0 cellSpacing=0 cellPadding=0><TBODY><TR><TD width=0px>" + fieldTable.innerHTML + "</TD><TD width=200><INPUT style='BACKGROUND-COLOR: #d8e8ff' onclick=Button_OnClick() value='Register' type=button></TD></TR></TBODY></TABLE>";
fieldTable.innerHTML = html;
document.all.new_registerbutton.style.display = 'none';
crmForm.all.new_registerbutton_c.innerText = "";
}
Button_OnClick = function () {
//var new_se_registration = new Object();
var invitationName = Xrm.Page.getAttribute("new_name").getValue();
//new_se_registration.new_name = invitationName;
var invitationGUID = Xrm.Page.data.entity.getId().replace('{', '').replace('}', '');
alert(invitationGUID);
var value = new Array();
value[0] = new Object();
value[0].id = invitationGUID;
value[0].name = invitationName;
//var invitation = {
//id: invitationGUID, name: invitationName, entityType: "new_se_registration"
//};
//var invitation= { Id: invitationGUID, LogicalName: "new_se_registration", Name: invitationName };
//value[0].entityType = Xrm.Page.data.entity.getEntityType();
//new_se_registration.new_new_se_invitation_new_se_registid.setValue([{ id: invitationGUID, name: invitationName, entityType: "new_se_registration"}]);
//new_se_registration.new_new_se_invitation_new_se_registid = invitation;
//new_se_registration.new_eventname= Xrm.Page.getAttribute("new_eventname").getValue();
//new_invitationid is the Event id
var lookupItem = new Array;
lookupItem = crmForm.all.new_invitationid.DataValue;
var eventname = lookupItem[0].name;
//new_se_registration.new_eventname = eventname;
lookupItem = crmForm.all.new_invitationid.DataValue;
var new_se_registration = {
new_new_se_invitation_new_se_registid: {
__metadata: { type: "Microsoft.Crm.Sdk.Data.Services.EntityReference" },
Id: invitationGUID,
LogicalName: invitationName
},
new_name: invitationName,
new_eventname: eventname
};
//alert ( eventname);
// end Ek - adding event name
//deleteRecord(new_se_registration.new_name, "new_se_registrationSet");
var reg = Xrm.Page.getAttribute("new_registered").getValue();
if (reg == null) {
reg = "N";
}
if (reg != "Y") {
//Xrm.Page.getAttribute("new_registered").setValue("Y");
//alert(reg);
//return;
createRecord(new_se_registration, "new_se_registrationSet", RegisterCompleted, null);
Xrm.Page.getAttribute("new_registered").setValue("Y");
//Xrm.Page.data.entity.attributes.get("new_registered").setSubmitMode("always");
//Xrm.Page.data.entity.save();
}
else {
alert("\"" + Xrm.Page.getAttribute("new_name").getValue() + "\" has been registered already.");
}
}
function RegisterCompleted(data, textStatus, XmlHttpRequest) {
var new_se_registration = data;
Xrm.Page.data.entity.save();
alert("\"" + Xrm.Page.getAttribute("new_name").getValue() + "\" has been registered successfully.");
}
function checkDuplicate() {
alert("test");
}
function deleteRecord(id, odataSetName) {
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'" + id + "')",
beforeSend: function (XMLHttpRequest) {
//XMLHttpRequest.setRequestHeader("Accept", "application/json");
XMLHttpRequest.setRequestHeader("X-HTTP-Method", "DELETE");
},
success: function (data, textStatus, XmlHttpRequest) {
alert("Record deleted successfully!");
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
alert("Error while deletion – " + errorThrown);
}
});
}
function createRecord(entityObject, odataSetName, successCallback, errorCallback) {
var jsonEntity = window.JSON.stringify(entityObject);
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName,
data: jsonEntity,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
if (successCallback) {
successCallback(data.d, textStatus, XmlHttpRequest);
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
if (errorCallback)
errorCallback(XmlHttpRequest, textStatus, errorThrown);
else
alert("Error on the creation of record; Error – " + errorThrown);
}
});
}

Solved. Case sensitivity. Was using wrong case for new_new_se_invitation_new_se_registId.
var new_se_registration = {
new_new_se_invitation_new_se_regist**I**d: {
__metadata: { type: "Microsoft.Crm.Sdk.Data.Services.EntityReference" },
Id: invitationGUID,
LogicalName: invitationName
},
new_name: invitationName,
new_eventname: eventname
};

Related

I can't pass the request value to controller laravel

Hi I'm new to Laravel and I'm having problem in passing the request properly in my controller which is a resource for update function I'm using Laravel 8. there is no error with the syntax it just return the request is empty. I paste my code for references.
my AJAX Request
let url = '/companystructure/1';
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: url,
type: "PATCH",
data: {
'fullname' : 'albert'
},
processData: false,
contentType: false,
success: function(response) {
console.log(response);
//alert(response);
//location.reload();
},
error: function (xhr, ajaxOptions, thrownError) {
var error = $.parseJSON(xhr.responseText) || thrownError;
var errorMsg = error['message'] || thrownError;
var errorObj = error.errors || [];
if (errorObj) {
Object.keys(errorObj).forEach(function (key){
if (errorObj[key][0].length <= 1 ) {
errorMsg = errorMsg + '<br/>' + errorObj[key];
} else {
errorMsg = errorMsg + '<br/>' + errorObj[key][0];
}
});
}
md.showNotification(errorMsg, 'danger');
}
});
and here is controller
public function update(Request $request, $id)
{
return response()->json($request);
}
and here is my Route
Route::resource('companystructure', CompanyStructureController::class);
this is the return I receive from my controller
type: 'PATCH' does not exists on HTTP methods thus will not be recognized by Laravel.
Try this:
let url = '/companystructure/1';
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: url,
type: "POST", /// UPDATE
data: {
'fullname' : 'albert',
'_method': 'PATCH', /// UPDATE
},
processData: false,
contentType: false,
success: function(response) {
console.log(response);
//alert(response);
//location.reload();
},
error: function (xhr, ajaxOptions, thrownError) {
var error = $.parseJSON(xhr.responseText) || thrownError;
var errorMsg = error['message'] || thrownError;
var errorObj = error.errors || [];
if (errorObj) {
Object.keys(errorObj).forEach(function (key){
if (errorObj[key][0].length <= 1 ) {
errorMsg = errorMsg + '<br/>' + errorObj[key];
} else {
errorMsg = errorMsg + '<br/>' + errorObj[key][0];
}
});
}
md.showNotification(errorMsg, 'danger');
}
});

Updating Dygraph with ajax

I have below code which pull data from mysql using ajax json and draw Dygraph chart which it works fine but when my problem is updating the chart.
When I try to update the graph I am getting this error:
Uncaught ReferenceError: g is not defined
which is already defined
all these code are in document ready fucntion
// get data from server
$.ajax({
type: 'POST',
url: 'php/proccess.php',
data: {
type: "jobgraph",
job: job
},
dataType: "json",
success: function(response) {
//console.log(response);
var i = 0;
$.each(response, function(key, value) {
test[i] = [new Date(value[0]), value[1] / 1000, value[2]];
i++;
});
if (test) {
document.addEventListener("mousewheel", function() {
lastClickedGraph = null;
}, false);
document.addEventListener("click", function() {
lastClickedGraph = null;
}, false);
if (response) {
var g = new Dygraph(document.getElementById("noroll"),
test, {
labels: ["Date", "Voltage", "Temp"],
digitsAfterDecimal: 3,
interactionModel: {
'mousedown': downV3,
'mousemove': moveV3,
'mouseup': upV3,
'click': clickV3,
'dblclick': referesh,
'mousewheel': scrollV3
}
}
);
}
}
},
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 500) {
alert('Internal error: ' + jqXHR.responseText);
} else {
console.log(errorThrown);
}
},
});
// update Data every 2 second by pulling new data from mysql server
window.intervalId = setInterval(function() {
$.ajax({
type: 'POST',
url: 'php/proccess.php',
data: {
type: "jobgraph",
job: job
},
dataType: "json",
success: function(response) {
//console.log(response);
var i = 0;
$.each(response, function(key, value) {
test[i] = [new Date(value[0]), value[1] / 1000, value[2]];
i++;
});
//console.log(test);
g.updateOptions({
'file': test
});
},
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 500) {
alert('Internal error: ' + jqXHR.responseText);
} else {
console.log(errorThrown);
}
},
});
}, 2000); </pre>
//end update
In your setup, you define the graph with:
var g = new Dygraph(...
var limits the scope of g, so it's not accessible in your later call. Make the g variable available globally, or in a variable that you pass between functions.

How to send post ajax request from (.js) file to Spring MVC Controller?

(.js)
$.ajax({
type: "POST",
//contentType : "application/json",
dataType : "json",
url: "getStateNames",
//url:"http://localhost:8081/Mining_22_11_17/pages/admin/a.jsp",
cache: false,
data: "region=" + re + "& stId=" + state_id,
success: function(response){
//$('#result').html("");
alert("hiiii state list");
var obj = JSON.parse(response);
alert("state list" + obj);
//$('#result').html("First Name:- " + obj.firstName +"</br>Last Name:- " + obj.lastName + "</br>Email:- " + obj.email);
},
error: function(){
alert('Error while request..');
}
});
Spring MVC Controller
#RequestMapping(value="/getStateNames",method = RequestMethod.POST)
public #ResponseBody RegionDistrict add(HttpServletRequest request, HttpServletResponse response,#RequestParam String region, #RequestParam String stId) {
System.out.println("Get state");
}
By running this program I am getting 404 error.I want to send request using POST only.
$("#yourID").click(function(event) {
var region = $('#id').val();
var state_id = $('#edited').val();
$.post("${pageContext.request.contextPath}/getStateNames", {
region : region ,
state_id : state_id
}, function(data) {
//var json = JSON.parse(data);
//...
}).done(function(data) {
alert("hiiii state list");
swal("success");
//location.reload();
}).fail(function(xhr, textStatus, errorThrown) {
}).complete(function() {
//$("#btn-save").prop("disabled", false);
});
});
try this hope its works fine
$.ajax({
type: "POST",
url: "/getStateNames",
data: { region: re, stId: state_id },
success : function(response) {
alert(JSON.stringify(resoinse));
},
error: function(){
alert('Error while request..');
}
});
This should work, tell me if this solves your problem

Data Inserted Successfully but ajax throwing error

Here is my ajax call function on button click
document.getElementById("btnSubmit").onclick = function ()
{
var txtImageName = $('#txtImageName').val();
var CategoryId = $('#cmbCategory').val();
var ImageURL = $('#txtImageURL').val();
var ImageSource = $('#textEditor').val();
var value = CKEDITOR.instances['textEditor'].getData()
alert
$.ajax({
url: "UrlwebService.asmx/InsertImage",
type: 'POST',
data: { ImageName: txtImageName, ImageUrl3x:ImageURL,ImageSource:value,CategoryId:parseInt(CategoryId) },
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
success: function (Categories) {
// states is your JSON array
alert(Categories);
},
error: function (xhr, err) {
alert("I'm in terror");
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
};
I change content type to application/json it will also throwing me error
and here I'm calling this method.....
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public void InsertImage(string ImageName, string ImageUrl3x, string ImageSource, int CategoryId)
{
var result = ImageRepo.InsertImage(ImageName,ImageUrl3x,ImageSource,CategoryId);
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
Context.Response.Write(js.Serialize(result));
}

jQuery Form plugin doesn't calls Method in IE 8

I am trying to upload files to server, but when i am submitting form it doesn't calls ActionResult. It works in chrome, FF but not in IE. When i am removing enctype="multipart/form-data" attribute from form in IE, then it calls method, but without file uploading...
I have such input:
<input id="jqueryfileupload" type="file" name="files" data-upload-id="#documentUniqueId"
data-url="#Url.Action(MVC.Profile.Documents().AddRouteValue("documentUniqueId", documentUniqueId))" multiple>
jQuery code:
$(document).on('change', '.documents-upload-container #jqueryfileupload', function (e) {
e.preventDefault();
e.stopPropagation();
var $this = $(this);
//input itself is not in the form tag, so i am creating form here and
//submitting it this way
var formContainer = $('<form action="' + $this.data('url') + '" enctype="multipart/form-data" method="POST"></form>');
$this.appendTo(formContainer);
var contentTypeOption = $.browser.msie ? 'text/html' : 'application/json';
var iframeOption = $.browser.msie ? true : false;
var options = {
dataType: 'json',
//contentType: contentTypeOption,
//iframe: iframeOption,
method: 'POST',
success: function (response, textStatus, xhr, form) {
alert(response);
},
error: function (xhr, textStatus, errorThrown) {
alert(xhr);
alert(textStatus);
alert(errorThrown);
},
clearForm: true
};
$(formContainer).ajaxSubmit(options);
return false;
});
There are no errors and alerts are not throwing at all in IE. Just method is not called...
Action Method:
[HttpPost]
public virtual ActionResult Documents(IEnumerable<HttpPostedFileBase> files, string documentUniqueId)
{
var result = new ContentResult();
if (files != null)
{
foreach (var item in files)
{
string docName = documentUniqueId + "_" + item.FileName;
var filename = Path.Combine(Server.MapPath("~/App_Data"), docName);
item.SaveAs(filename);
}
var docs = files.Select(x => new
{
url = Url.Action(MVC.Profile.Documents(documentUniqueId + "_" + x.FileName, x.ContentType)),
name = x.FileName,
contentType = x.ContentType,
id = documentUniqueId + "_" + x.FileName
});
result.Content = new JavaScriptSerializer().Serialize(docs);
return result;
}
result.Content = new JavaScriptSerializer().Serialize(new { success = false });
return result;
}
[HttpGet]
public virtual ActionResult Documents(string fileName, string contentType)
{
var docPath = Path.Combine(Server.MapPath("~/App_Data"), fileName);
return File(docPath, contentType);
}
I use this plugin : http://malsup.com/jquery/form/
I think you are not inserting the form in the page. that's the problem. you have to add formContainer.appendTo(container);
try this code:
$(document).on('change', '.documents-upload-container #jqueryfileupload', function (e) {
e.preventDefault();
e.stopPropagation();
var $this = $(this);
var container = $this.parents('.documents-upload-container').addClass("current-container");
var formContainer = $('<form action="' + $this.data('url') + '" enctype="multipart/form-data" method="post"></form>');
$this.appendTo(formContainer);
formContainer.appendTo(container);
var contentTypeOption = $.browser.msie ? 'text/plain' : 'application/json';
var iframeOption = $.browser.msie ? true : false;
var options = {
dataType: 'json',
contentType: contentTypeOption,
//iframe: iframeOption,
method: 'POST',
//data: { 'isIE': iframeOption },
success: function (response, textStatus, xhr, form) {
alert(response);
},
error: function (xhr, textStatus, errorThrown) {
alert(xhr);
alert(textStatus);
alert(errorThrown);
},
clearForm: true
};
formContainer.ajaxSubmit(options);
return false;
});

Resources