Dynamic NAV Control Add-in exchange data - javascript

Im solving how to exchange data between JS control add-in and NAV.
Now, when I want to get data from JS control add-in to NAV. I call from NAV, JS method and in JS method I call method in NAV. See example below.
Is there some easy way e.g. return values on first call from NAV?
Because I need data from JS in one method.
Thank you for your help.
C/AL Code
d::someMethod()
//I need to work with data from JS here
CurrPage.d.getDataFromJS();
d::receiveDataFromJS(data: Variant)
//here I receive data from JS
JS
function getDataFromJS() {
var result = 'bla bla';
Microsoft.Dynamics.NAV.InvokeExtensibilityMethod('receiveDataFromJS', [result]);
}

You can return data from your addin via events. Just define the event in your dll and reinclude your addin, it should then be visible in the C/AL. To trigger the event on JavaScript side use Microsoft.Dynamics.NAV.InvokeExtensibilityMethod('eventName', [parameters]);
The parameters you parse here can then be used to parse your data to the NAV-side. I hope this helps you

Related

UI page (jelly) - how to use dynamic data in g:evaluate

TLDR: How to access i.e. variables or say values in a input field - within the evaluate?
Hello :)
The short of it, is that I have a UI page (modal opened by UI action) with an input field. Onchange, this field needs to run some serverside code that validates the field. The main issue is actually accessing the input data within the evaluate. It doesn't seem posssible to access variables or HTML fields. I can fetch variables set in the modal via setpreferences using RP, but the input data is created within the page, not the UI action.
Is there a way to pass data to an evaluate, or at least have it fetch it itself? I'm seriously considering just creating a script include called via glideajax to do the job.
Help would be much appreciated. Brgds.
Tried fetching variables within g:evaluate, both from client script and HTML id's.
HTML/Jelly code:
<g:cs_ui_text_field class="p" name="input_field_value" id="input_field_value" value="" onchange="validateRequest();" /> <!-- Dont mind the macro name, its just a text field (input). -->
<g2:evaluate var="jvar_gr" jelly="true">
var return_value = '${input_field_value}'; // Attempting to fetch field value wont work.
return_value ;
</g2:evaluate>
Client script:
function validateRequest() {
// ValidateRequest calls evaluate jvar_gr, and alerts the return value.
alert('$[jvar_gr]');
}
As far as I know, you'd need to do this via a GlideAjax call like you mentioned within your client script. Jelly code is used to perform server-side rendering. That means that when your browser requests the UI page from ServiceNow, ServiceNow's servers will run the jelly code. That involves running code within the g2:evaluate tags, and also substituting your macro with raw HTML that your browser can understand (browser don't understand jelly, it only understands how to render HTML). This raw HTML is then sent to your browser to show your UI page.
So the code within your <g2:evaluate></g2:evaluate> tags run before the user even sees your page and has a chance to start interacting with it. So you'll need to perform your server-side calls within your client script component of your UI page. To access an input value using a client script, you can use gel:
function validateRequest() {
var gr = gel("input_field_value").value; // read the value from the input
var ga = new GlideAjax(/* your script include */);
ga.addParam('sysparm_name', /* method name */);
ga.addParam(/* param name */, gr);
ga.getXMLAnswer(function(answer) {
// do what you need to do to update your UI.
});
}
Keep in mind that a UI page's processing script can also run server-side code, and can access input variables. But this usually only comes in handy if you're submitting a form (created with <g:form>), and not trying to run code on change. However, this might be useful depending on when you need to make your server-side calls and your actual use case.

Load data with AJAX only if it has not already been loaded?

I need to load data for my JavaScript app to use. I would like to load the following:
userlist JSON
milestones JSON
Tags JSON
user ACL permissions JSON
These 4 items of data from the server as JSON should be loaded using AJAX but only loaded once.
So I need code that will check to see if the data is loaded already and if it is, use it. If it is not loaded yet, it would make an AJAX request and load the data, and then use it.
I have multiple JavaScript files which need access to this data so I want to make sure that any of them can access it, and whichever once calls for it first will load it using AJAX and make it available for the other scripts to call it without making multiple repeat AJAX requests.
How could I go about this using JavaScript and jQuery?
A basic example would be super appreciated and useful. Thank you
If any of these are not set, load them using AJAX. After loading with AJAX, set these vars for the next caller to access them without a new AJAX request being made...
var userList = userJsonData;
var milestoneList = milestoneJsonData;
var tagList = tagJsonData;
var useAclPermissions = useAclPermissionsJsonData;
Just store the data in a global javascript variable, which is set to null, when your page loads. The first script which loads the data, stores it in the variable, all the other scripts try to access the content of the variable, and if not set, load it:
var milestoneData = null;
function getMilestoneData() {
if (milestoneData === null) {
//make the ajax request, and populate milestoneData variable
} else return milestoneData;
}
According to can i use you can check out localstorage aka webstorage. If you can use it, it might solve your issues. There is a jQuery plugin available. jstorage is an alternative, and has a really simple example at the bottom of the page. Hope this helps.

Call a PHP Link with Onclick

This isn't a duplicate question by any means and I have tried a lot finding solutions.So, please read it before down voting.
Background:
This application is like a note-taking web app where you can post/delete your notes.
Each item in the list has an id which is needed when making a delete call.
In my application, I have to delete individual items from a list which is generated by looping over a JSON response (by a REST API) using PHP.The JSON response can be obtained after successful login.
Question:
To implement delete functionality I have to send id of each of the items as a parameter to the rest api delete call.
So, for this I have to generate dynamic links of the form :
http://localhost/myfolder/api/notes/:id
which should be passed to the delete.php function (Which I have implemented in CURL).
I searched for possible ways :
Using a PHP function: It seems to be complex, however if there is some way to invoke a PHP function (the delete code using CURL) on click of a link (Which I found not possible as per some answers ?) this could be a great solution.
Using Javascript: I have to call a function upon click of link that sets a variable $_SESSION["id"] to the current item["id"] and then goes to delete.php where I use the $_SESSION variable to first set up the link and then use the CURL code.
I tried basic implementation using the second approach but I have hit a roadblock in this issue. It would be great if you could tell with a bit of code which approach should be followed or any other way to do this ?
This functionality is present in twitter/facebook and almost every such service, how do they implement this, the basic approach should be the same, right: Generate dynamic links and pass them to a php script on click ?
Basic Javasript approach :
<script>
<script>
var el = document.getElementById('del1');
el.onclick = del1;
function del() {
// I have to set $_SESSION here
return false;
}
</script>
echo "<a href=\"delete.php\" title=\"Delete\" id=\"del1\">";
//Here, I have to pass the item["id"] to the javascript function.
I had tried some other ways but I have modified the code a lot so, I can't post them. Thanks for your help.
Regarding #2, you can't access the user's session from Javascript, so that will not work.
My preferred way (if using jquery) is to put the id in a data attribute of the delete button (or the block as a whole). Then in the delete onclick function do something like
<div class="block" data-itemid="<?=$item['id']?>">
...
<div class="delete_button">Delete</div>
</div>
...
$('.delete_button').on('click',function(event) {
block = $(event).target.parent('.block');
itemid = block.data('itemid');
$.post('delete.php',[itemid: itemid]...);
});

Store very small amount of data with javascript

I have one of those websites that basically gives you a yes or no response to a question posed by the url. An example being http://isnatesilverawitch.com.
My site is more of an in-joke and the answer changes frequently. What I would like to be able to do is store a short one or two word string and be able to change it without editing the source on my site if that is possible using only javascript. I don't want to set up an entire database just to hold a single string.
Is there a way to write to a file without too much trouble, or possibly a web service designed to retrieve and change a single string that I could use to power such a site? I know it's a strange question, but the people in my office will definitely get a kick out of it. I am even considering building a mobile app to manipulate the answer on the fly.
ADDITIONAL:
To be clear I just want to change the value of a single string but I can't just use a random answer. Without being specific, think of it as a site that states if the doctor is IN or OUT, but I don't want it to spit out a random answer, it needs to say IN when he is IN and OUT when he is out. I will change this value manually, but I would like to make the process simple and something I can do on a mobile device. I can't really edit source (nor do I want to) from a phone.
If I understand correctly you want a simple text file that you change a simple string value in and have it appear someplace on your site.
var string = "loading;"
$.get('filename.txt',function(result){
string = result;
// use string
})
Since you don't want to have server-side code or a database, one option is to have javascript retrieve values from a Google Spreadsheet. Tabletop (http://builtbybalance.com/Tabletop/) is one library designed to let you do this. You simply make a public Google Spreadsheet and enable "Publish to web", which gives you a public URL. Here's a simplified version of the code you'd then use on your site:
function init() {
Tabletop.init( { url: your_public_spreadshseet_url,
callback: function (data) {
console.log(data);
},
simpleSheet: true } )
}
Two ideas for you:
1) Using only JavaScript, generate the value randomly (or perhaps based on a schedule, which you can hard code ahead of time once and the script will take care of the changes over time).
2) Using Javascript and a server-side script, you can change the value on the fly.
Use JavaScript to make an AJAX request to a text file that contains the value. Shanimal's answer gives you the code to achieve that.
To change the value on the fly you'll need another server-side script that writes the value to some sort of data store (your text file in this case). I'm not sure what server-side scripting (e.g. PHP, Perl, ASP, Python) runtime you have on your web server, but I could help you out with the code for PHP where you could change the value by pointing to http://yoursite.com/changeValue.php?Probably in a browser. The PHP script would simply write Probably to the text file.
Though javascript solution is possible it is discouraged. PHP is designed to do such things like changing pieces of sites randomly. Assuming you know that, I will jump to javascript solution.
Because you want to store word variation in a text file, you will need to download this file using AJAX or store it in .js file using array or string.
Then you will want to change the words. Using AJAX will make it possible to change the words while page is loaded (so they may, but do not have to, change in front of viewers eyes).
Changing page HTML
Possible way of changing (words are in array):
wordlist.js
var status = "IN"; //Edit IN to OUT whenever you want
index.html
<script src="wordlist.js"></script>
<div>Doctor is <span id="changing">IN</span></div>
<script>
function changeWord(s) { //Change to anything
document.getElementById("changing").innerHTML = s;
}
changeWord(status); //Get the status defined in wordlist.js
</script>
Reloading from server
If you want to change answer dynamically and have the change effect visible on all open pages, you will need AJAX or you will have to make browser reload the word list, as following:
Reloading script
function reloadWords() {
var script = document.createElement("script"); //Create <script>
script.type="text/javascript";
script.src = "wordlist.js"; //Set the path
script.onload = function() {changeWord(status)}; //Change answer after loading
document.getElementsByTagName("head")[0].appendChild(script); //Append to <head> so it loads as script. Can be appended anywhere, but I like to use <head>
}
Using AJAX
Here we assume use of text file. Simplest solution I guess. With AJAX it looks much like this:
http = ActiveXObject==null?(new XMLHttpRequest()):(new ActiveXObject("Microsoft.XMLHTTP"));
http.onloadend = function() {
document.getElementById("changing").innerHTML = this.responseText; //Set the new response, "IN" or "OUT"
}
http.open("GET", "words.txt")
http.send();
Performance of AJAX call may be improved using long-poling. I will not introduce this feature more here, unless someone is interested.

Cascading Dropdown List

I am working on a web app and trying to code a form with two dropdown lists. The list in the second dropdown will be dependent on the selection from the first one. The task itself isn’t too complicated except that once the first selection is made, I need to make a database call to pull the data for the second dropdown. This is where I am having difficulty. Both lists are in fact populated from a database.
I am working on this in a python script and have been trying to do this w/ an onChange javascript function. The web app is built in Zope and page templates may be an option along w/ the python scripts.
you will have to use a combination of Ajax and javascript here. Onchange event of your select drop down call a javascript function. This javascript function will make a ajax request to a python script that will actually make a database hit and return you a response in a javascript variable. With this javascript variable you can edit you DOM and set the html of second select box.
see if u can get some hint from this:
http://www.satya-weblog.com/2007/04/dynamically-populate-select-list-by.html
That's exactly what I did. Below is the javascript function I came up with. OnChange, I call getOptions and the pythonScript creates the second dropdown list. I am able to pass in a parameter to get the data I need for this dropdown. Thanks!
function getOptions() {
var code = 'code=' + $("dropdown1").getValue();
var myAjax = new Ajax.Updater('dropdown2', './pythonScript', { method: 'get', parameters: code });
}

Categories

Resources