Javascript - Webpage contents to String - javascript

I'm currently playing around with JavaScript attempting to fetch the contents of a webpage as plain text, and dump the text to a String.
I have found many ways to do this but nothing seems to happen when I do something similar to this: (In this example I use a plain text file)
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
// As you can see I'm also spamming myself with alerts, but they also
// just return blank.
alert(xmlhttp.response);
}
xmlhttp.open("GET", "http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-demo.txt", true);
xmlhttp.send();
How do I go about doing this?

You cannot because of the Same-Origin-Policy.. otherwise each webpage could load some bank website or so.. So they (Browser vendors) implemented Same-Origin Policy.. You can access only websites which have give you access to..
just try put this in you console on stackoverflow:
open devtools while you see this site
put this into the console
jQuery.get('http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-demo.txt')

Related

Either .js or .php file is not running unless page link ends with .html

I am currently creating a website where we take the data of our most visited articles of our website and list them on a specific page.
Now, the way I am collecting the data is by using PHP and I am using JS to generate the result on my page. The thing is that the coding is working but it only works if the page link ends with .html (i.e. www.website.com/article.html) but it my page link is addressed like this: www.website.com/article, the results don't show.
I tried extending the link of my js (i.e. ../result.js) but that doesn't do anything.
If you could please help me figure this out, I'd greatly appreciate it!
Thanks!
Here is a sample of the js code:
var xmlhttp;
function loadXMLDoc(url,cfunc)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function mostVisitedExt()
{
loadXMLDoc('mostvisited.txt',function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var txt=xmlhttp.responseText;
var res = txt.split('*&^');
document.getElementById("mostVisitedExt").innerHTML =
"<ul class='jrecent'><div class='jname'><p class='body'>"+res[0]+"</p> </div><div class='jcontent'><a href=http://"+res[0].toLowerCase()+".website.com"+res[20]+" class='body-link' target='_blank'>"+res[10].substring(2, res[10].length-2)+"</a><p class='body'>" +
res[21] + "</p></div></ul>" +
The mostVisitedExt function is the PHP file where it is getting the data from.

Load same div everytime a button is clicked

I have been troubled on how to load the same div into the same page for days.
Been looking for answer in stackoverflow but not found one yet.
Simplified, this is my code so far,
<script>
function add_fields() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", "add_more.php", false);
xmlhttp.send();
document.getElementById("add_more1").innerHTML = xmlhttp.responseText;
}
</script>
<html>
<body>
<input type="button" onclick="add_fields()" value="ADD"/>
<div id="add_more1"></div>
</body>
</html>
The problem is that when i clicked the button, it will only load add_more.php once. I want it to load everytime the button is clicked. How to do that?
Please help.
function add_fields() {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); //really no need for this anymore these days.
}
xmlhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200) //success
{
document.getElementById("add_more1").innerHTML=this.responseText;
}
}
xmlhttp.open("POST","add_more.php",true); //set the sync to true, modern browsers will block a synchronous request.
xmlhttp.send();
}
This updated versions contains a readystate event that will fill your div every time the Ajax call is completed.
You were using a XMLHttpRequest with the asynchronous option set to false. This could block the user experience and modern browsers (like Firefox) will block this.
if you would like to add more content to the div, use
document.getElementById("add_more1").innerHTML += this.responseText;
+= adds content to the element instead of replacing it. It's a shorthand for:
document.getElementById("add_more1").innerHTML = document.getElementById("add_more1").innerHTML + this.responseText;
SIDENOTE: You are using a POST (in this case a GET would be better, since you're retrieving information only). If you want to send post data to the server you need to put the querystring (without the ?) as an argument in the send method.
To continue with this read up on asynchronous coding:
Easy to understand definition of "asynchronous event"? (very simple explanation).
How does Asynchronous Javascript Execution happen? and when not to use return statement? (more comprehensive).

XMLHttpRequest does nothing....?

I am new to javascript and AJAX, and have spent the last 8 hours on this one problem, and its beating me. I know its simple, just can't find what I am doing wrong. I have an image on my site with a with an on-click=SendCommand() . This is the js code that I have
function SendCommand(){
alert("BingoBango!");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","https://www.justanexample.com/API/MobileAPP/SendCommand.php?apikey=7785adf3a5d3a3adsf555nb5v55bsaer5v&mac=b827eb6ffa19&command=2",true);
xmlhttp.send();
};
I get the alert message, and I get no errors using firebug or in chrome javascript console. However that page is not executed. I can however copy and paste that exact url into the browser and it executes successfully.
Any help would be GREATLY appreciated, its kickin my butt.
The page it is calling is calling a python script as well as updating a mysql record. Is there something i can do in my request to ask it to not use the browser cache and actually hit my server?
You should not use a GET request for things that execute actions on the server. Use POST instead, which should not be cached.
If that doesn't help, adapt your HTTP cache headers or, as a last resort, append random strings to the url.
This is how I would do it
JS
function SendCommand()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","https://www.justanexample.com/API/MobileAPP/SendCommand.php?apikey=7785adf3a5d3a3adsf555nb5v55bsaer5v&mac=b827eb6ffa19&command=2",true);
xmlhttp.send();
}
HTML
<button type="button" onclick="SendCommand()">My button</button>
<div id="myDiv"></div>

Loading a text file into javascript

I have a text file with a lot of values and I want to know if there is a way of loading these text file values into java script so that these values van be used by the script itself. Note I'm a newbie...
You haven't provided much context, but if we assume you mean "JavaScript running in a browser via an HTML page loaded from the same server as the text file", then you want to use the XMLHttpRequest object.
(Which is well documented in many places, so rather then providing yet another tutorial here, I'll let people use Google in the unlikely event of the above link breaking).
There are no shortage of libraries that abstract XHR. e.g. YUI, a host of tiny libraries and jQuery.
Assuming the text file is on your web server and you are loading from the browser, you could use jQuery like so:
jQuery.get('http://localhost/mytextfile.txt', function(data) {
alert(data);
});
Using XMLHttpRequest, you can achieve.
Example:
function ajaxCall() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
alert("Your browser does not support XMLHTTP!");
}
return xmlhttp;
}
xmlhttp = ajaxCall();
xmlhttp.open('GET', 'YOURFILE.txt');
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
alert(xmlhttp.responseText);
}
}
with jQuery:
$('#result').load('ajax/test.txt');
Html code:
<div id="result">Text loaded here</div>
After loading the text will be replaced with the text file.

parse XML file with javascript in variable on click

I am trying to load a different xml file everytime a link is clicked, based on its href.
I have the following in head:
JAVASCRIPT
window.onload=function() {
loadXMLDoc("papers.xml"); // loads the default xml file so that page is not empty
}
function scanForXML(){
var extLinks=document.getElementById('results_list').getElementsByTagName('a');
for (i=0; i<extLinks.length; i++) {
extLinks[i].onclick=function getName()
{
var fileName=this.getAttribute('href');
loadXMLDoc(fileName);
return false;
}
}
}
HTML
<ol id="results_list">
<li> <a class="tooltip" href="paper2.xml"> Teaching with Tablet PC's </a></li>
<li> Tablet PC’s as Instructional Tools </li>
</ol>
The onclick event works, I get the href value but the new xmlFile does not get loaded.
Any ideas why?
ps: no jquery plz, cannot use that. trying to learn better basic javascript
The Javascript load code - by the way it does not work in chrome and opera - but works the default xml file gets loaded in safari
Code:
function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET",dname,false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
}
Thanks!
K
That's because the request is asynchronous : there is no response when your loadXMLDoc function returns.
The usual solution is this :
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200) {
// use xmlhttp.responseXML;
}
}
}
xmlhttp.open("GET",dname,false);
xmlhttp.send();
The main difference is that you don't use the return of the loadXMLDoc function but ask it to do something after it has fetched the XML.
Another solution would be to force a synchronous request using jquery's ajax function
EDIT : I mark it as duplicate as it's a frequent question but I hope this specific answer will help you.

Categories