Load external URL content using pure Javascript - javascript

The following JQuery gets content of an external url:
var url = 'example.com/editor/stores/10';
$('#storeArticlePublish_Channel').load(url);
I do not want to use JQuery. How would I do this using normal javascript?

You can use XMLHttpRequest object for this.To make a request:
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
xmlhttp.open("GET",URL,true);
xmlhttp.send();
The 'URL' is the url you want to execute/open.
The 3rd parameter is for async request, it can be either true or false.
And to get the result in #storeArticlePublish_Channel element, you can simply use this in the next line:
document.getElementById("storeArticlePublish_Channel").innerHTML = xmlhttp.responseText;

Related

How to write a JavaScript which returns the contents of a webpage as result when the URL is given

I want to write a JavaScript to return contents of a webpage when URL is given and enter those contents as a data in table?
The alert pop up is not working.
Return HTML content as a string, given URL. JavaScript function returns a blank screen.
Here is my code:
<html>
<head></head>
<body>
<script type="text/JavaScript"> function httpGet(theUrl) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", theUrl, false);
xmlHttp.send(null);
return xmlHttp.responseText;
}
document.write(httpGet("stackoverflow.com/")); </script>
</body>
</html>
You can simply get contents of a webpage by using javascript's ajax
var contents="";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
contents=this.responseText;
}
};
xhttp.open("GET", "webpage.html", true);
xhttp.send();
Although you can also manipulate HTML you should make sure that webpage.html is showing the data in a valid format for you to easily manipulate. Like JSON, xml or anything else so that you can use the data in the contents variable and iterate over it for your insert statements.
The reason because its showing a blank screen is because of the cross origin policy. stackoverflow.com does not allow CORS(cross origin requests).
And one more thing,, Until and unless you are requesting from a relative Url, specify the address with the protocol name.
Like : 'stackoverflow.com' to 'http://stackoverflow.com'
So just change the address to your file and it will work fine. :)

How to use AJAX in Java? [duplicate]

This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 6 years ago.
I have the following javaScript function:
function loadSomething() {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "javaservlet.java", true);
xhttp.send();
}
and I want to get, lets say an int value from a Java Servlet - "javaservlet". What code should I write in javaservlets doGet() method in order to send a value, so I can get and use it in javaScript? Thank you!
So, you want to return something from your servlet back to the javascript you called that servlet from. Here is the way, make an XMLHttpRequest object using these lines of code
var reqObject = new XMLHttpRequst(); or new ActiveXObject("Microsoft.XMLHTTP");
now make a request to the servlet's get or post method using the XMLHttpRequst's open method, you can simply do it like this
reqObject.open("GET/POST", "ServletName", true);
now if you have made a request to the server and state of the object reqObject is being changed then you will want to see the changes that are being made. Call a function when the state of the object is changed
reqObject.onreadystatechange = processRespose;
if you want to send something as parameter to the servlet use send method otherwise send null.
reqObject.send(null);
now if the servlet is returning something in the method you called from .open the state of the object will be changed and function processResponse will be called.
function processResponse(){
//check whether the response form the server is intact and correct
if(reqObject.status==200 && reqObject.readyState==200){
//simply means we got the response correctly
//Now you can get the response by
var res = reqObject.responseText;
}
}
you can read about the objects methods and properties here
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
I java servlet you just have to send the expected string with the PrintWriter's object. A rough version of Get method would look somewhat like this
doGet(request, response){
PrintWriter out = response.getWriter();
out.println("Javasrvlet");
}
You need to provide url mapping for that servlet in web.xml. I am assuming your servlet class name is JavaServlet.
<servlet>
<description></description>
<display-name>JavaServlet</display-name>
<servlet-name>JavaServlet</servlet-name>
<servlet-class>JavaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JavaServlet</servlet-name>
<url-pattern>/javaServlet</url-pattern>
</servlet-mapping>
Now change the following in javascript code to send GET request to JavaServlet.
function loadSomething()
{
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "javaServlet", true);
xhttp.send();
}
You can write like this....
public void service(HttpServletRequest request, HttpServletResponse){
response.getWriter().write("<Your Data>");
}

Pulling already loaded JS into a local variable

The source of linked to .js is not available via the DOM currently.
var b = document.createElement("script");
b.type= "text/javascript";
b.src = "foo/source/ArcJ.js" // dynamically load .js file
Can I just do
var c = b.src // probably not
I think this would just give me the path...I want the source...i.e. all the code in a string.
Is there a way to do this with out using ajax? Shouldn't this be a simple DOM Pull...
document.getElementById(b.id).source_code
?
.src is the url, so you just load the url from that using an ajax request...
$.get($("script[src*=jquery]").attr("src"),function(data){
console.log(data)
})
Took from How do I get source code from a webpage? (written by me)
There is three way in javascript :
Firstly, by XMLHttpRequest : http://jsfiddle.net/635YY/1/
var url="../635YY",xmlhttp;//Remember, same domain
if("XMLHttpRequest" in window)xmlhttp=new XMLHttpRequest();
if("ActiveXObject" in window)xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
xmlhttp.open('GET',url,true);
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)alert(xmlhttp.responseText);
};
xmlhttp.send(null);
Secondly, by iFrames : http://jsfiddle.net/XYjuX/1/
var url="../XYjuX";//Remember, same domain
var iframe=document.createElement("iframe");
iframe.onload=function()
{
alert(iframe.contentWindow.document.body.innerHTML);
}
iframe.src=url;
iframe.style.display="none";
document.body.appendChild(iframe);
Thirdly, by jQuery : http://jsfiddle.net/edggD/2/
$.get('../edggD',function(data)//Remember, same domain
{
alert(data);
});

parse rss feed using javascript

I am parsing an RSS feed using PHP and JavaScript. First I created a proxy with PHP to obtain the RSS feed. Then get individual data from this RSS feed using JavaScript. My issue with with the JavaScript. I am able to get the entire JavaScript document if I use console.log(rssData); with no errors. If I try to get individual elements within this document say for example: <title>, <description>, or <pubDate> using rssData.getElementsByName("title"); it gives an error "Uncaught TypeError: Object....has no method 'getElementsByName'". So my question is how to I obtain the elements in the RSS feed?
Javascript (Updated)
function httpGet(theUrl) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", theUrl, false);
xmlHttp.send(null);
return xmlHttp.responseXML;
}
// rss source
var rssData = httpGet('http://website.com/rss.php');
// rss values
var allTitles = rssData.getElementsByTagName("title"); // title
var allDate = rssData.getElementsByTagName("pubDate"); // date
Try changing the last line of the httpGet function to:
return xmlHttp.responseXML;
After all, you are expecting an XML response back. You may also need to add this line to your PHP proxy:
header("Content-type: text/xml");
To force the return content to be sent as XML.

How can I access the plain text loaded in an <iframe> on IE?

I have an <iframe> whose src points to a plain text file (not HTML). The text gets loaded and displayed on screen, but seems to be hidden to JavaScript.
In other browsers, iframe.contentWindow.document.body.innerText is enough to get it for you, but IE returns an empty string in that case.
Is there a way that IE can access the text inside the file without involving a server?
You can read this file using XmlHttpRequest. If the browser can read it, so can XmlHttpRequest.
/* Read a file using xmlhttprequest
If the HTML file with your javascript app has been saved to disk,
this is an easy way to read in a data file. Writing out is
more complicated and requires either an ActiveX object (IE)
or XPCOM (Mozilla).
fname - relative path to the file
callback - function to call with file text
*/
function readFileHttp(fname, callback) {
xmlhttp = getXmlHttp();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4) {
callback(xmlhttp.responseText);
}
}
xmlhttp.open("GET", fname, true);
xmlhttp.send(null);
}
/*
Return a cross-browser xmlhttp request object
*/
function getXmlHttp() {
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp == null) {
alert("Your browser does not support XMLHTTP.");
}
return xmlhttp;
}
Call the readFileHttp(fname, callback) using the iframe.src property for the fname parameter.
The callback parameter should be a function that does whatever you want with the result.
Something like this:
var myIFrame = document.getElementById('iframeIdGoesHere');
readFileHttp(myIFrame.src, function(result){
//process the result
});
EDIT based on comment and edit in question:
It might be that body is not available as a js property on the document. You could try:
iframe.contentWindow.document.getElementsByTagName('body')[0].innerText
My original answer (kept only as reference because of the comment):
You
say in a comment that you pull the
path from an <input type='file' />.
You can use that to upload the file to
the server, and then read it using
simple file reading mechanisms. (after
all, the <input type='file' /> is
meant for server uploads...)
Just a shot in the dark, but have you tried the innerHTML property?
Alternatively, the more "proper" way to do this is to request the file directly with XMLHttpRequest.
and
window.frames[0].document.getElementsByTagName("body")[0].innerHTML
?

Categories

Resources