I've checked through the forum and cant seem to get what i need to work.
On the lead entity, when a user creates a new lead a Workflow runs just before to change some lead fields.
I found out this is only possible through javascript and onload in the entity settings.
I've created the Workflow and a JavaScript file and set it to run onload. The Javascript i have used is:
function callworkfow(workflowId, entityId) {
var request =
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<Execute xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<request i:type="b:ExecuteWorkflowRequest" xmlns:a="http://schemas.microsoft.com/xrm/2011 /Contracts" xmlns:b="http://schemas.microsoft.com/crm/2011/Contracts">
<a:Parameters xmlns:c="http://schemas.datacontract.org/2004/07/System.Collections.Generic">
<a:KeyValuePairOfstringanyType>
<c:key>B3D77337-D5FD-E211-BB05-005056AF0003</c:key>
<c:value i:type="d:guid" xmlns:d="http://schemas.microsoft.com/2003/10/Serialization/">EntityIdValue</c:value>
</a:KeyValuePairOfstringanyType>
<a:KeyValuePairOfstringanyType>
<c:key>2EF8C158-182B-444A-A9DF-FF2DC5E44514</c:key>
<c:value i:type="d:guid" xmlns:d="http://schemas.microsoft.com/2003/10/Serialization /">WorkflowIdValue</c:value>
</a:KeyValuePairOfstringanyType>
</a:Parameters>
<a:RequestId i:nil="true" />
<a:RequestName>ExecuteWorkflow</a:RequestName>
</request>
</Execute>
</s:Body>
</s:Envelope>
var xhr = new XMLHttpRequest();
xhr.open('POST', '/XRMServices/2011/Organization.svc/web', true);
xhr.setRequestHeader('Accept', 'application/xml, text/xml, */*');
xhr.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
xhr.setRequestHeader('SOAPAction', 'http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute');
xhr.onreadystatechange = function () { alert(xhr.status); };
xhr.send(request);
}
However this fails to load.
If anyone could help me i would be very grateful. Just need the JavaScript to simply load a Workflow. Oh and with cross platform compatibility.
function SetLookupValue(fieldName, id, name, entityType) {
if (fieldName != null) {
var lookupValue = new Array();
lookupValue[0] = new Object();
lookupValue[0].id = id;
lookupValue[0].name = name;
lookupValue[0].entityType = entityType;
Xrm.Page.getAttribute(fieldName).setValue(lookupValue);
}
}
var ExistingCase = curentUserId = Xrm.Page.context.getUserId();
if (ExistingCase.getValue() != null) {
var ExistingCaseGUID = ExistingCase.getValue()[0].id;
var ExistingCaseName = ExistingCase.getValue()[0].name;
SetLookupValue("new_accountmanager", ExistingCaseGUID, ExistingCaseName, "incident");
}
please check following code, it worked fine for me last time i used it:
if (typeof (SDK) == "undefined")
{ SDK = { __namespace: true }; }
//This will establish a more unique namespace for functions in this library. This will reduce the
// potential for functions to be overwritten due to a duplicate name when the library is loaded.
SDK.Workflow = {
_getServerUrl: function () {
///<summary>
/// Returns the URL for the SOAP endpoint using the context information available in the form
/// or HTML Web resource.
///</summary>
var ServicePath = "/XRMServices/2011/Organization.svc/web";
var serverUrl = "";
if (typeof GetGlobalContext == "function") {
var context = GetGlobalContext();
serverUrl = context.getServerUrl();
}
else {
if (typeof Xrm.Page.context == "object") {
serverUrl = Xrm.Page.context.getServerUrl();
}
else
{ throw new Error("Unable to access the server URL"); }
}
if (serverUrl.match(/\/$/)) {
serverUrl = serverUrl.substring(0, serverUrl.length - 1);
}
return serverUrl + ServicePath;
},
ExecuteRequest: function () {
var requestMain = ""
requestMain += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
requestMain += " <s:Body>";
requestMain += " <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
requestMain += " <request i:type=\"b:ExecuteWorkflowRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">";
requestMain += " <a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
requestMain += " <a:KeyValuePairOfstringanyType>";
requestMain += " <c:key>EntityId</c:key>";
requestMain += " <c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">267d4790-e41a-e311-b6a7-3c4a92db481b</c:value>";
requestMain += " </a:KeyValuePairOfstringanyType>";
requestMain += " <a:KeyValuePairOfstringanyType>";
requestMain += " <c:key>WorkflowId</c:key>";
requestMain += " <c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">a6832cc5-1d82-48f5-a940-e41269726204</c:value>";
requestMain += " </a:KeyValuePairOfstringanyType>";
requestMain += " </a:Parameters>";
requestMain += " <a:RequestId i:nil=\"true\" />";
requestMain += " <a:RequestName>ExecuteWorkflow</a:RequestName>";
requestMain += " </request>";
requestMain += " </Execute>";
requestMain += " </s:Body>";
requestMain += "</s:Envelope>";
var req = new XMLHttpRequest();
req.open("POST", SDK.Workflow._getServerUrl(), false)
req.setRequestHeader("Accept", "application/xml, text/xml, */*");
req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
req.send(requestMain);
//work with the response here
var strResponse = req.responseXML.xml;
alert(strResponse.toString());
},
__namespace: true
};
UPDATE:--------------
My previous answer was direct to question. Now providing new answer due to question comments. As it's said in comments workflows can be run only over existing records, but as you said you want to change some field on creation form: record is not saved yet. To do that you must use Xrm object as it is shown below:
function OnLoadingForm() {
var FormType = Xrm.Page.ui.getFormType();
if (FormType != null) {
switch (FormType) {
case 1:
// It's a "create" form
var test = "Mr.";
Xrm.Page.getAttribute("salutation").setValue(test);
break;
case 2:
// It's a "update" form
break;
case 3:
// It's a "readonly" form
break;
case 4:
// It's a "disabled" form
break;
case 6:
// It's a "bulkedit" form
break;
default:
break;
}
}
}
This code works on classic CRM forms (Information forms in customizations). New release may change this. "salutation" is name of field from customizations. Notice that this field change is only on form and will be saved to CRM DB after user clicks Save button.
UPDATE 2:-----------
Due to new circumstances new code snippet:
function OnLoadingForm() {
// Get the current FormType
var FormType = Xrm.Page.ui.getFormType();
if (FormType != null) {
switch (FormType) {
case 1:
// It's a "create" form
var curentUserId = Xrm.Page.context.getUserId();
var serverUrl;
if (Xrm.Page.context.getClientUrl !== undefined) {
serverUrl = Xrm.Page.context.getClientUrl();
} else {
serverUrl = Xrm.Page.context.getServerUrl();
}
var ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
var userRequest = new XMLHttpRequest();
userRequest.open("GET", ODataPath + "/SystemUserSet(guid'" + Xrm.Page.context.getUserId() + "')", false);
userRequest.setRequestHeader("Accept", "application/json");
userRequest.setRequestHeader("Content-Type", "application/json; charset=utf-8");
userRequest.send();
if (userRequest.status === 200) {
var retrievedUser = JSON.parse(userRequest.responseText).d;
var userFullName = retrievedUser.FullName;
SetLookupValue("new_accountmanager", curentUserId, userFullName, "systemuser");
}
else {
return "error";
}
break;
case 2:
// It's a "update" form
break;
case 3:
// It's a "readonly" form
break;
case 4:
// It's a "disabled" form
break;
case 6:
// It's a "bulkedit" form
break;
default:
break;
}
}
}
function SetLookupValue(fieldName, id, name, entityType) {
if (fieldName != null) {
var lookupValue = new Array();
lookupValue[0] = new Object();
lookupValue[0].id = id;
lookupValue[0].name = name;
lookupValue[0].entityType = entityType;
Xrm.Page.getAttribute(fieldName).setValue(lookupValue);
}
}
Related
here am trying to get reccurring events from calendar list for sharepoint Online app and there am using code as like
hostWebUrl = decodeURIComponent(manageQueryStringParameter('SPHostUrl'));
function GetListData() {
var webUrl = hostWebUrl;// = "http://server/sitewhereyourlistexists";
var listGuid = "{2000da75-8663-42d9-9999-ad855c54b4e0}"
// An XMLHttpRequest object is used to access the web service
var xhr = new XMLHttpRequest();
var url = webUrl + "/_vti_bin/Lists.asmx";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xhr.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/GetListItems");
// The message body consists of an XML document
// with SOAP elements corresponding to the GetListItems method parameters
// i.e. listName, query, and queryOptions
var data = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body>" +
"<GetListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\">" +
"<listName>" + listGuid + "</listName>" +
"<query>" +
"<Query><Where>" +
"<DateRangesOverlap>" +
"<FieldRef Name=\"EventDate\"/>" +
"<FieldRef Name=\"EndDate\"/>" +
"<FieldRef Name=\"RecurrenceID\"/>" +
"<Value Type=\"DateTime\"><Today/></Value>" +
"</DateRangesOverlap>" +
"</Where></Query>" +
"</query>" +
"<queryOptions>" +
"<QueryOptions>" +
"<ExpandRecurrence>TRUE</ExpandRecurrence>" +
"</QueryOptions>" +
"</queryOptions>" +
"</GetListItems>" +
"</soap:Body>" +
"</soap:Envelope>";
// Here we define what code we want to run upon successfully getting the results
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var doc = xhr.responseXML;
// grab all the "row" elements from the XML results
var rows = doc.getElementsByTagName("z:row");
var results = "Today's Schedule (" + rows.length + "):\n\n";
var events = {};
for (var i = 0, len = rows.length; i < len; i++) {
var id = rows[i].getAttribute("ows_FSObjType"); // prevent duplicates from appearing in results
if (!events[id]) {
events[id] = true;
var allDay = rows[i].getAttribute("ows_fAllDayEvent"),
title = rows[i].getAttribute("ows_Title"),
start = rows[i].getAttribute("ows_EventDate");
var index = start.indexOf(" ");
var date = start.substring(5, index) + "-" + start.substring(2, 4); // get the date in MM-dd-yyyy format
start = start.substring(index, index + 6); // get the start time in hh:mm format
var end = rows[i].getAttribute("ows_EndDate");
index = end.indexOf(" "); end = end.substring(index, index + 6); // get the end time in hh:mm format
results += date + " " + (allDay == "1" ? "All Day\t" : start + " to " + end) + " \t " + title + "\n";
}
}
alert(results);
} else {
alert("Error " + xhr.status);
}
}
};
// Finally, we actually kick off the query
xhr.send(data);
}
after calling this function in decument. ready section it is not retrieving any data but there is ine error which i can see in console of browser that is as below
You will click on the correct request in the left hand side panel, then select "Inspectors" in the right hand side top panel. Then choose between the different request and response options.
I've created an Action under Process for a custom entity new_enrollment. I've created no I/O argument for that action. Now, by using following code snippet I want to run that custom action so that when action is executed a plugin get fired and create a phone call.
But it seems that action is not get executed. Any suggestion or help so that I can get action executed.
function emailOrderDetails(){
var entityId = Xrm.Page.data.entity.getId();
var entityName = "new_enrollment";
var requestName = "new_sendemail";
RunAction(entityId, entityName, requestName);
window.location.reload(true);
}
function RunAction(entityId, entityName, requestName) {
try{
// Creating the request XML for calling the Action
var requestXML = ""
requestXML += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
requestXML += " <s:Body>";
requestXML += " <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
requestXML += " <request xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\">";
requestXML += " <a:Parameters xmlns:b=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
requestXML += " <a:KeyValuePairOfstringanyType>";
requestXML += " <b:key>Target</b:key>";
requestXML += " <b:value i:type=\"a:EntityReference\">";
requestXML += " <a:Id>" + entityId + "</a:Id>";
requestXML += " <a:LogicalName>" + entityName + "</a:LogicalName>";
requestXML += " <a:Name i:nil=\"true\" />";
requestXML += " </b:value>";
requestXML += " </a:KeyValuePairOfstringanyType>";
requestXML += " </a:Parameters>";
requestXML += " <a:RequestId i:nil=\"true\" />";
requestXML += " <a:RequestName>" + requestName + "</a:RequestName>";
requestXML += " </request>";
requestXML += " </Execute>";
requestXML += " </s:Body>";
requestXML += "</s:Envelope>";
var req = new XMLHttpRequest();
req.open("POST", GetClientUrl(), false)
req.setRequestHeader("Accept", "application/xml, text/xml, */*");
req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
req.send(requestXML);
//Get the Response from the CRM Execute method
//var response = req.responseXML.xml;
}
catch(e){
alert(e.Message);
}
}
function GetClientUrl() {
if (typeof Xrm.Page.context == "object") {
clientUrl = Xrm.Page.context.getClientUrl();
}
var ServicePath = "/XRMServices/2011/Organization.svc/web";
return clientUrl + ServicePath;
}
you are using 2016 which supports WebAPI and its very easy using WebAPI. Below is the working example of calling custom action using JS. I have 2 output variables, one get set by custom action and the other one "ptext" by plugin which i have registered on this Action.
Hope it will solve your problem.
function CallCAction(context) {
var Credit_Limit = Xrm.Page.getAttribute("creditlimit").getValue();
var Credit_hold = Xrm.Page.getAttribute("creditonhold").getValue();
if(Credit_hold !=null && Credit_Limit!=null){
var actionName = "new_Preferred_Check";
var inputParam = {
"Credit_Limit": Credit_Limit,
"Credit_hold": Credit_hold
};
Xrm.Page.ui.setFormNotification("Processing...","INFO","processingFId");
var actionResponse = callPreferredCust(actionName, inputParam);
if (actionResponse != null) {
Xrm.Page.getAttribute("new_preferredcust").setValue(actionResponse.Preferred_Cust);
alert(actionResponse.ptext);
Xrm.Page.ui.clearFormNotification("processingFId");
}
}
}
function callPreferredCust(actionName, inputParam) {
var result = null;
var req = new XMLHttpRequest();
var uri = Xrm.Page.context.getClientUrl() + "/api/data/v8.2/";
try {
req.open("POST",encodeURI(uri+actionName),false);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.onreadystatechange = function () {
if(this.readyState==4){
req.onreadystatechange = null;
if(this.status==200){
result = JSON.parse(this.response);
}else{
var err = JSON.parse(this.response).error;
alert(err.message);
}
}
};
req.send(JSON.stringify(inputParam));
return result;
}catch(err){
alert(err.message);
}
}
I am writing an extension for a text-editor (Brackets) that can generate HTML and append libraries automatically in the HTML.
I have an Object called 'choice'.
This modal requests the users input:
choice grabs the user's input by defining methods on choice
partial JS here:
var choice = new Object();
choice.language = function () {
//Buid HTML top 'head'
var htmlTop = "<!DOCTYPE html>" + "<html>" + "<head lang='";
//Grab Selected Language Type
var languageChoice = document.getElementById("languages").value;
//Determine what Selected Language type is and complete HTML 'head'
if (languageChoice === "english") {
languageChoice = "en";
return htmlTop + languageChoice + "'>";
} else if (languageChoice === "german") {
languageChoice = "de";
return htmlTop + languageChoice + "'>";
} else if (languageChoice === "spanish") {
languageChoice = "es";
return htmlTop + languageChoice + "'>";
} else if (languageChoice === "french") {
languageChoice = "fr";
return htmlTop + languageChoice + "'>";
} else if (languageChoice === "italian") {
languageChoice = "it";
return htmlTop + languageChoice + "'>";
} else if (languageChoice === "chinese") {
languageChoice = "zh-cn";
return htmlTop + languageChoice + "'>";
}
}; //end choice.language
choice.charset = function () {
//Build meta and the rest of the 'head tag'
var htmlCharset_Beginning = "<meta charset='";
var htmlCharset_End = "'>" + "<title> -Insert Title- </title>" + "<!-- Insert CSS links below -->" + "</head>" + "<body>";
var charsetChoice = document.getElementById("charset").value;
if (charsetChoice === "utf8") {
charsetChoice = "UTF-8";
return htmlCharset_Beginning + charsetChoice + htmlCharset_End;
} else {
charsetChoice = "UTF-16";
return htmlCharset_Beginning + charsetChoice + htmlCharset_End;
}
}; // end choice.charset
choice.doctype = function () {
var doctypeChoice = document.getElementById("doctype").value;
return doctypeChoice;
}; // end doctype
choice.libraries = function () {
var checkedBoxes = getCheckedBoxes("lib_checkboxes");
checkedBoxes.forEach(function(item){
var scripts =+ $(item).data('script');
});//End forEach
var bottomHTML = scripts + "</body>" + "</html>";
return bottomHTML;
}; //End choice.libraries
var chosenTemplate = function(){
var template = choice.language() + choice.charset() + choice.libraries();
// insert html into file, this will overwrite whatever content happens to be there already
EditorManager.getCurrentFullEditor()._codeMirror.setValue(template);
// automatically close the modal window
$('#templates_modalBtn').click();
};
//Get checkedBoxes function
// Pass the checkbox name to the function
function getCheckedBoxes(chkboxName) {
var checkboxes = document.getElementsByName(chkboxName);
var checkboxesChecked = [];
// loop over them all
for (var i = 0; i < checkboxes.length; i++) {
// And stick the checked ones onto an array...
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i]);
}
}
// Return the array if it is non-empty, or null
return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
} // End action();
//JEFF STOP CODING HERE
// Register the commands and insert in the File menu
CommandManager.register(Strings.MENU_COMMAND, 'templates', action);
var menu = Menus.getMenu(Menus.AppMenuBar.EDIT_MENU);
menu.addMenuDivider();
menu.addMenuItem('templates');
}); //end define;
QUESTION:
Can I save multiple methods (each method returns a string) as a variable?
Example here:
var chosenTemplate = function(){
var template = choice.language() + choice.charset() + choice.libraries();
// insert html into file, this will overwrite whatever content happens to be there already
EditorManager.getCurrentFullEditor()._codeMirror.setValue(template);
// automatically close the modal window
$('#templates_modalBtn').click();
};
My code is loading with no errors, but its not executing at all so I am trying to debug and figure out what is going wrong...
Before you realize the function 'chosenTemplate', you should check whether the document stream of the page has already downloaded. If it not, you may not be able to get the value of the widget (empty).
It's been a while since I've toyed with my JS, so I might be missing something completely obvious. I have the following:
MyApp.IaeCheckboxCallback = function ($trigger) {
var $checkbox = $trigger.find('input[type="checkbox"]');
$checkbox.on('click', function () {
doIAECallbackNT($trigger.attr('id'), $trigger.data('data-recordid'), $trigger.data('data-recordtype'),
$trigger.data('data-valuejs'), $trigger.data('data-statuselement'), $trigger.data('data-callback'))
});
};
Once inside $checkbox.on, $trigger becomes undefined. How do I prevent this?
Adding more relevant code
I'm tying into this other developer's JS that is in another script file.
function doIAECallbackNT
(
iaeId,
recordId,
recordType,
fieldName,
value,
statusElementId
)
{
doIAECallbackNT(iaeId, recordId, recordType, fieldName, value, statusElementId, function(success) { });
}
function doIAECallbackNT
(
iaeId,
recordId,
recordType,
fieldName,
value,
statusElementId,
callback
)
{
var req = newXMLHttpRequestNT ();
var statusElement = document.getElementById(statusElementId);
setStatusNT(statusElement, "Updating...");
var msg =
"<?xml version='1.0' encoding='utf-8'?>" +
"<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" +
"<soap:Body>" +
"<HandleRequest xmlns='https://somesite.com/WebService/'>" +
"<iaeId>" + iaeId + "</iaeId>" +
"<recordId>" + recordId + "</recordId>" +
"<recordType>" + recordType + "</recordType>" +
"<fieldName>" + fieldName + "</fieldName>" +
"<value>" + escape(value) + "</value>" +
"</HandleRequest>" +
"</soap:Body>" +
"</soap:Envelope>";
//alert(msg);
req.onreadystatechange = function() {
if (req.readyState == 4) {
var success = false;
try { success = (req.responseXML.documentElement.getElementsByTagName("Success")[0].text.toLowerCase() == "true"); }
catch (e) { success = false; }
var msg2 = "";
//var msg3 = "";
try { msg2 = req.responseXML.documentElement.getElementsByTagName("Message")[0].text; }
catch (e) { msg2 = req.responseText; }
//msg3 = msg2;
if (!success) {
//Error: The string was not recognized as a valid DateTime. There is a unknown word starting at index 2.
if ( msg2.indexOf("valid DateTime") != -1 )
msg2 = "Failed: You entered an invalid date. Please re-enter the date.";
if (msg2.indexOf("StartDate_Must_Be_Before_EndDate") != -1)
msg2 = "Failed: The Start date must be prior to the End date. Try changing the start date first.";
//alert(msg2);
AddFailedNote(msg2);
if (statusElement.tagName.toLowerCase() != 'a')
msg2 = "<span class='error bold'>" + msg2 + "</span>";
}
else if (statusElement.tagName.toLowerCase() != 'a') {
AddSuccessNote(msg2);
msg2 = "<span class='success bold'>" + msg2 + "</span>";
}
setStatusNT(statusElement, msg2);
if (callback != null) { callback(success); }
}
};
req.open("POST", "../Services/IAEService.asmx", true);
req.setRequestHeader("Content-type", "text/xml; charset=utf-8");
req.setRequestHeader("Content-length", msg.length.toString());
req.setRequestHeader("SOAPAction", "https://www.somesite.com/WebService/HandleRequest");
req.send(msg);
}
and here's the ugly .NET rendering of a checkbox:
<span class="IaeCheckboxCallback" title="Ent?" data-recordid="11012" data-recordtype="Person" data-fieldname="HasEnterprise" data-statuselement="MainContent_MainContent_hrmol3_sp_ctl00" data-callback="function() { }" data-valuejs="MainContent_MainContent_hrmol3_dp_ctl00_0.checked" style="font-size:1em;"><input id="MainContent_MainContent_hrmol3_dp_ctl00_0" type="checkbox" name="ctl00$ctl00$MainContent$MainContent$hrmol3$dp$0$tc_HasEnterprise$ctl00" /></span>
The other person's code fails at: f (statusElement.tagName.toLowerCase() != 'a')
All the parameters that I've passed in show as undefined in the browser developer tool.
I have looked at this example but I am still unable to retrieve the JSON Object in the jsp. Here's the code in my MyCalendarController.java class:
public class MyCalendarController implements Controller{
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
if("Add".equals(request.getParameter("action"))){
...
JSONObject jObj = new JSONObject();
jObj.put("test", "Success");
response.getWriter().write(jObj.toString());
...
}
return new ModelAndView("mycalendar", "model", myModel);
}
and here's how I'm trying to retrieve it in jsp but the alert always says 'undefined'
var queryString = "?action=Add";
queryString += "&t=" + title;
queryString += "&sDT=" + stDate + "T" + stHour + ":" + stMin + ":00";
queryString += "&eDT=" + eDate + "T" + eHour + ":" + eMin + ":00";
$.ajax({
type:"GET",
url: "mycalendar.htm" + queryString,
success: function(response){
alert(response.test);
}
});
Note: I am trying to create the JSON Object when the ajax call is made to the class from the jsp. I am new to ajax and javascript so must be doing something wrong... Please help!!!
In the above mentioned code, the response.responseText property is 'undefined'. But I tried it another way:
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
}catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
alert(ajaxRequest.responseText);
alert("test: " + ajaxRequest.test);
}
}
var queryString = "?action=Add";
queryString += "&t=" + title;
queryString += "&sDT=" + stDate + "T" + stHour + ":" + stMin + ":00";
queryString += "&eDT=" + eDate + "T" + eHour + ":" + eMin + ":00";
ajaxRequest.open("GET", "mycalendar.htm" + queryString, true);
ajaxRequest.send(null);
This way I get the ajaxRequest.responseText but the alert("test: " + ajaxRequest.test); still shows undefined
var a = '<%=DropDown.returnList()%>';
var countryObj = JSON.parse(a);
var s = $('#selectCountry');
for(var val in countryObj)
{
$('<option />', {value: val, text: countryObj[val]}).appendTo(s);
}
Try to alert(response.responseText),I am not sure.