What is the best method to detect xml in JavaScript - javascript

What is the best method to detect xml in JavaScript
e.g. is it possible to detect the mime type of a document - particularly if it is text/xml in JavaScript.
this needs to work in Chrome.
thanks,
Josh

If you are using XMLHttpRequest to get this data, then you can simply check for the Content-Type header using the getResponseHeader method (granted that the server sends the appropriate headers).
var getFile = function(address, responseHandler) {
var req = new XMLHttpRequest();
req.open('get', address, true);
req.onreadystatechange = responseHandler;
req.send(null);
}
var responseHandler = function(resp) {
if ( this.readyState < 4 ) { return; }
console.log(this.getResponseHeader("Content-Type"));
};
getFile("http://zebrakick.com/some/file", responseHandler);
(I seem to be using this code sample a lot...)

You can't determine what the mime-type is with Javascript. I would recommend doing checks on the data returned to see if it is valid XML before you try to parse it. (I'm only assuming what you're trying to do. I can provide a more rigid example if you clarify what your goal is.)

I came across this when looking to determine that a chrome extension script was on an XML page. Maybe this saves someone a few minutes.
In the chrome console and content scripts you can check with:
document.contentType==="application/xml"

Related

Is it possible to serve a string via a URL request from one Javascript to another?

I am not even sure that what I ask is possible at all, but maybe somebody would be able to give me some ideas...
Here is the situation. I have a certain third-party Javascript module which is being run in browser. The module exposes an API call which loads some configuration (XML file) from a provided URL. I would like to pass it instead some XML which I generate in my own script. I cannot change the module; so, what I am looking for is some way to specify some URL which will serve my local data. Is there any way to do something like this?
Testing with the "javascript:" pseudo protocol didn't work - making it look like XMLHttpRequest does not accept "pseudo" protocols.
Testing with data URIs did work:
var xmlSource =
`<?xml version="1.0" encoding="UTF-8"?>
<text>
<para>hello world</para>
</text>
`;
var xmlDataURL = "data:text/xml," + xmlSource;
loadConfig( xmlDataURL);
was succesfully sent using a dummy version of loadConfig:
// Dummy loadConfig:
function loadConfig( url)
{ var req = new XMLHttpRequest();
req.open("GET", url);
req.onreadystatechange = function ()
{ if( req.readyState == 4)
console.log(req.responseText);
};
req.send();
}

How to receive data from XMLHttpRequest in chome extension via javascript?

I wanna to send request form a webpage to chrome extension, and then in chrome extenison receive data and read data, is there any way to this?
Ex:
In doman www.nope.com/sendRequest.html will sent data to chrome extension via url chrome-extension://xxxxxxx/getData.htm?isToken=abc, and then extension will receive and can read data "isToken".
Here is my code in sendRequest.html
<script type="text/javascript">
function sendRequest() {
document.write("Sending request");
var req = new XMLHttpRequest();
req.open("POST", "chrome-extension://xxxxxxxxxx/getData.htm?isToken=abc", true);
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
alert(req.responseText);
document.write("OK");
}
}
};
req.send();
}
</script>
And in chrome extension file getData.htm, how can I get data?
(Edit: what type of data are you sending? Could you pass it through as a JSON encoded string, via GET? JSON.stringify() and JSON.parse() may be of use to you. :)
The following may be useful as a guide for accessing that POST/GET data. :) )
As far as I am aware, this is best done using some form of server side scripting. You could use window.location.search in JS, and split the string and perform the necessary functions, but I think server-side scripting may work best. :)
An example of a JS implementation could be as follows:
var url = window.location.search;
var params = url.substr(url.IndexOf("?") - 1, 30);
This would grab the parameters (starting at ? (inclusive), and continue for 30 chars. You could also use something like var params = url.substr(url.IndexOf("?") - 1, url.length); to get the whole parameters list.
How you use this from then on, is up to you, but you could pass it through a switch() or whatever you need. :)
Obviously, this being a chrome extension would limit your options regarding any server-side processing. :/
Edit: The above would go in getData.htm. :)

How to add header data in XMLHttpRequest when using formdata?

I'm trying to implement a file upload API, given here :
Mediafire file Upload
I am successfully able to upload the Post data & Get data, but have no clue how to send the x-filename attribute, which is meant to be Header data as given in API guide.
My Code :
xmlhttp=new XMLHttpRequest();
var formData = new FormData();
formData.append("Filedata", document.getElementById("myFile").files[0]);
var photoId = getCookie("user");
// formData.append("x-filename", photoId); //tried this but doesn't work
// xmlhttp.setRequestHeader("x-filename", photoId); //tried this too (gives error) [edited after diodeous' answer]
xmlhttp.onreadystatechange=function()
{
alert("xhr status : "+xmlhttp.readyState);
}
var url = "http://www.mediafire.com/api/upload/upload.php?"+"session_token="+getCookie("mSession")+"&action_on_duplicate=keep";
xmlhttp.open("POST", url);
// xmlhttp.setRequestHeader("x-filename", photoId); //tried this too, doesnt work. Infact nothing gets uploaded on mediafire. [edited after apsillers' answer]
// cant get response due to same origin policy
xmlhttp.send(formData);
Your error
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable
appears because you must call setRequestHeader after calling open. Simply move your setRequestHeader line below your open line (but before send):
xmlhttp.open("POST", url);
xmlhttp.setRequestHeader("x-filename", photoId);
xmlhttp.send(formData);
Use: xmlhttp.setRequestHeader(key, value);
Check to see if the key-value pair is actually showing up in the request:
In Chrome, found somewhere like: F12: Developer Tools > Network Tab > Whatever request you have sent > "view source" under Response Headers
Depending on your testing workflow, if whatever pair you added isn't there, you may just need to clear your browser cache. To verify that your browser is using your most up-to-date code, you can check the page's sources, in Chrome this is found somewhere like:
F12: Developer Tools > Sources Tab > YourJavascriptSrc.js and check your code.
But as other answers have said:
xhttp.setRequestHeader(key, value);
should add a key-value pair to your request header, just make sure to place it after your open() and before your send()

Get Raw Gist File [duplicate]

This question already has answers here:
Pull in JSON data
(3 answers)
Closed 6 years ago.
What I want is simple. Is there any way (including a work around) to make this work?
function loadXMLDoc() {
var request = new XMLHttpRequest();
var gistRawFileUrl = 'https://gist.github.com/kentcdodds/5822336/raw/6ef128c8c8d6fe416782d969efa95d36e0acf374/KentsBlog.md';
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
var gistFileContent = request.responseText;
doSomethingCool(gistFileContent);
}
};
request.open('GET', gistRawFileUrl, true);
request.send();
}
Right now, if I execute this in the console here I'm getting:
XMLHttpRequest cannot load https://gist.github.com/kentcdodds/5822336/raw/6ef128c8c8d6fe416782d969efa95d36e0acf374/KentsBlog.md. Origin http://stackoverflow.com is not allowed by Access-Control-Allow-Origin.
This makes sense, and I know I'm not going to get GitHub to open up their access control, but if there's a work around to this or if I'm doing something wrong that would be great.
I realize that you can get the content of the file, by hitting the JSONP endpoint, but that doesn't give you the newline characters, so what was once this:
Hello World!
You
Rock!
Is now this:
Hello World!YouRock!
Thanks in advance.
Edit The problem with the newlines is something I need to fix on my end, not a Gist thing.
Check out this answer: https://stackoverflow.com/a/10454873/240963
API endpoint will give you content of each file within the Gist, including the formatting. The only downside is that you need to transfer extra data even if you already know the URL for the raw file.
We can simplify the code from the original answer, since you don't want to parse JSON and you probably know the filename:
$.ajax({
url: 'https://api.github.com/gists/'+gistid,
type: 'GET',
dataType: 'jsonp'
}).success( function(gistdata) {
var content = gistdata.data.files[filename].content;
DoSomethingWith(content)
}).error( function(e) {
// ajax error
});
JSFiddle
Using JSONP with raw XHR is a bit more complicated, but you could use something lighter than jQuery.

How to receive response on client side?

I have this form to upload an xml file to server, I am using fiddler to monitor each req and resp. So the server sends me a small xml and i would like to receive it in my javascript as XMLHttpRequest makes it happen
Note: I am uploading a file so enctype="multipart/form-data"
var client;
var url_action = "/csm/create.action";
var dataString;
if (window.XMLHttpRequest) {
client = new XMLHttpRequest();
} else {
client = new ActiveXObject("Microsoft.XMLHTTP");
}
if (client.readyState == 4 && client.status == 200) {
alert(client.responseTest);
}
client.open("POST", url_action, true);
client.setRequestHeader("enctype", "multipart/form-data");
client.send();
My question is how can i receive the response from server side to JS variable. In the above code XMLHttpRequest i don't think i can send a multipart request (file upload). So any alternative is welcome. Whichever solution provides me a response is good.
Here is what i am doing, to submit the form. Thanks :)
var url_action="/csm/create.action";
$('#mainForm').attr('action', url_action);
$('#mainForm').submit();
Updated with solution
$(data).find('com\\.abc\\.db\\.ConfigInfo').each(function(){
cfgid=$(this).find('cfgId').text();
cfgname=$(this).find('cfgName').text();
filename=$(this).find('fileName').text();
timestamp=$(this).find('updateDate').text();
alert(cfgid+", "+cfgname+", "+filename+", "+timestamp);
});
You have jQuery available so don't ever create XHR objects manually.
Besides that, you cannot use AJAX for file uploads unless you don't care about compatibility with certain browsers.
Last but not least, you want to use the jQuery form plugin which will automatically fallback to a hidden iframe and a regular form if there is a file input in the form.
Note that you need to wrap your JSON response in <textarea></textarea> for it to work properly though. See http://jquery.malsup.com/form/#file-upload for details. If you want to return XML you don't need to wrap it though - it should work fine without any server-side changes.

Categories

Resources