Simple ajax/prototype problem - ajax

im beginning with Ajax, i have problem with including Ajax files.
Ajax code written in original page (like index.php) and placed in (head) section works fine, but when i try to place code in external file (in js folder, where is placed prototype.js file), i don't get any response, not even in Firefox Error Console.
I haven't changed Ajax code except url for calling PHP function.
edit:
calling ajax files:
<script type="text/javascript" src="js/prototype.js"></script>
<script type="text/javascript" src="js/myValidation.js"></script>
</head><body>
....
Username: <input type="text" name="uname" id='uname' />
Available?
<span id="result"></span>
Email address: <input type="text" name="email" />
...
I embaded this function call in html. Validate function is from book "PHP and Script.aculo.us Web 2.0 app interfaces"
myValidation.js
function Validate(){
var user=$('uname');
var name="uname="+user.value;
var pars=name;
new Ajax.Request(
'myValidation.php',
{
method:'post', parameters:pars, asynchronous:true, onComplete: showAvailable
}
);
}
function showAvailable(originalRequest){
var newData=originalRequest.responseText;
$('result').innerHTML=newData;
}
This example is from mentioned book

You haven't shown us your myValidation.js file, but here are the typical reasons I see when people move from inline script blocks to external files and things stop working:
They put script blocks in the external JavaScript files. You probably didn't do that, but I've seen it often enough to mention it. Your external script is pure JavaScript, so for instance it should be:
function Validate() {
// ...
}
not:
<script type='text/javascript'>
function Validate() {
// ...
}
</script>
I've seen the latter a fair bit.
They put the JavaScript file in a location that doesn't match their script tag src.
They left an opening <!-- or closing --> in the script. Important not to do that, in external JavaScript files those are syntax errors.
They're using a web server that's case sensitive and the src attribute and the file's actual name don't match.
They're using a web server sensitive to permissions and the file doesn't have the right permissions.
In the case of the last two above, it's easy to check: Just open a new tab and actually enter the URL of the JavaScript file. If you see the JavaScript, great; if not, you probably have more information.
For issues like this (and hundreds of others), there's nothing like having a decent toolset. For debugging JavaScript on browsers, there are quite a few. There's Firebug (a Firefox add-in), Chrome's and Safari's Development Tools (built into the browsers), Microsoft Visual Studio or Script Debugger for debugging with IE, etc. Firebug and Dev Tools would both tell you about broken src links, as well as any exceptions, etc.

Have you checked that those files are accessible from the HTML code? And more - have you placed you scripts in the bottom of the page - because AJAX will bind it's handlers only to existing elements?

Problem solved.
In /js/ folder i had one php file, that i put there just because of simplicity. After moving it to other location all worked. Don't know if that is rule, nut no php files in /js/ folder. Thanks T.J and Tomasz

Related

Can I prevent obfuscation when debugging my Google Apps Script spreadsheet add-on? [duplicate]

I can't find syntax errors in my JavaScript that is in the Google HTMLService (html window in Google Scripts). My work involves Google Visualizations which requires this. It is my first experience with JavaScript and HTML so I'm quite prone to mistakes making this a distressing problem.
The execution log just shows that the html was run, and I don't where in my code to look for errors. I expect that somewhere would say "error in: line x" or "object not accepted line y" but I just don't know where to look.
I would appreciate any pointers on where to find a solution or how to clarify my question.
You can use your browser's Developers Tools. In Chrome, press the f12 button, OR choose More Tools, Developer Tools, and window will open in your browser that looks like this:
One of the tabs is labeled Console. You can print information to the console by using a:
console.log('This is text: ' + myVariable);
statement.
When the Apps Script macro runs, and serves the HTML to your browser, if there are errors, they will be displayed in the Console Log.
I used the HTML you posted, and got msgs in the console of this:
So, for the JavaScript in a <script> tag of the HTML, you don't look for errors in the Apps Script code editor. You need to use the browsers Developer Tools. The JavaScript in a .gs code file is server side code. It runs on Google's servers. The JavaScript in an HTML tag runs in the users browser on the users computer.
You can also step through client side JavaScript code in your browser.
One problem is, that when the HTML is served, the code is changed.
So the JavaScript in your Apps Script code editor will not look the same as what gets served to the browser. If you view the JavaScript served to the browser, it will look totally different than the code in the Script tag in the original file.
You could also use a code editor that has error checking in it. Net Beans has a free code editor.
Debugging a Google Apps Script web application depends a lot on what Google Apps Script features are used, i.e. if it's created using templated HTML, if the client side communicates with the server side, etc.
As the OP case the Google Apps Script execution log doesn't show any error message, it's very likely that the HtmlOutput was created and it should be possible to inspect the code on the client-side.
Google sends to the client-side a IIFE that inserts into an iframe a satinized version of the HTML/CSS/JavaScript passed to the HtmlService, i.e. the white spacing will not be same, comments will not be included among other changes. Anyway, you might use the dev tools to see the resulting JavaScript and call JavaScript functions from dev tools console, etc.
To execute client-side JavaScript from a Google Apps Script web app, first select the userHtmlFrame(userCodeAppPanel) on the console dropdown selector:
You can even do changes to the client-side JavaScript using the dev tools Elements panel or using JavaScript in the dev tools console, and do other stuff. Just bear in mind that changes done there will not be saved on the Google Apps Script project.
It's worthy to mention that it's possible to debug pure JavaScript using the Google Apps Script editor. The easier way is to put the JavaScript code in a .gs file and use HtmlTemplate to create the HtmlOutput object of the web application together with: ScriptApp.getResource(name).getDataAsString(). Also this approach will help to test the JavaScript code using desktop tools, will help to make it easier to fix "Malformed" errors caused by missing / misplaced <,>,",',(,),:,; and take advantage of the intellisense features for JavaScript that aren't available in the .html files.
Sample of a web application having the client-side JavaScript on a .gs file instead of on a .html file. The client-side JavaScript is in the javascript.js.gs file. In this overly simplified example, the function to be tested require parameters. This makes that the function cannot be run directly from the Editor toolbar, so there is couple of "test" functions on the test.gs file that set the required parameters and call the function that we want to debug.
Code.gs
/**
* Respond to HTTP GET request. Returns a htmlOutput object.
*/
function doGet(e){
return HtmlService.createTemplateFromFile('index')
.evaluate()
.setTitle('My web app');
}
/**
* Returns the file content of a .gs or .html Google Apps Script file.
*
* #param {filename} Google Apps Script file name. It should not include the .gs or .html file extension
*/
function include(filename){
const [name, sufix] = filename.split('.');
switch(sufix){
default:
return HtmlService.createHtmlOutputFromFile(name).getContent();
case 'js':
const content = ScriptApp.getResource(name).getDataAsString();
return `<script>${content}</script>`;
}
}
index.html
<!DOCTYPE html>
<html>
<head>
<?!= include('stylesheet.css') ?>
</head>
<body>
<p>Add here some content</p>
<?!= include('javascript.js') ?>
</body>
</html>
javascript.js.gs
/**
* Arithmetic addition of two operands. Validates that both operands are JavaScript numbers.
*
* #param {number} a Left addition operand
* #param {number} a Right addition operand
*/
function addition(a,b){
if(typeof a !== 'number') || typeof b !== 'number') throw new Error('Operands should be numbers');
return a + b;
}
tests.gs
/**
* Passing two numbers. Expected result: 2.
*/
function test_addition_01(){
const a = 1;
const b = 1;
const result = addition(a,b);
console.log(result === 2 ? 'PASS' : 'FAIL');
}
/**
* Passing one number and one string. Expected result: Custom error message.
*/
function test_addition_02(){
const a = 1;
const b = '1';
try{
const result = addition(a,b);
} catch(error) {
console.log(error.message === 'Operands should be numbers' ? 'PASS' : 'FAIL');
}
}
Note: ScriptApp.getResource can't pull files from libraries even when including this method on the library
For debugging JavaScript that makes use of other technologies, i.e. document.getElementById(id) one option is to dev tools console or using try... catch and call some function from the server side, google.script.run, for logging errors on the execution logs.
To debug a JavaScript that calls JavaSCript libraries, you might copy the libraries code into one or multiple .gs files or load it into the server side by using UrlFetchApp and eval (see How to load javascript from external source and execute it in Google Apps Script)

How can i read the xml file using AJAX? [duplicate]

I'm a novice to AJAX and just want to confirm: if I have all my code in a folder on my desktop and I am using AJAX to output file content in a div in HTML, is it possible to access local files through AJAX or file should have to be on server?
I am just testing AJAX functionality for the first time and i am facing problem as its showing error "Access denied " in .js file
For security reasons JavaScript's access to the file system on the client is restricted - consider whether you would want (somebody else's) JavaScript to read your sensitive documents.
Even when experimenting it's best to work with a realistic topology, serve things from the server that would be served from there in the real system.
It's really easy to set up a web server such as Apache to point to your development directory, so the "server" is just your desktop in disguise. Hence the edit/test cycle is really quick.
File Access is prohibited from the start, in any browser javascript implementation. Someone can disable that "security feature" in his browser manually. For instance, for Google Chrome you have to startup the executable with --disabled-web-security as commandline argument. Firefox can disabled that within it's about:config.
Anyway, you totally cannot rely on that of course if you're writting code for the public. But there is light at the end of the tunnel. The "new" Javascript File API is already available in Chrome, other vendors will follow soon I guess/hope. That API "officially" allows your script to read files on the local machine.
Javascript is work on client side but have limited access so it not able to access local files form the client machine.
So you require to palce you content on server than you can use ajax and get the data in you div to display the client.
If you just want it for testing you can try disabling web security on chrome and then it should work.
I hope its possible to access a file locally using Ajax, i tried it with mozilla firefox and worked well. I'd created 2 text files and paced in the same folder. Here is the code. Sorry if there is any mistake.
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest(); //Not IE
}
else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP"); //IE
}
else {
alert("Your browser doesn't support the XmlHttpRequest object. Better upgrade to Firefox.");
}
}
var receiveReq = getXmlHttpRequestObject();
function sayHello(fname) {
if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
receiveReq.open("GET", fname, true);
receiveReq.onreadystatechange = handleSayHello;
receiveReq.send(null);
}
}
function handleSayHello() {
if (receiveReq.readyState == 4) {
document.getElementById('span_result').innerHTML = receiveReq.responseText;
}
}
Here is the html code
<select name="files" onchange="sayHello(this.value)">
<option value="">Select a file</option>
<option value="file.txt">file.txt</option>
<option value="file2.txt">file2.txt</option>
<option value="ajax.html">Ajax.html</option>
</select><br>
<p>Contents of the file will be displayed below</p>
<div id="span_result"></div>

js in html is not executing in Phoenix framework sample app

I'm playing around with the phoenix framework. I copied the chat example entirely but I'm not getting any results.
In fact when I write console.log("testing") in my app.js I notice that my console does not log anything...
I am getting the error referenced in this link:
phoenix framework - invalid argument at new Socket - windows
However that error seems to be related to Brunch not working in windows. When I brunch build, I can confirm that app.js has the console.log("testing") that I included.
Nevertheless, I don't see that console log when I visit my localhost:4000.
Why is JS not executing?
Turns out the guide is missing a key line that made it not work.
The guide has the following:
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="<%= static_path(#conn, "/js/app.js") %>"></script>
</body>
But that is missing the below line which you can put above the body tag.
<script>require("web/static/js/app")</script>
Even as Chowza already solved this question I would like to propose another, possible cleaner solution, using the autoRequire feature of Brunch.io.
The problem occurs because Brunch.io does not autoRequire the app.js under Windows correctly. Chowza worked around this issue by requiring the file manually in the html. You can omit the manual require if you alter the /brunch-config.js as follows: Change from
modules: {
autoRequire: {
"js/app.js": ["web/static/js/app"]
}
}
To
modules: {
autoRequire: {
"js/app.js": ["web/static/js/app"],
"js\\app.js": ["web/static/js/app"]
}
}
This way the app.js is autoRequired, even if you work on a Windows based system.
I would like to mention, that this solution is based on the link Chowza himself posted, so all credit goes to him for pointing to the link.

Ace editor "SECURITY_ERR: DOM Exception 18" in Chrome when running locally (no server)

I'm trying to run Ace editor from file system for now and in Chrome I'm getting:
"SECURITY_ERR: DOM Exception 18"
FireFox doesn't mind it.
Found this on google groups:
due to same origin restrictions workers can't be loaded from cdn you
need to put them on your site, and add ace.config.set("workerPath",
"path/to/ace/src-min");
No joy.
I'm initializing the editor like so:
<script src="js/source-editor/src-min-noconflict/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
var editor = ace.edit("editor");
ace.config.set( "workerPath", "js/source-editor/src-min-noconflict");
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/css");
</script>
Am I missing something hopelessly simple?
This isn't a full solution but it may help:
editor.getSession().setUseWorker(false);
This turns off worker, probably destroying performance in the process. It should probably be conditional on whether you are a local file by checking the url.
For what's it worth, issue disappears one deployed to server.

How to implement message passing in Firefox extension?

I have a file which overwrites overlay.xul that overwrites browser.xul. I want to implement message passing in a similar way as implemented in chrome extensions.
chrome.manifest-
content helloworld content/
overlay chrome://browser/content/browser.xul chrome://helloworld/content/overlay.xul
overlay chrome://navigator/content/navigator.xul chrome://helloworld/content/overlay.xul
skin helloworld classic/1.0 skin/
style chrome://global/content/customizeToolbar.xul chrome://helloworld/content/overlay.css
How to I register content_script.js which in my case is overlay.js?
Overlay.xul -
<script type="application/x-javascript" src="chrome://helloworld/content/jquery.js" />
<script type="application/x-javascript" src="chrome://helloworld/content/overlay.js" />
<script type="application/x-javascript" src="chrome://helloworld/content/background.js" />
Now inside my overlay.js I'm using -
document.documentElement.addEventListener('click', function(e) {
messageManager.sendAsyncMessage('MyMessenger.MyMessage', {});
}, true);
And the background.js is-
addMessageListener("MyMessenger.MyMessage", function(obj) {
Firebug.Console.log(obj.name);
}, true);
What is the correct syntax for message passing?
How do I configure the connection between content script and browser script?
If all you are interested in is really injecting a content script and communicating with it then it should be easier to use the Add-on SDK, particularly the page-mod package. It allows injecting content scripts easily and provides a way to communicate (see "Communicating With Content Scripts" section in the docs I mentioned).
As to messageManager, it is meant for a multi-process environment but it will work in the current single-process Firefox as well. The main problem with your code above is: addMessageListener isn't a global function, you should call messageManager.addMessageListener(). But using messageManager to pass messages between scripts that are loaded into the same namespace and could call each other directly is an overkill anyway.
To communicate with a content script in the current tab the script in the overlay would do:
gBrowser.selectedBrowser.messageManager.sendAsyncMessage('MyMessenger.MyMessage', {});
And the content script would indeed have addMessageListener as a global function so this should work:
addMessageListener("MyMessenger.MyMessage", function(obj) {
console.log(obj.name);
});

Resources