Error in getting data from xml using AJAX - javascript

I am using AJAX for reading data from external xml file but it is giving error "Invalid argument"
I am using IE 8
PFB the code:
var xhr;
xhr = new XMLHttpRequest();
xhr.open("GET","C:/Users/abc/Desktop/Project/POC/ajax/Data.xml", false);
xhr.onreadystatechange = function ()
{
if (xhr.readyState===4 && xhr.status===200)
{
var items = xhr.responseXML.getElementsByTagName('name');
var output = '<ul>';
for (var i=0; i<items.length; i++)
output += '<li>' + items[i].firstChild.nodeValue + '</li>';
output += '</ul>';
var div = document.getElementById('update');
div.innerHTML = output;
}
}
xhr.send();
The line in bold is giving error.
Any idea ?
thanks in advance

you should be using url not path, like change :
xhr.open("GET","C:/Users/abc/Desktop/Project/POC/ajax/Data.xml", false);
to, something like
xhr.open("GET","http://localhost/your_Project/POC/ajax/Data.xml", false);

AJAX requests will not work for file based urls you need to host your sources on a server to make XMLHttpRequest calls

You are creating request to the server for GET for xml. but GET only understands HTTP requests so it is throwing error.
To resolve this problem you should add the xml file to the solution or web deploy directory and then make request with browser address and if successful then make it with your xhr object.

I think you should put xml file on a web server, and point your xhr target to that file url.
which looks like this:
xhr.open("GET","http://localhost/yourpath/Data.xml", false);
The basic html file, which contains your js code, should also be put on the web server too.
http://localhost/yourpath/basic.html
Because of the Same Origin Policy, you can not send a ajax request from file system to web server url, but can send the request from server A to server B, and the two servers should on same origin, both are
http://localhost
etc.

Related

difference between youtube's request and mine

i want to make a script that makes every video's comment section look like the ones that still have the old kind.
for example, videos on this channel:https://www.youtube.com/user/TheMysteryofGF/videos
in Firebug, in the Net tab, i noticed the comment JSON file's URL it is requested from is different.
i tried to run a code on the youtube watch page which would request the file the same way, but it doesnt work, and in firebug it says it was forbidden.
the URL is the same, they are both POST, and i cant figure out what is different. i can even resend the original request in firebug and it works... so anyway, here is a code i tried on a video with "1vptNpkysBQ" video url.
var getJSON = function(url, successHandler, errorHandler) {
var xhr = typeof XMLHttpRequest != 'undefined'
? new XMLHttpRequest()
: new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('post', url, true);
xhr.onreadystatechange = function() {
var status;
var data;
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate
if (xhr.readyState == 4) { // `DONE`
status = xhr.status;
if (status == 200) {
data = JSON.parse(xhr.responseText);
successHandler && successHandler(data);
} else {
errorHandler && errorHandler(status);
}
}
};
xhr.send();
};
getJSON('https://www.youtube.com/watch_fragments_ajax?v=1vptNpkysBQ&tr=time&frags=comments&spf=load', function(data) {
alert('Your public IP address is: ' + data);
}, function(status) {
alert('Something went wrong.');
});
You are using Ajax to get data. Ajax has 1 restriction: You can only get data from your own server. When you try to get data from another server/domain, you get a "Access-Control-Allow-Origin" error.
Any time you put http:// (or https://) in the url, you get this error.
You'll have to do it the Youtube way.
That's why they made the javascript API. Here is (the principal of) how it works. You can link javascript files from other servers, with the < script > tag
So if you could find a javascript file that starts with
var my_videos = ['foo', 'bar', 'hello', 'world'];
then you can use var my_videos anywhere in your script. This can be used both for functions and for data. So the server puts this (dynamically generated) script somewhere, on a specific url. You, the client website can use it.
If you want to really understand it, you should try building your own API; you'll learn a lot.
Secondary thing: Use GET.
POST means the client adds data to the server (example: post a comment, upload a file, ...). GET means you send some kind of ID to the server, then the server returns its own data to the client.
So what you are doing here, is pure GET.

Google App Engine, serving files with Jquery and Python, 2 identical files are returned instead of 1

I am running Flask on GAE with a google app engine backend. I submit a form on my site, send it to the backend, the backend returns an xml file and I would like to serve up that xml file. However, I have an issue serving up my file.
This is the only way I could figure out how to serve up my file, it works, but it returns 2 identical files in the browser instead of one, what am I doing wrong?
On the frontend jQuery:
$.get('submit',
dat,
function(data, status, request) {
if (status = 'success'){
console.log(status);
$("body").append("<iframe src='" + request.getResponseHeader('redirect')+ "' style='display: none;' ></iframe>");
}
else
alert("There is an exception on server side while submitting the response!");
},
'xml');
On the frontend Python:
#app.route("/submit", methods=["GET"] )
def submit():
... do some stuff to get the data and url packaged...
headers = {'content-type': 'application/json', 'charset':'UTF-8'}
r = requests.post(url, data=json.dumps(jsonstring), headers=headers)
response = make_response(r.text)
response.headers["Content-Type"] = 'application/xml'
response.headers.add("redirect", request.url)
response.headers["Content-Disposition"] = 'attachment; filename="exportChecklists.xml"'
return response
Basically, I added a redirect url which was my request url to start with, so when the file was ready, I just created an hidden iFrame that modern browsers redirect to and prompt for download.
How can I modify this to only get 1 file instead of 2?
Thanks for the help.
UPDATE
I have tried doing a synchronous post and still no prompt for download. (I am making a call to my server, and response comes as an XML file from my server).
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "POST", "/submit", false );
xmlHttp.setRequestHeader("Content-type", "application/json");
xmlHttp.send( JSON.stringify(dat ));
return xmlHttp.responseText;
Response Headers:
Cache-Control:no-cache
content-disposition:attachment; filename="exportChecklists.xml"
Content-Length:76
content-type:application/xml
Date:Fri, 27 Dec 2013 22:59:27 GMT
Expires:Fri, 01 Jan 1990 00:00:00 GMT
Server:Development/2.0
UPDATE #2
I still can't figure out how to do this so I only serve one file. While the below explanation is good in general, I can't figure out how to serve only 1 file using jQuery. Could someone please provide an example on how to do this.
The only probable thing i can think of without seeing the server side code, is the following scenario:
SCENARIO:
First lets do some reverse engineering, lets examine the following snippet in your code:
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "POST", "/submit", false );
xmlHttp.setRequestHeader("Content-type", "application/json");
xmlHttp.send( JSON.stringify(dat ));
return xmlHttp.responseText;
OBSERVATION 1:
The line 6 of the snippet return xmlHttp.responseText; proves that the page that you're opening outputs something, i.e. the XML code, since you're attempting to return it.
CONCLUSION 1:
This output that you're printing, is one of the two XML files that get downloaded.
OBSERVATION 2:
Lets see this line of code content-disposition:attachment; filename="exportChecklists.xml"
This prompts the browser to download the XML, to the computer.
CONCLUSION 2:
This is the second XML file that gets downloaded.
NOTE:
This is the best guess made by me without looking at your server code, so think before you downvote, please...
MY RESEARCH AFTER, AlexIIP'S COMMENT:
Let's analyse the jQuery code:
$.get('submit',
dat,
function (data, status, request) {
if (status = 'success') {
console.log(status);
$("body").append("<iframe src='" + request.getResponseHeader('redirect') + "' style='display: none;' ></iframe>");
} else alert("There is an exception on server side while submitting the response!");
},
'xml');
Specifically this line:
$("body").append("<iframe src='" + request.getResponseHeader('redirect') + "' style='display: none;' ></iframe>");
when you append the result of request.getResponseHeader('redirect') as the source of the iframe, its clear that the request doesn't return the XML but a redirect header attribute that points to the XML, so, you get the XML in the iframe and the header content-disposition:attachment; filename="exportChecklists.xml" prompts a download, that's why, you get two downloads. (probably, the iframe and the doc, both try a download, resulting in 2 downloads..)
Now the reason why you get no downloads in JavaScript can be easily understood once you understand the above paragraph, what we can conclude from the above paragraph is:
The response doesn't contain any XML, but a header of the response ("redirect") points to XML code file...
So in JavaScript, when you do return xmlHttp.responseText; you are returning the text (HTML) that the response has, but what really you have is a redirect header with the url of the XML file. So to get XML, instead of:
return xmlHttp.responseText;
you shall do this:
return xmlHttp.getResponseHeader('redirect');
but the above line will return the path to the XML file, and hopefully prompt one download...

Deleting a Google Drive file using JS client

I tried using the example from Google Drive documentation.
So the code is :
var request = gapi.client.drive.files.delete({
'fileId' : someFileId
});
request.execute(function(resp)
{
console.log(resp);
});
The app is installed properly and I'm using drive.file scope.
The problem is that the file is not deleted. It is still present in the Drive UI and cannot be opened anymore or downloaded. File is corrupted.
The request being sent is not the DELETE https://www.googleapis.com/drive/v2/files/fileId as was stated in docs. It is a POST https://www.googleapis.com/rpc?key=API_KEY. The body contains a JSON array:
[{"jsonrpc":"2.0","id":"gapiRpc","method":"drive.files.delete","params":{"fileId":"someFileId"},"apiVersion":"v2"}]
Response contains one empty JSON object. There are no errors in the response and there are no JS errors in the page. The APIs Explorer successfully deletes the file.
Any hints?
Try a XMLHttpRequest instead:
var xmlReq = new XMLHttpRequest();
xmlReq.open('DELETE', 'https://www.googleapis.com/drive/v2/files/' + fileId + '?key=' + apiKey);
xmlReq.setRequestHeader('Authorization', 'Bearer ' + accessToken);

XHR in Chrome Extension with CI

I'm sending a POST from a chrome extension content script to a server I control. I setup the permissions in the manifest ok. Here is my XHR code. (I want to avoid jQuery for this). Its sending an empty responseText
var xhr = new XMLHttpRequest();
xhr.open("POST",'http://mysite.com/make',true);
xhr.onreadystatechange=function() {
if (xhr.readyState == 4) {
var res = JSON.parse(xhr.responseText);
console.log(res);
}
}
xhr.send({'textbox':data[0].user,'from':'extension'});
data[0].user is an object I got directly from the Twitter API
in my CI controller I have
$user = $this->input->get_post('textbox', TRUE);
$from = $this->input->get_post('from', TRUE);
$fullURL = 'http://www.google.com'; //example of a URL from code.
$json = $this->output->set_content_type('application/json');
$json->set_output(json_encode(array('URL' => $fullURL)));
The response text is empty
a jquery call on the other hand works fine
$.post("http://mysite.com/make", { 'textbox': data[0].user, 'from':'jquery' },
function(data) {
console.log(data);
});
Reason is simple, JQuery post method can accept JSON and then convert it to string and send to the server.
What you are trying to do is to directly send JSON here :
xhr.send({'textbox':data[0].user,'from':'extension'}) // Incorrect way
send method should either accept NULL or a string which is generally made up of QueryString Parameters like.
xhr.send("textbox="+ data[0].user + "&from=extension"); // Correct way
This will ensure that your data goes to the appropriate URL with textbox and from as post request parameters.
and queryString will be generated like textbox=username1234&from=extension in the packet's body unlike one goes in Get with the headers along side the URL.
jQuery's post method makes it simpler for you to format data you send using JSON and then internally it converts that to a queryString to send parameters.
You can't directly send Javascript object like that with an XHR object!
Also checkout this example:
http://beradrian.wordpress.com/2007/07/19/passing-post-parameters-with-ajax/

Javascript XML http request can not open RSS file from server, XML status = 0

I am trying to parse an RSS feed using javascript, and I recently ran into a problem opening an XML file from both localhost and web server (I always access my local files using http:// keyword all the time when I work on localhost). I received XML status 0 instead of status 200 (established) in all browser. The problem only occurs when I try to open an XML file hosted on a server. Here is what I have :
if(window.ActiveXObject)//IE
xml_req = new ActiveXObject("Microsoft.XMLHTTP");
else if(window.XMLHttpRequest)
xml_req = new XMLHttpRequest();
else alert('no ajax support');
xml_req = new XMLHttpRequest();
var url = "http://www.something.net/rss.xml";
xml_req.open("GET", url, true);
xml_req.onreadystatechange = function(){
if(xml_req.readyState == 4){
if(xml_req.status == 200){
if(xml_req.responseText != null)
.....//DO STUFF
else{
alert("Error");
return false;
}
}
else{
//THIS IS WHERE THE ERROR OCCURS,STATUS=0 INSTEAD OF 200
alert("XML Status = " + xml_req.status + xml_req.statusText);}
}
}
Everything works fine when I open an XML local file that is not hosted on the server. For instance, the code below opens the rss file within the localhost just fine :
var url = "rssLocalhost.xml";
xml_req.open("GET", url, true);
Please help! Would appreciate any suggestions from anybody out there. Thanks!
You can't make requests to other sites. You either need to proxy the data through your own server, or use a JSON-P data source.

Categories