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

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>

Related

Cross-subdomain AJAX works in Chrome, not IE

I have a local build of my site running at local.mydomain.com. I'm making ajax requests to api.mydomain.com which is running on an AWS server and returns JSON. In Chrome, I can call the API no problem. But in IE, I get Access Denied.
After researching, it seems to be a cross-(sub)domain restriction. But I was under the impression that this restriction would apply to both browsers. Can anybody see what might be going wrong here and why it might work in some browsers and not others?
It looks like the problem was in the transport object that IE8+ wants you to use. jQuery uses either ActiveXObject (for IE) or XMLHttpRequest (all others), but IE 8 and above requires XDomainRequest for ajax.
What you can do is return a custom xhr object via $.ajaxSettings.xhr like this,
// override xhr for browser that use XDR
if ('XDomainRequest' in window && window.XDomainRequest !== null) {
// override default jQuery transport
jQuery.ajaxSettings.xhr = function() {
try { return new XDomainRequest(); }
catch(e) {
console.log('test');
}
};
// also, override the support check
jQuery.support.cors = true;
}
I pulled this code from a discussion on the subject here:
http://graphicmaniacs.com/note/getting-a-cross-domain-json-with-jquery-in-internet-explorer-8-and-later/
Definitely take a look at that if you think you're experiencing the same problem.

Monitor file change through AJAX, how?

I'm looking for a way through AJAX (not via a JS framework!) to real time monitor a file for changes. If changes where made to that file, I need it to give an alert message. I'm a total AJAX noob, so please be gentle. ;-)
Edit: let me explain the purpose a bit more in detail. I'm using a chat script I've written in PHP for a webhop, and what I want is from an admin module monitor the chat requests. The chats are stored in text files, and if someone starts a chat session a new file is created. If that's the case, in the admin module I want to see that in real time.
Makes sense?
To monitor a file for changes with AJAX you could do something like this.
var previous = "";
setInterval(function() {
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4) {
if (ajax.responseText != previous) {
alert("file changed!");
previous = ajax.responseText;
}
}
};
ajax.open("POST", "foo.txt", true); //Use POST to avoid caching
ajax.send();
}, 1000);
I just tested it, and it works pretty well, but I still maintain that AJAX is not the way to go here. Comparing file contents will be slow for big files. Also, you mentionned no framework, but you should use one for AJAX, just to handle the cross-browser inconsistencies.
AJAX is just a javascript, so from its definition you do not have any tool to get access to file unless other service calls an js/AJAX to notify about the change.
I've done that from scratch recently.
I don't know how much of a noob you are with PHP (it's the only server script language I know), but I'll try to be as brief as possible, feel free to ask any doubt.
I'm using long polling, which consists in this (
Create a PHP script that checks the content of the file periodically and only responds when it sees any change (it could include a description of the change in the response)
Create your XHR object
Include your notification code as a callback function (it can use the description)
Make the request
The PHP script will start checking the file, but won't reply until there is a change
When it responds, the callback will be called and your notification code will launch
If you don't care about the content of the file, only that it has been changed, you can check the last-modified time instead of the content in the PHP script.
EDIT: from some comment I see there's something to monitor file changes called FAM, that seems to be the way to go for the PHP script

FBJS AJAX.post is not working after permissions dialog

I have problems with facebook application based on flash which communicate with PHP using FBJS-bridge. When someone use the application for the first time, he/she is asked for various permissions. After that, flash contact PHP with ajax but request is never sent. When you refresh page, everything is working without any problems.
If you remove the application on privacy settings, refresh the page and try again - same bug happens. If you allow application, refresh page, in other tab remove application and start application in previous tab - user is asked for permissions but everything is working after allowing application.
This is FBJS code
function openPermissions(){
Facebook.showPermissionDialog(/*permissions string*/, permissionOnDone);
}
function permissionOnDone(perms){
if (!perms) {
document.getElementById("indexswf").callSWF('noallow');
} else {
document.getElementById("indexswf").callSWF('allow');
}
}
function ajaxCall(url,parameters){
var params = {};
for(var i=0;i<parameters.length;i+=2){
params[parameters[i]]=parameters[i+1];
}
ajax = new Ajax();
ajax.requireLogin = true;
ajax.responseType = Ajax.RAW;
ajax.ondone = function(data){
document.getElementById("indexswf").callSWF('parseAjax', data);
}
ajax.post('http://the.url.to/the_real_server/not_to_the_fb_url/'+url,params);
}
openPermissions is called to display permission dialog, and on allow flash function allow() is called. In flash, allow() calls JS function ajaxCall(), which should make ajax request. But, ajax.post never sends request. I know that for sure, because flash function parseAjax was never called and also debugging tools in browsers are not showing any ajax requests. URL and parameters are same as when it is working. No flash or JS errors are detected...
Anyone have idea what is wrong here? Maybe facebook bug again since this was all working few days ago...
ajax.requireLogin = true should be set to false for some reason

Simple ajax/prototype problem

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

Debugging: IE6 + SSL + AJAX + post form = 404 error

The Setting:
The program in question tries to post form data via an AJAX call to a target procedure contained in the same package as the caller. This is done for a site that uses a secure connection (HTTPS). The technology used here is PLSQL and the DOJO JavaScript library. The development tool is basically a text editor.
Code Snippet:
> function testPost() {
>> dojo.xhrPost( {
url: ''dr_tm_w_0120.test_post'',
form: ''orgForm'',
load: testPostXHRCallback,
error: testPostXHRError
});
}
> function testPostXHRCallback(data,ioArgs) {
>> alert(''post callback'');
try{
dojo.byId("messageDiv").innerHTML = data;
}
catch(ex){
if(ex.name == "TypeError")
{
alert("A type error occurred.");
}
}
return data;
}
>
function testPostXHRError(data, ioArgs) {
>> alert(data);
alert(''Error when retrieving data from the server!'');
return data;
}
The Problem:
When using IE6 (which the entire user-base uses), the response sent back from the server is a 404 error.
Observations:
The program works fine in Firefox.
The calling procedure cannot target any procedures within the same package.
The calling procedure can target outside sites (both http, https).
The other AJAX calls in the package that are not posts of form data work fine.
I've searched the internets and consulted with senior-skilled team members and haven't discovered anything that satisfactorily addresses the issue.
*Tried Q&A over at Dojo support forums.
The Questions:
What troubleshooting techniques do you recommend?
What troubleshooting tools do you recommend for HTTPS analyzing?
Any hypotheses on what the issue might be?
Any ideas for workarounds that aren't total (bad) hacks?
Ed. The Solution
lomaxx, thx for the fiddler tip. you have no idea how awesome it was to get that and use it as a debugging tool. after starting it up this is what i found and how i fixed it (at least in the short term):
> ef Fri, 8 Aug 2008 14:01:26 GMT dr_tm_w_0120.test_post: SIGNATURE (parameter names) MISMATCH VARIABLES IN FORM NOT IN PROCEDURE: SO1_DISPLAYED_,PO1_DISPLAYED_,RWA2_DISPLAYED_,DD1_DISPLAYED_ NON-DEFAULT VARIABLES IN PROCEDURE NOT IN FORM: 0
After seeing that message from the server, I kicked around Fiddler a bit more to see what else I could learn from it. Found that there's a WebForms tab that shows the values in the web form. Wouldn't you know it, the "xxx_DISPLAYED_" fields above were in it.
I don't really understand yet why these fields exist, because I didn't create them explicitly in the web PLSQL code. But I do understand now that the target procedure has to include them as parameters to work correctly. Again, this is only in the case of IE6 for me, as Firefox worked fine.
Well, that the short term answer and hack to fix it. Hopefully, a little more work in this area will lead to a better understanding of the fundamentals going on here.
First port of call would be to fire up Fiddler and analyze the data going to and from the browser.
Take a look at the headers, the url actually being called and the params (if any) being passed to the AJAX method and see if it all looks good before getting to the server.
If that all looks ok, is there any way you can verify it's actually hitting the server via logging, or tracing in the AJAX method?
ed: another thing I would try is rig up a test page to call the AJAX method on the server using a non-ajax based call and analyze the traffic in fiddler and compare the two.

Resources