Use jQuery to insert a script which includes a function? - javascript

I am trying to append a line of JavaScript to a div dynamically, but it seems that when I run the .append() call, the browser sees a function() call within that line as an actual function instead of an actual string:
var startDate = 0
...
function insertCalendar(){
var divName = "div[name=StartDate" + startDateNum + "]";
$(divName).append("<script>Calendar.setup({ trigger : 'StartDate" + startDateNum + "', inputField : 'StartDate" + startDateNum + "', onSelect : function() { this.hide() } });</script>");
startDateNum++;
}
At the call to .append() the JavaScript console returns "Uncaught SyntaxError: Unexpected end of input," and it seems to mess with the function insertCalendar. I'm fairly certain I'm not missing a quote...
Let me know if this is too vague as this is my first question here. Thanks!

You can create a script tag, and then add the javascript.
var jstag=document.createElement('script');
jstag.setAttribute("type","text/javascript");
jstag.appendChild(document.createTextNode(" Javascript code goes here "));
document.appendChild(jstag);

Got the answer thanks to Anzz, mixed it with some AJAX:
var startDateNum = 0;
...
function setNewCal(){
var url = "getCal.php?startDate=" + startDateNum;
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = addCalendar;
xmlHttp.send(null);
}
function addCalendar(){
var divName = "StartDate" + startDateNum + "Div";
var response = xmlHttp.responseText;
if (xmlHttp.readyState == 4){
var calscript = document.createElement("script");
calscript.setAttribute("type", "text/javascript");
calscript.appendChild(document.createTextNode(response));
document.getElementById(divName).appendChild(calscript);
startDateNum++;
}
}

Related

How to bind parameter to URL

This is my jsp code. I want to bind the catid parameter to url when I call getproductsub() and send ajax request.
r.open("GET", "url?catid=" + catid,true);
above line seems an error of my code.How can I fix it.
<select class="form-control" id="pcategory" name="pcategory" onchange="getproductsub();">
<script>
function getproductsub() {
var catid = document.getElementById('pcategory').value;
var url = window.location.href;
var r = new XMLHttpRequest();
r.onreadystatechange = function() {
if (r.readyState === 4 && r.status === 200) {}
};
r.open("GET", "url?catid=" + catid, true);
r.send();
}
</script>
Note that window.location.href gives the complete location including the parameters in the url at the current time. So ? might be included in it.
You can either use
var url = window.document.location.pathname;
And concat the url to the String passed to open().
r.open("GET", url + "?catid=" + catid, true);
OR
Use getRequestURL() as you are coding in jsp.
r.open("GET", "<%= request.getRequestURL()%>?catid=" + catid, true);

$('#' + postFormId ).html( xml ) throwing Unexpected call to method error

Edit:I have tried jquery versions 1.11.3 and 1.4.2
The following code throws the error "Unexpected call to method or property access" when emulating previous versions of ie(5 and 7). Using this emulation is not optional as it is set by a third party IT. It works fine in IE8 and there was a version that was essentially the same code (I copy and pasted it, and made a couple of changes) used to work in 5 and 7.
Using console.logs, I'm fairly certain that the issue is in $('#' + postFormId ).html( xml ) though I could be wrong.
if( punchOutCartPage != "SalesOrder" ) {
$(document).on('click','#btn-proceed-checkout',function(){
var itemsXML = parseShoppingCart();
var headerXML = "\t<header>\n\t\t{sellerId}\n\t\t{buyerID}\n\t\t{sessionId}\n\t</header>";
var shoppingCartXML = createNetSuiteShoppingCart( headerXML, itemsXML );
var form = $("#cart");
var form_action = form.attr("action");
$.ajax({
url:'/app/site/backend/emptycart.nl?c=',
context: document.body,
success: function(data){
var form_serialized = form.serialize();
$.post(form_action, form_serialized,
function (val) {
postToPunchOutUrl(punchOutUserCartUrl, shoppingCartXML);
}
);
}
});
return false;
});
}
function parseShoppingCart() {
}
function createNetSuiteShoppingCart( headerXML, itemsXML ) {
var parentCompany =localStorage.StrparentCompany;
var account =localStorage.Straccount;
var sessionId = localStorage.StrpunchOutSessionId;
headerXML = headerXML.replace("{sellerId}", "<sellerID>" + encodeXML(account) + "</sellerID>");
headerXML = headerXML.replace("{buyerID}", "<buyerID>" + encodeXML(parentCompany) + "</buyerID>");
headerXML = headerXML.replace("{sessionId}", "<PunchOutSessionID>" + encodeXML(sessionId) + "</PunchOutSessionID>");
itemsXML = "<NetSuiteSellerPunchOutShoppingCart>\n" + headerXML + "\n" + "<itemList>\n" + fezzik + "</itemList>\n" + "</NetSuiteSellerPunchOutShoppingCart>";
itemsXML = encodeXML(itemsXML);
var shoppingCartXML = '<input type="hidden" name="shoppingcart-urlencoded" value="{url-encoded-raw-xml}">';
return shoppingCartXML.replace("{url-encoded-raw-xml}", itemsXML);
}
function postToPunchOutUrl( url, xml ) {
var postFormId = "poomform";
$('#' + postFormId ).html( xml );
$('#' + postFormId ).attr( "action", url );
document.forms[postFormId].submit();
}
function encodeXML(string) {
return string.replace(/\&/g, '&' + 'amp;').replace(/</g, '&' + 'lt;').replace(/>/g, '&' + 'gt;').replace(/\'/g, '&' + 'apos;').replace(/\"/g, '&' + 'quot;');
}
This issue was caused by the document mode emulation itself. When internet explorer emulates document mode 5 or 7, it wraps a form tag around your forms in certain cases. So this <form method="POST" name="poomform" id="poomform" action="https://www.example.net"></form> became (I didnt copy it, but approximately)
<form><form method="POST" name="poomform" id="poomform" action="https://www.example.net"></form></form>
Which then throws the unexpected call to method error.
I worked around this by adding the form with javascript after the page had loaded, so I replaced the form in the html with <div id="poomformholder"></div>
and then added a line of jquery to my postToPunchOutUrl function to look like:
function postToPunchOutUrl( url, xml ) {
$('#' + "poomformholder" ).html("<form method=\"POST\" name=\"poomform\" id=\"poomform\" action=\"https://www.example.net\"></form>");
//The id name of our form.
var postFormId = "poomform";
$('#' + postFormId ).attr("action",url);
$('#' + postFormId ).html(xml);
And now everything works. Hopefully this helps someone in the future and thank you for your help!

Load a JavaScript event the last in CRM form

I have one image saved in Notes with every form in my CRM Online 2013 custom entity. I am using the following code to query the image and show it in an Image tag in a Web Resource on the form. For debugging purposes I was calling the following code through a button, but I want this process of querying the Notes and displaying the image in the web resource to be automatic when the form load. Here is my code:
<html><head><meta charset="utf-8"></head>
<body>
<img id="image" src="nothing.jpg" style="width: 25%; height: auto;" />
<script type="text/javascript">
$(windows).load(function()
{
var recordId = window.parent.Xrm.Page.data.entity.getId();
var serverUrl = Xrm.Page.context.getServerUrl().toString();
var ODATA_ENDPOINT = "XRMServices/2011/OrganizationData.svc";
var objAnnotation = new Object();
ODataPath= serverUrl+ODATA_ENDPOINT;
var temp= "/AnnotationSet?$select=DocumentBody,FileName,MimeType,ObjectId&$filter=ObjectId/Id eq guid'" + recordId + "'";
var result =serverUrl + ODATA_ENDPOINT + temp;
var retrieveRecordsReq = new XMLHttpRequest();
retrieveRecordsReq.open('GET', ODataPath + temp, false);
retrieveRecordsReq.setRequestHeader("Accept", "application/json");
retrieveRecordsReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
retrieveRecordsReq.onreadystatechange = function ()
{
if (this.readyState == 4 /* complete */)
{
if (this.status == 200)
{
this.onreadystatechange = null; //avoids memory leaks
var data = JSON.parse(this.responseText, SDK.REST._dateReviver);
if (data && data.d && data.d.results)
{
SuccessFunc(JSON.parse(this.responseText, SDK.REST._dateReviver).d.results);
}
}
else
{
alert(SDK.REST._errorHandler(this));
}
}
};
var x = new XMLHttpRequest();
x.open("GET", result, true);
x.onreadystatechange = function ()
{
if (x.readyState == 4 && x.status == 200)
{
var doc = x.responseXML;
var title = doc.getElementsByTagName("feed")[0].getElementsByTagName("entry")[0].getElementsByTagName("content")[0].getElementsByTagName("m:properties")[0].getElementsByTagName("d:DocumentBody")[0].textContent;
document.getElementById('image').src ="data:image/png;base64,"+title;
}
};
x.send(null);
});
</script>
</body></html>
I have removed the button tag..now I want this the query to happen on page Load, but nothing happens when I refresh the form. In my opinion the function loads before the annotation loads. Is there a way to make it wait and load the last?
If you want to wait for the parent window to load I think $(windows).load(myFunction); should do the trick.
Maybe $ is undefined because you did not add jQuery to your webressource.
There are also a few little mistakes and unattractive things:
First:
You will get a wrong server url.
If you want to access the Xrm-object in a webresource you always have to use window.parent.Xrm or you put it in a variable var Xrm = window.parent.Xrm;
For example:
var Xrm = window.parent.Xrm;
var recordId = Xrm.Page.data.entity.getId();
var serverUrl = Xrm.Page.context.getServerUrl().toString();
Second:
The ODataPath variable is not declared. Use var ODataPath= serverUrl+ODATA_ENDPOINT; instead. By the way the value of the ODataPath has nothing to do with OData. It is more the REST-Endpoint of Dynamics CRM.
My script would look like this:
var Xrm, recordId, serverUrl, restEndpointUrl, odataQuery, fullRequestUrl, xmlRequest;
Xrm = window.parent.Xrm;
recordId = Xrm.Page.data.entity.getId();
serverUrl = Xrm.Page.context.getServerUrl().toString();
restEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc";
^ I think a '/' was missing there
odataQuery = "/AnnotationSet?$select=DocumentBody,FileName,MimeType,ObjectId&$filter=ObjectId/Id eq guid'" + recordId + "'";
fullRequestUrl = restEndpointUrl + odataQuery;
I also dont understand why you use the second HttpRequest.
All of this code is not tested.

calling JQuery HTTP GET request inside javascript function

I will start off by saying I am new to Javascript and JQuery. What I want to accomplish is have a submit button on an HTML page that will call the dbQuery function in my .js file that will print the value of variables to the screen and then add them into a MySQL database.
I need to use the JavaScript variable selectedVisibleValue that is defined in my first function dbQuery The reason I want to do this is because I have four drop downs, three of which are hidden drop downs that are only shown depending on the first non hidden dropdown, only one of the hidden drop downs is ever visible.
I want to work with these variables in my PHP page formPage to do the Database functions. My code is below I want to add the testing1 function into the dbQuery function.
I have tried just copying and pasting it into the dbQuery function but it does not work. I am not trying to work with the selectedVisibleValue in the code below. I am just trying to do some testing with some bogus variables.
var dbQuery = function(){
var description = document.getElementById("jobDescription").value;
var selectedEquip = document.getElementById("equipmentList");
var selectedEquip1 = selectedEquip.options[selectedEquip.selectedIndex].text;
var selectedVisibleValue = $(".unitDropDowns select:visible").val();
document.getElementById("descriptionSummary").innerHTML = "<h3>Description</h3>" + "<p>" + description + "</p>";
document.getElementById("equipmentRan").innerHTML = "<h3>Equipment Ran </h3>" + "<p>" + selectedEquip1 + "</p>" + "<h3>Unit Number</h3>" + "<p>" + selectedVisibleValue + "</p>";
document.getElementById("equipmentRan").style.display = "block";
document.getElementById("descriptionSummary").style.display = "block";
}
var testing1 = function() {
$.get(
"formPage.php",
{paramOne : 123, paramX : 'abc'},
function(data) {
document.getElementById("equipmentRan").innerHTML = ('page content: ' + data);
}
);
}
//cache references to static elements
var jobDescription = $('#jobDescription')
, selectedEquip = $('#equipmentList')
, descriptionSummary = $('#descriptionSummary')
, equipmentRan = $('#equipmentRan')
;
function dbQuery(){
//gather params
var params = {
jobDescription : jobDescription.val(),
selectedEquip1 : selectedEquip.val(),
selectedVisibleValue = $(".unitDropDowns select:visible").val()
}
//show summary
descriptionSummary.html('<h3>Description</h3><p>'+description+'</p></h3>').show();
equipmentRan.html('<h3>Equipment Ran</h3><p>'+selectedEquip1+'</p><h3>Unit Number</h3><p>'+selectedVisibleValue+'</p>').show();
//do a get
$.get('formPage.php',params,function(data) {
equipmentRan.html('page content: ' + data);
}
}
jsFiddle DEMO
Passing variables between functions might come in useful for your project.
HTML:
<div id="theBox"></div>
<button>Press Me</button>
JS
$(document).ready(function() {
// This is some other Do More function, defined prior to the next variable function.
// This is your .get() request.
function doMore(target){
// For the incomming targer, add a class style of a larger font.
$(target).css('font-size', 30);
}
// The main function.
var dbQuery = function() {
// Show dynamic text on the HTML page.
var extra = $('#theBox').html('Dynamic Text Results');
// Run some other function, also... send the private variable in use.
doMore(extra);
};
// The submit button.
$('button').on('click', function() {
// Start the function.
dbQuery();
});
});
Here is the working code:
function dbQuery() {
window.description = document.getElementById("jobDescription").value;
var selectedEquip = document.getElementById("equipmentList");
window.selectedEquip1 = selectedEquip.options[selectedEquip.selectedIndex].text;
window.selectedVisibleValue = $(".unitDropDowns select:visible").val();
testing1();
}
function testing1() {
$(document).ready(function() {
$.get(
"formPage.php",
{paramOne : window.selectedVisibleValue, paramX : window.description, paramY : window.selectedEquip1},
function(data) {
document.getElementById("equipmentRan").innerHTML = (data);
}
);
});
}

Injecting code into the web page does not work

This is a follow-up to a question I asked yesterday.
I have a userscript (kind of like GreaseMonkey script, but for Chrome).
The idea is to add a textbox and a button to the page. Then when the user clicks the button, it kicks off a function that does stuff. So I inject the textbox, button and the function into the page, but when the user clicks the button, the Chrome console tells me "Uncaught TypeError: object is not a function". So obviously it does not see the function I just injected and that is specified in the onclick event for the button.
So I have code like this:
initialize();
function initialize() {
var dropDown = document.getElementById("tstGlobalNavigation_ddlChooseProject");
// add a textbox
dropDown.innerHTML = dropDown.innerHTML + " <input type='text' name='txtSearch' style='position:absolute;top:8px;left:800px;width:50px' >";
// add a button
dropDown.innerHTML = dropDown.innerHTML + " <input type='button' name='btnSearch' value='Go' onclick='fn()' style='position:absolute;top:8px;left:860px;width:35px'>";
addScript("var obj = document.getElementById('txtSearch'); "
+ "if (obj != null) { "
+ " var incidentId = document.getElementById('txtSearch').value; "
+ " var currentURL = location.href; "
+ " var splitResult = currentURL.split('/'); "
+ " var projectId = splitResult[4]; "
+ " location.href = 'http://dev.myApp.com/ProductTeam/' + projectId + '/Incident/' + incidentId + '.aspx'; "
+ " }"
, "fn");
}
function addScript(contents, id) {
var head, script;
head = document.getElementsByTagName('head')[0];
script = document.getElementById(id);
if(script != undefined) {
head.removeChild(script);
}
script = document.createElement('script');
script.type = 'text/javascript';
script.id = id;
script.innerHTML = contents;
head.appendChild(script);
}
What am I missing here?
You're not calling the function you created, you're using the id that you give to the script tag... Try changing the code to
addScript("function fn() { var obj = document.getElementById('txtSearch'); "
+ "if (obj != null) { "
+ " var incidentId = document.getElementById('txtSearch').value; "
+ " var currentURL = location.href; "
+ " var splitResult = currentURL.split('/'); "
+ " var projectId = splitResult[4]; "
+ " location.href = 'http://dev.myApp.com/ProductTeam/' + projectId + '/Incident/' + incidentId + '.aspx'; "
+ " } }"
, "fn");
and you will have a fn() function that can be called
The problem is that you're trying to use the onclick element attribute to bind an event handler. These attributes are only parsed when the page is first loaded, at which time the function you're trying to bind as the callback doesn't exist.
Avoid binding event handlers in element on* attributes whenever possible. This is called writing unobtrusive JavaScript.
That said, if you absolutely must stick with using onclick, you can bind to a dummy function which does nothing but turn around and call the function that you inject:
<button onclick="wrapper()"
Where wrapper looks something like this:
function wrapper() {
return functionThatWillEventuallyBeInjected();
}
I'm not sure you can actually create script tags on the fly and push content in it.
You could instead create the script tag and modify the src attribute to some JS file:
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "path/to/your/javascript.js";
document.body.appendChild(script);
If you really need to execute a code stored in a string, maybe you could simply eval() it when required!

Categories