I am trying to get the source code of HTML by using an XMLHttpRequest with a URL. How can I do that?
I am new to programming and I am not too sure how can I do it without jQuery.
Use jQuery:
$.ajax({ url: 'your-url', success: function(data) { alert(data); } });
This data is your HTML.
Without jQuery (just JavaScript):
function makeHttpObject() {
try {return new XMLHttpRequest();}
catch (error) {}
try {return new ActiveXObject("Msxml2.XMLHTTP");}
catch (error) {}
try {return new ActiveXObject("Microsoft.XMLHTTP");}
catch (error) {}
throw new Error("Could not create HTTP request object.");
}
var request = makeHttpObject();
request.open("GET", "your_url", true);
request.send(null);
request.onreadystatechange = function() {
if (request.readyState == 4)
alert(request.responseText);
};
You can use fetch to do that:
fetch('some_url')
.then(function (response) {
switch (response.status) {
// status "OK"
case 200:
return response.text();
// status "Not Found"
case 404:
throw response;
}
})
.then(function (template) {
console.log(template);
})
.catch(function (response) {
// "Not Found"
console.log(response.statusText);
});
Asynchronous with arrow function version:
(async () => {
var response = await fetch('some_url');
switch (response.status) {
// status "OK"
case 200:
var template = await response.text();
console.log(template);
break;
// status "Not Found"
case 404:
console.log('Not Found');
break;
}
})();
There is a tutorial on how to use Ajax here: https://www.w3schools.com/xml/ajax_intro.asp
This is an example code taken from that tutorial:
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// Code for Internet Explorer 7+, Firefox, Chrome, Opera, and Safari
xmlhttp = new XMLHttpRequest();
}
else
{
// Code for Internet Explorer 6 and Internet Explorer 5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajax_info.txt", true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
I had problems with the fetch api and it seams that it always returns promise even when it returns text "return await response.text();" and to handle that promise with the text, it needs to be handled in async method by using .then.
<script>
// Getting the HTML
async function FetchHtml()
{
let response = await fetch('https://address.com');
return await response.text(); // Returns it as Promise
}
// Usaing the HTML
async function Do()
{
let html = await FetchHtml().then(text => {return text}); // Get html from the promise
alert(html);
}
// Exe
Do();
</script>
For an external (cross-site) solution, you can use: Get contents of a link tag with JavaScript - not CSS
It uses $.ajax() function, so it includes jquery.
First, you must know that you will never be able to get the source code of a page that is not on the same domain as your page in javascript. (See http://en.wikipedia.org/wiki/Same_origin_policy).
In PHP, this is how you do it:
file_get_contents($theUrl);
In javascript, there is three ways :
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);
});
]4
Edit: doesnt work yet...
Add this to your JS:
var src = fetch('https://page.com')
It saves the source of page.com to variable 'src'
Related
I need to send a mail with jsp, but the page itself mustn't reload. The whole implementation is working fine when reloading on the POST-event, but adjusting the code to work with ajax breaks it. It seems that the jsp-Code within the index.jsp is not executed, when the ajax event is triggerd.
I am gonna show some snippets:
index.jsp
<%
String result = "=(";
String to = request.getParameter("rec_mail");
if(to != null) {
String from = request.getParameter("sendermail");
String host = "mailserver";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session mailSession = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("Feedback");
message.setText(request.getParameter("feedbackinput"));
Transport.send(message);
result = "Sucess!";
}catch (MessagingException e) {
e.printStackTrace();
result = "failed!";
}
}
out.println(request.getParameter("sendermail"));
out.println(result);
%>
<input id="bsend" class="fbutton" type="submit" name="send" value="Send" onclick="loadContent()" style="float:right; width:18%; height:35%;" >
ajax.js
var xmlhttp
function loadContent() {
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Your browser does not support Ajax!");
return;
}
var url="./index.jsp";
xmlhttp.open("post",url,true);
xmlhttp.send(null);
xmlhttp.onreadystatechange=getOutput;
}
function getOutput()
{
if (xmlhttp.readyState==4)
{
alert("Message sent!");
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
(just showing the relevant parts, everywhere)
I get the alert-message, but no mail is sent ... I hope it is clear, what I am trying to do..
Thank you!
Best regards
Don't you also need to set a header for a HTTP Post
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
also, not sure if it will make a difference but I would make "post" to "POST".
I'm using this code below for the navigation system on my site, the purpose is to open an HTML page within a div .. (InnerHTML), but, when I'm clicking one of my menu links I'm getting the JavaScript notification "Problem: " (see "else" in the JavaScript code block). This code is fixed (good) for SEO aspect.
Can someone please tell me what the problem with it is? I'm trying to preserve the code as it is as much as possible.
Thank you in advance for your help!
JavaScript code:
function processAjax(url)
{
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = targetDiv;
try {
req.open("GET", url, true);
}
catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = targetDiv;
req.open("GET", url, true);
req.send();
}
}
return false;
}
function targetDiv() {
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
document.getElementById("containerDiv").innerHTML = req.responseText;
} else {
alert("Problem: " + req.statusText);
}
}
}
In HTML body:
<a onclick="return processAjax(this.href)" href="example.html">CLICK ME</a>
<div id="containerDiv"></div>
The server returned a non-200 response. If you're using a debugger like Firebug, Chrome Developer, or IE Developer, check the Network tab to see exactly where your XHR went, and what the response was.
I'm creating a Chrome extension that injects an HTML form on a page through inject.js and when a query is entered and the button is pressed an API call is made through background.js. The contents are then brought back to the inject.js script and processed.
When I first try to make a call through inject.js I get the following error:
Error in event handler for 'undefined': fetchResult is not defined ReferenceError: searchResult is not defined
Oddly enough when I wait a little and press again the query is fetched.
I'm suspecting fetchresult is undefined the first time because it takes a couple of moments to fetch the query but I don't know how to fix this.
inject.js:
function fetch() {
var fetchResult;
var fetchquery = document.getElementById('field').value;
chrome.extension.sendMessage({greeting: fetchquery}, function(response) {
fetchResults = response.farewell
constructHTML(fetchResultsResults)
});
};
background.js:
function loadXMLDoc(query)
{
if (query){
// new cross origin XML request
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
fetchResult = JSON.parse(xmlhttp.responseText);
}
}
xmlhttp.open("GET","http://XXXXXXXXXXXXXXX&q="+query, true);
xmlhttp.send();
return fetchResult;
} else {
return "noquery";
}
};
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (loadXMLDoc(request.greeting) != "noquery"){
sendResponse({farewell: loadXMLDoc(request.greeting)})
}
});
Any help will be greatly appreciated!
XMLHttpRequest is asynchronous, so instead of return fetchResult, you should invoke a callback to pass the result. Here's an example:
function loadXMLDoc(query, callback)
{
if (query){
// new cross origin XML request
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4)
{
if(xmlhttp.status==200)
{
fetchResult = JSON.parse(xmlhttp.responseText);
callback(fetchResult);
} else {
callback("noquery");
}
}
}
xmlhttp.open("GET","http://XXXXXXXXXXXXXXX&q="+query, true);
xmlhttp.send();
} else {
callback("noquery");
}
};
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
loadXMLDoc(request.greeting, function(fetchResult) {
if (fetchResult != "noquery")
sendResponse({farewell: fetchResult})
else
sendResponse({});
});
return true; // See the description of https://developer.chrome.com/extensions/extension.html#property-onMessage-sendResponse.
});
There may be a small error in my code. please advice me.
I want to call a URL and display the value in div on pageload.I wrote this code from SO but the responseText doesnt write the value in the div element's innerhtml
Code
<script type="text/javascript" >
var req ;
// Browser compatibility check
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
var req = new XMLHttpRequest();
req.open("GET", "www.example.com/Default.aspx?usrname=john",true);
req.onreadystatechange = function () {
document.getElementById('divTxt').innerHTML = "My Status: " + req.responseText;
}
req.send(null);
</script>
<html>
<head/>
<body>
<div id="divTxt"></div></body>
</html>
The output I get is
My status :
PS: I want this to be done after pageload and The url returns a value "online" when called manually
EDIT
This is the code I referred : code
You cannot ajax a url from another domain unless it has implemented CORS
If you need to get data from somewhere which is not same origin you need to use JSONP
Also to debug, try calling the url from the locationbar to see if you receive valid data for your request
req.onreadystatechange = function () {
document.getElementById('divTxt').innerHTML = "My Status: " + req.responseText;
}
you have to check, if the request was successful:
if (req.readyState === 4) {
// what should be done with the result
}
finally, it has to look like this:
req.onreadystatechange = function () {
if (req.readyState === 4) {
document.getElementById('divTxt').innerHTML = "My Status: " + req.responseText;
}
}
Does anyone know of a tutorial on how to read data from a server side file with JS? I cant seem to find any topics on this when I google it. I tried to use but it does not seem to work. I just want to read some data from a file to display on the page. Is this even possible?
var CSVfile = new File("test.csv");
var result = CVSfile.open("r");
var test = result.readln();
To achieve this, you would have to retrieve the file from the server using a method called AJAX.
I'd look into JavaScript libraries such as Mootools and jQuery. They make AJAX very simple use.
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mootools/1.6.0/mootools-core.min.js"></script>
<script type="text/javascript">
//This event is called when the DOM is fully loaded
window.addEvent("domready",function(){
//Creating a new AJAX request that will request 'test.csv' from the current directory
var csvRequest = new Request({
url:"test.csv",
onSuccess:function(response){
//The response text is available in the 'response' variable
//Set the value of the textarea with the id 'csvResponse' to the response
$("csvResponse").value = response;
}
}).send(); //Don't forget to send our request!
});
</script>
</head>
<body>
<textarea rows="5" cols="25" id="csvResponse"></textarea>
</body>
</html>
If you upload that to the directory that test.csv resides in on your webserver and load the page, you should see the contents of test.csv appear in the textarea defined.
You need to use AJAX. With jQuery library the code can look like this:
$.ajax({ url: "test.csv", success: function(file_content) {
console.log(file_content);
}
});
or if you don't want to use libraries use raw XMLHTTPRequest object (but you I has different names on different browsers
function xhr(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest();
} catch(e) {
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
return xmlHttp;
}
req = xhr();
req.open("GET", "test.cvs");
req.onreadystatechange = function() {
console.log(req.responseText);
};
req.send(null);
UPDATE 2017 there is new fetch api, you can use it like this:
fetch('test.csv').then(function(response) {
if (response.status !== 200) {
throw response.status;
}
return response.text();
}).then(function(file_content) {
console.log(file_content);
}).catch(function(status) {
console.log('Error ' + status);
});
the support is pretty good if you need to support browser that don't support fetch API you can use polyfill that github created