I am using AJAX calls and getting JSON as response then it is used to perform various operations. However there are times when I will get HTML response instead of AJAX(a full HTML page), in such cases I want to reload the page with the HTML content (as if a redirection happened). I am able to find out whether a response is HTML or JSON, however I am unable to find a way in which I can reload the page with HTML content received as part of response so that user only sees the HTML content received as part of AJAX response.
Here is the code:
function redirectIfHTML(xhr,data){
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf('html') > -1) {
// Need to reload the data on current window
}
}
You can nuke and rewrite the entire content of the page using document.write():
document.write("<html><body><p>Hello world!</p></body></html>");
If you want to keep the <head> (and therefore your CSS and so forth) a cleaner solution is to replace the content of the body:
$('body').html("<p>Hello world!</p>");
I would never want to do something like this, but you can use some data-url to solve:
A data-URI with MIME-type text/html + the html you just received:
var myurl = 'data:text/html,' + <HTML HERE>
Then you do:
document.location.href = myurl
(i didn't really try it)
Related
I'm working on a simple webmail script in php. The content of a message body is retrieved using jQuery which gets the content returned from a php script. For example:
$.get("file.php", function(data) { /* Data is the message content */ });
From here, I'm then writing the string in data to the document of an iFrame. I want to make sure that the content returned is sanitized and one step to this is removing all references to external files, particularly remote files accessed over http. For example, javascript files or images on a server somewhere. It's important to do this because not only may external scripts try to manipulate my page, external images may be running through a dynamic engine like php and confirming to spammers that my email address is active and able to receive mail, and some images can apparently contain viruses.
The following script can remove a lot of things that may be hazardous:
function sanitize(str) {
var html = $(str);
var evil = new Array("head","base","link","script","img","object","embed","video","audio","iframe");
for (e=0; e<evil.length; e++) { html.find(evil[e]).remove(); }
var result = html.wrap("<div>").parent().html();
return result; }
But my question is this: how can I remove a line of css that contains a reference to an external file? For example, if the message body content contained a tag and inside it was this:
background-image: url(http://some/dodgy/server/image.jpg);
how would I remove that line from the string?
has not been tested , but you can try something like
str = str.replace(/background\-image:\s*url\(.*\);\s*/ig, "");
Hi I'm trying to get contents of the link tag. So with:
<link rel="stylesheet" href="some.css">
I want the contents of the file some.css in a string.
Tried:
document.getElementsByTagName('link')[0].firstChild.nodeValue; // fails
document.getElementsByTagName('link')[0].hasChildNodes(); // false
Any ideas? I don't want to use the styleSheet method (which only works in FF anyway) because it will strip out stuff like -moz-border-radius and such.
Thanks.
I think Daniel A. White is correct. Your best bet is to get the href of the stylesheet, then load the content via Ajax and parse it.
What are you trying to do exactly?
You can't get the contents of a file with only javascript. You'll need an ajax request to the server which opens the file and returns its contents.
To do this, you need to access the file via an ajax request.
So, with jQuery, something like this
$.ajax({
url: "some.css",
success: function(){
//do something
}
});
More details here: http://api.jquery.com/jQuery.ajax/
Note: this only works if the file making the request is on the same server as the file requested.
CSS rules offer a special API, but nothing like innerHTML.
This is as close as it gets:
var result = '';
var st = document.styleSheets[0].cssRules;
for (var i = 0; i < st.length; i++) {
result += st[i].cssText;
}
console.log(result);
However, this will not respect whitespace, comments, erroneous rules, ...
And as usual, this is subject to Same Origin Policy.
In an app that i'am creating i have to receive from the server an xml string with this format eg: <reply>
<script>
alert('Hello World!');
</script>
</reply>
when i did this using ajax work perferct, but when i try to receive the data in an iframe i can't extract the data from the frame because is not there, IE and FF open new tabs and append the data on that tab, how i avoid that and makes them insert the data on the frame.
I can do this work still using Javascript, get the result of the ajax and write it inside the iframe:
first create your iframe tag like this:
than the javascript code to insert the ajax:
var t = document.getElementById('iftarget');
h = t.contentWindow.document.getElementsByTagName('html');
h[0].innerHTML = '<h1>Hello</h1> This must work! Put your data here';
I have created a jsFiddle for this
http://jsfiddle.net/nunomazer/JGyEr/
Best Regards
Hit an interesting problem today when trying to upload an image file < 2MB using dojo.io.iframe.
My function to process the form is called, but before the form is posted to the server I am getting the following error:
TypeError: ifd.getElementsByTagName("textarea")[0] is undefined
My function that is used to action the post of the form is :
function uploadnewlogo(){
var logoDiv = dojo.byId('userlogo');
var logoMsg = dojo.byId('uploadmesg');
//prep the io frame to send logo data.
dojo.io.iframe.send({
url: "/users/profile/changelogo/",
method: "post",
handleAs: "text",
form: dojo.byId('logoUploadFrm'),
handle: function(data,ioArgs){
var response = dojo.fromJson(data);
if(response.status == 'success'){
//first clear the image
//dojo.style(logoDiv, "display", "none");
logoDiv.innerHTML = "";
//then we update the image
logoDiv.innerHTML = response.image;
}else if(response.status == 'error'){
logoMsg.innerHTML = data.mesg;
}else{
logoMsg.innerHTML = '<div class="error">Whoops! We can not process your image.</div>';
}
},
error: function(data, ioArgs){
logoMsg.innerHTML = '<div class="error">' + data + '</div>';
}
});
}
The form is very basic with just a File input component and a simple button that calls this bit of javascript and dojo.
I've got very similar code in my application that uploads word/pdf documents and that doesn't error, but for some reason this does.
Any ideas or pointers on what I should try to get this to work without errors?
Oh I'm using php and Zend framework for the backend if that has anything to do with it, but I doubt it as it's not even hitting the server before it fails.
Many thanks,
Grant
Another common reason for this error is the server isn't packaging the data correctly. This means even if you have set "handleAs: json" you have to send that json wrapped in some html. This is what it should look like:
<html>
<body>
<textarea>
{ payload: "my json payload here" }
</textarea>
</body>
</html>
Your error was saying it couldn't find the textarea in your return from the server. For more look at http://docs.dojocampus.org/dojo/io/iframe
Since the load handler of dojo.io.iframe.send() has been triggered, the request should have been sent to the server and response is back. I think the response from server is not correct. Maybe the server returns an error page.
Use Firebug to inspect current page's DOM and find the transporting iframe created by Dojo and check its content. Firebug can capture iframe I/O too, check its Net tab. You may find the root cause of this issue.
Did you respect the constraint written in the doc ?
IMPORTANT: For all values EXCEPT html and xml, The server response should be an HTML file with a textarea element. The response data should be inside the textarea element. Using an HTML document is the only reliable, cross-browser way this transport can know when the response has loaded. For the text/html (Or XML) mimetype, just return a normal HTML/XML document. In other words, your services for JSON and Text formats should return the data wrapped as the following:
Let's say I have a web page (/index.html) that contains the following
<li>
<div>item1</div>
details
</li>
and I would like to have some javascript on /index.html to load that
/details/item1.html page and extract some information from that page.
The page /details/item1.html might contain things like
<div id="some_id">
picture
map
</div>
My task is to write a greasemonkey script, so changing anything serverside is not an option.
To summarize, javascript is running on /index.html and I would
like to have the javascript code to add some information on /index.html
extracted from both /index.html and /details/item1.html.
My question is how to fetch information from /details/item1.html.
I currently have written code to extract the link (e.g. /details/item1.html)
and pass this on to a method that should extract the wanted information (at first
just .innerHTML from the some_id div is ok, I can process futher later).
The following is my current attempt, but it does not work. Any suggestions?
function get_information(link)
{
var obj = document.createElement('object');
obj.data = link;
document.getElementsByTagName('body')[0].appendChild(obj)
var some_id = document.getElementById('some_id');
if (! some_id) {
alert("some_id == NULL");
return "";
}
return some_id.innerHTML;
}
First:
function get_information(link, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", link, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(xhr.responseText);
}
};
xhr.send(null);
}
then
get_information("/details/item1.html", function(text) {
var div = document.createElement("div");
div.innerHTML = text;
// Do something with the div here, like inserting it into the page
});
I have not tested any of this - off the top of my head. YMMV
As only one page exists in the client (browser) at a time and all other (virtual/possible) pages are on the server, how will you get information from another page using JavaScript as you will have to interact with the server at some point to retrieve the second page?
If you can, integrate some AJAX-request to load the second page (and parse it), but if that's not an option, I'd say you'll have to load all pages that you want to extract information from at the same time, hide the bits you don't want to show (in hidden DIVs?) and then get your index (or whoever controls the view) to retrieve the needed information from there ... even though that sounds pretty creepy ;)
You can load the page in a hidden iframe and use normal DOM manipulation to extract the results, or get the text of the page via AJAX, grab the part between <body...>...</body>ยจ and temporarily inject it into a div. (The second might fail for some exotic elements like ins.) I would expect Greasemonkey to have more powerful functions than normal Javascript for stuff like that, though - it might be worth to thumb through the documentation.