javascript variables loaded from server are not defined in chrome but firefox - javascript

After form data input the data will be processed on server. The result will be responded immediately to client on same site where the data were entered. The tool "visualize.js" needs the result to visualize.
view.py:
if form.is_valid():
//data processing ...
return render(request, 'data_input.html',{'n':n,'t':t,'f':f,'s':s})
data_input.html:
<script type='text/javascript'>
var n_value = {{n}}; //to be visualized
var t_value = {{t}}; //to be visualized
var f_value = {{f}}; //to be visualized
var s_value = {{s}}; //to be visualized
</script>
<script type='text/javascript' src ="{% static "visualize.js" %}" ></script>
In firefox the variables can be found and visualized by the external tool "visualize.js" but in chrome they seem not to be defined with the error:
Uncaught ReferenceError: n is not defined
I also tried some code tricks like "visualize.js" should be loaded after the result is there but no success.
Any idea I could try? Thank you.

So, I already mentioned that my javascript visualization tool only worked in firefox and not in google chrome. After I tried a lot I found this solution:
<script type='text/javascript'>
var n_value = {{n|safe}}; //to be visualized
var t_value = {{t|safe}}; //to be visualized
var f_value = {{f|safe}}; //to be visualized
var s_value = {{s|safe}}; //to be visualized
</script>
safe has to be used.

Related

When a page loads can it pass data to an ES6 module?

I am writing an app where some of the data to be used in the app is fixed and not going to change once the page is loaded. Other data is changing all the time and is brought into the app by ajax when the user clicks a button. This data needs to be combined with the fixed data for displaying to the user every time they click the button.
I want to use ES6 modules for this app. The solution I have attempted is shown below. In reality the variable, fixedData, would be quite a large data structure which is why I definitely do not want to get it by ajax every time the user clicks the button as that would be unnecessary and take time transferring data. Here I have used the value 6 for fixedData to keep the example simple.
The line, const fixedData = 6, would be made as PHP generates the page like this: `const fixedData = '<?php echo 6; ?>';
index.php:
<script type='module' src='./main.js'>
const fixedData = 6;
</script>
main.js:
const h2 = document.createElement('h2');
function displayFixedData(fixedData){
h2.innerText = data;
document.body.appendChild(h2);
}
displayFixedData(fixedData);
When I run this, I get 'Uncaught ReferenceError: fixedData is not defined'
Is there some way I can feed fixed data into my JavaScript code on page load and which would be available for using as an argument in functions inside ES6 modules in the app?
I feel like I need to export the data from the script tag and import it into main.js although I believe that is not possible. Is there some other way I can achieve that?
Edit:
In response to Barmar's comment I now have something which does work:
index.php
<script type="module">
import { displayFixedData } from './main.js'
const fixedData = 5;
displayFixedData(fixedData);
</script>
main.js:
const h2 = document.createElement('h2');
function displayFixedData(fixedData){
h2.innerText = fixedData;
document.body.appendChild(h2);
}
export { displayFixedData };
You can create a non-executable <script> element containing some text serialization of data, e.g. JSON:
<script id="fixed-data" type="application/json">
<?= json_encode($fixedData, JSON_HEX_TAG) ?>
</script>
<script type="module" src="main.js"></script>
(The JSON_HEX_TAG flag escapes <, preventing HTML injection (XSS) issues with data containing <!-- or </script>.)
Then select and deserialize in your script:
const fixedData = JSON.parse(document.getElementById('fixed-data').textContent);

How to extract parameters attached to a URL in a script on the server related to get diagrams from Google Charts?

I am trying to set up a service on my web space that will receive parameters attached to a URL. Then extract them on the server in a script to replace default parameters by the received ones to generate charts.
I am just engaged with html, javascript, jquery and google charts for roundabout one week. Took some quick online tutorials on some aspects. So I am a novice. Please excuse errors in terminology!
Basically in a web browser the url will be entered with attached parameters. The script on the server receives the url, extracts the parameters and puts them at the places where default values are situated in the code. In the index.htm file is a code that defines properties of a Google Chart. The url parameters are the values of the columns. From that a request to Google Charts API is sent, which returns the generated graph, which is then visible in the browser window of the user.
I have made an example code for the diagram (see attached). Now I am searching for a simple method to do what I stated above. I already read about "param"," "get", "set" and have seen many example codes, with and without jquery, etc. Everybody does it in his own way and with various complexity. I tried to implement those methods into my code, but had a lot of errors I could not solve.
Unfortunately it was not obvious to me for some code, where to put it exactly, as in the examples it was at a certain position, which did not work out for me (sorry that I have included more lines of code as usual people would do here to show you, but it is necessary for me to understand it).
Could you maybe help me, showing me in the example code I provided how I could do it for the three columns of the chart?
The url could look like that:
https://example.org/?c1=10&c2=12&c3=7
In the code the parameters have the same names c1, ..., for simplicity.
Additionally, image of code: https://imgur.com/ns1hL2P
Thank you for any help!
Kaydon
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="chartA"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChartColumnChart);
function drawChartColumnChart(){
var data = google.visualization.arrayToDataTable([['',''],['c1',1],['c2',2],['c3',3]
],false);
var options = {"axisTitlesPosition":"out","width":"900","height":"500","focusTarget":"datum",
"animation":{"easing":"linear"},"bars":"horizontal"};
var chart = new google.visualization.ColumnChart(document.getElementById('chartA'));
chart.draw(data, options);
}
</script>
</body>
</html>
You can use getParameterByName(name, url) to extract parameters
var url = 'https://example.org/?c1=10&c2=12&c3=7'
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
var c1 = getParameterByName('c1', url);
console.log(c1);
// your function liket this
/*
function drawChartColumnChart(){
var c1 = getParameterByName('c1', url);
var c2 = getParameterByName('c2', url);
var c3 = getParameterByName('c3', url);
var data = google.visualization.arrayToDataTable([['',''],['c1',c1],['c2',c2],['c3',c3];
],false);
*/

Netsuite External Url Call

I am Trying to call External URL From Suitelet its throwing 406 Error.
var user_name = ‘username’;
var password = ‘password’;
var url=”Url”;
var auth = nlapiEncrypt(user_name+’:’+password,’base64′);
var headers = new Array();
headers[“Content-Type”] = “application/json”;
headers[“Authorization”] = ‘Basic ‘+auth+”;
headers[“Token”] = ‘abcdddd-djfjjff-djd/dkdkd’;
var token_res=nlapiRequestURL(url, null,headers);
var token_response_XML = token_res.getBody();
nlapiLogExecution(‘DEBUG’, ‘token_response_XML’, token_response_XML);
Anyone Suggest Please?
Thanks in Advance
Based on a quick Google search (it's been a LONG time since I've seen that error code), it looks like your other system is not returning the data in the manner that is expected. I would suggest testing with something like the chrome ARC (Advanced REST Client) extension so that you can see the entire process and get it all perfected. Here is the page I read up on 406 errors to refresh my memory.
406 Not Acceptable

How to read the contents of a file inside an epub using javascript

I need to read, inside a page of an epub3 book, the contents of one of the file of that same epub, being some data to process with a javascript function.
Unfortunately, Javascript prevents from loading local files for security reasons. (e.g the File API only allows loading uploaded user files).
But for me in the context of an epub3, it makes sense and I didn't find any information in the IDPF EPUB3 documentation related to this topic.
Any idea ?
OK. Let's clarify:
I have an epub3 with the following structure:
<root>
META-INF
...
OEBPS
pages
page.xhtml
data
data.xml
In page.xhtml, I want to write in Javascript something like:
<script type="text/javascript">
//pseudo code
var indata = readAsText("../data/data.xml"); // how to write that ???
var outdata = myfunction(indata);
</script>
Found the solution for ages, and realized that it had never been answered:
So answering to my own question ;-)
<script type="text/javascript">
/* Load the file using HTTP GET */
$.get( "../data/data.xml", function( indata ) {
var outdata = myfunction(indata);
}, 'text');
</script>

Problem when I try to open file and write into it

Could somebody explain why the following simple script doesn't work in Firefox and how can I fix it?
<script type="text/javascript">
var w = window.open("a.php");
w.document.write("hello");
</script>
Thanks much
(edited to make the code sample display better)
DOM Scripting is more up to date and more robust.
e.g.
var w = window.open("a.php");
w.onload = function(){//you could also use dom ready rather than onload but that is a longer script that I've not included here
var body = w.document.getElementsByTagName("body")[0];
body.appendChild(document.createTextNode("bar"));
}
I'm pretty sure you can't read/ write files using javascript because it's a client side language? I may be completely wrong though!
EDIT:
Try this code:
var new_window, new_window_content = [];
new_window_content.push('<html><head><title>New Window</title></head>');
new_window_content.push('<body>New Window</body>');
new_window_content.push('</html>');
new_window = window.open("", "", "status,height=200,width=200");
new_window.document.write(new_window_content.join(''));
Cheers, Sean
To the others posting answers here: he is not trying to open a file and write to it - it is impossible in javascript in a browser. What he is instead trying to do with the w.document.write is to write to the end of the web page he has just opened in a browser.
Google Chrome says this code fails as:
>>> var w = window.open("http://www.google.co.uk");
undefined
>>> w.document.write("lol");
TypeError: Cannot call method 'write' of undefined
You first need to open the document stream by using document.open() - this will add a write function in w.document:
<script type="text/javascript">
var w = window.open("a.php");
w.document.open();
w.document.write("hello");
w.document.close();
</script>

Categories

Resources