trying to get this to trigger when the page loads but it's not displaying anything when the page loads.
http://jsfiddle.net/3GLFA/1/
$( document ).ready( function loadData() {
var url = "https://docs.google.com/spreadsheet/pub?key=p_aHW5nOrj0VO2ZHTRRtqTQ&single=true&gid=0&range=A1&output=csv";
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
document.getElementById("display").innerHTML = xmlhttp.responseText;
alert(xmlhttp.responseText);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
{
});
HTML
<div id="display"></div>
Jquery's .ready() method takes an anonymous function as a parameter.
Just remove the name of your function and it will work.
$( document ).ready( function() {
var url = "https://docs.google.com/spreadsheet/pub?key=p_aHW5nOrj0VO2ZHTRRtqTQ&single=true&gid=0&range=A1&output=csv";
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
document.getElementById("display").innerHTML = xmlhttp.responseText;
alert(xmlhttp.responseText);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="display"></div>
You use the jQuery method to trigger your code on the DOMReady event. But the inner code is not jQuery.
I think you don't have jQuery in your code. Just add it in your html code :
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
Change $(document).ready to $(document).load
https://api.jquery.com/load-event/
`but it's not displaying anything when the page loads.`
I just checked that the response from the url is empty that's why nothing is displayed. Check this fiddle which shows in an alert box what the response is.
http://jsfiddle.net/3GLFA/259/
Related
I am trying to make a landing page with json. I am trying to have it so when someone clicks it goes to a page from the json file. So far I have this:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200)
{
var Link = JSON.parse(this.responseText);
document.getElementById("Link1").innerHTML = Link.title;
}
};
xmlhttp.open("GET", "link.json", true);
xmlhttp.send();
function click1(){
window.location.href = Link.link;
}
And when I click on it it gives me (from console):
(index):22 Uncaught ReferenceError: Link is not defined at click1 ((index):22) at HTMLAnchorElement.onclick ((index):8)
Assuming your JSON content has properties title and link, and that your click1 handler has been properly registered, you should be able to combine what you have into something like this:
function click1() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var Link = JSON.parse(this.responseText);
document.getElementById("Link1").innerHTML = Link.title;
window.location.href = Link.link;
}
};
xmlhttp.open("GET", "link.json", true);
xmlhttp.send();
}
Note that setting the innerHTML of an element before window.location.href = Link.link; is somewhat pointless because updating window.location will cause a new page to load.
I want to access the data returned by this link with a simple function: https://geoapi123.appspot.com/
If you click the link, the return looks like:
function geoip_country_code(){return"UK"}
function geoip_country_name(){return"United Kingdom"}
function geoip_city(){return"London"}
...
In particular, I'm looking for the geoip_city. I do not want to use AJAX or jQuery.
I need a simple function, which does nor require script tags or any references in the head. The data received needs to be stored in a variable, totally independent from the homepage or any events at the homepage. The function cannot be called by any onload or click events, or anything else happening with the homepage.
Here is a working example with head script tag (not what I want):
<head>
<script language="JavaScript" src="https://geoapi123.appspot.com/"></script>
</head>
<body>
<script language="JavaScript">
var city = geoip_city();
alert(city);
</script>
</body>
Here is an idea of what I want:
function getLocation() {
??? //access homepage somehow here
var city = geoip_city(); //get result
alert(city); //alert result
};
getLocation(); //call function
Here is my closest try so far (not working, the return is "0"):
function accessLocation() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
alert(xmlhttp.status);
}
};
xmlhttp.open("GET", "https://geoapi123.appspot.com", true);
xmlhttp.send();
};
accessLocation();
You can add a script element by code and loading the source from 'geoapi':
function clickHandler() {
var city = geoip_city();
alert(city);
}
function ready() {
var element = document.getElementById('cityFinder');
element.addEventListener('click', clickHandler, false);
}
function init() {
var script = document.createElement('script');
script.onload = function() {
ready();
};
script.src = "https://geoapi123.appspot.com/";
document.getElementsByTagName('head')[0].appendChild(script);
}
<body onload="init();">
<input type="button" id="cityFinder" value="Where am I?"></input>
</body>
i have a span with the same value..
echo "<span id='msgNotif1' class='badge' style='position:relative;right:5px;bottom:10px;'>".$number."</span>";
where $number have a value..
and my js code is..
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var val = xmlhttp.responseText;
//alert(val);
document.getElementById("msgNotif1").innerHTML = val;
//document.getElementById("msgNotif2").innerHTML = val;
alert(val);
//document.getElementById("msgNotif3").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "some page", true);
xmlhttp.send();
the problem is the value still remains and do not change,
trying to uncomment the first alert shows an alert with the right value, but when i try to comment it the second alert never executed, giving me an idea that the document.getelementbyid().innerhtml is the one that is not working, been with this for a few hours,
any help will be appreciated.
thanks in advance
Your error message Cannot set property 'innerHTML' of null" means that:
document.getElementById("msgNotif1")
is returning null. That can happen for several possible reasons:
There is no element in your page with id="msgNotif1".
You are calling this code before your document has finished loading and thus the element with id="msgNotif1" has not yet loaded. This can commonly happen if you execute your code in the <head> section of the document rather than at the very end of <body> or in response to the DOMContentLoaded event.
Your content is dynamically loaded (not in the original page HTML) and you are calling document.getElementById("msgNotif1") before your dynamic content has been loaded.
You have some HTML errors which are preventing the proper parsing of your HTML that contains the element with id="msgNotif1".
For a general purpose description of how to run Javascript after the current page has been loaded without using a framework like jQuery, see this answer: pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it
You are receiving this error in your console because it doesn't exist at the time your script is running. This can be caused if the element hasn't been loaded when your script is running, if your IDs aren't the same, or if the element doesn't exist in your html. If you are referencing the element before it loads, add a function that executes when your page loads.
You can use JQuery
$(document).ready(function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var val = xmlhttp.responseText;
//alert(val);
document.getElementById("msgNotif1").innerHTML = val;
//document.getElementById("msgNotif2").innerHTML = val;
alert(val);
//document.getElementById("msgNotif3").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "some page", true);
xmlhttp.send();
});
or with pure Javascript to create the event.
window.onload = function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var val = xmlhttp.responseText;
//alert(val);
document.getElementById("msgNotif1").innerHTML = val;
//document.getElementById("msgNotif2").innerHTML = val;
alert(val);
//document.getElementById("msgNotif3").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "some page", true);
xmlhttp.send();
};
Valid points have been brought up in that doing Ajax requests with pure Javascript takes much more code than if you were to use JQuery. This is the reason why I (and many others) use JQuery for all the Ajax requests performed. JQuery has many methods for Ajax that will save a lot of time and code and in the long run will reduce your file size by a few bytes since, with JQuery, the code is reused.
here is my html:
<html><body>
page starts here
this is a test page
top:
<script id="invoc_code" type="text/javascript">
window.onload = function() {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function() {
var body = document.body;
if (xhr.readyState == 4 && xhr.status == 200) {
if(body.firstChild){
body.insertBefore(xhr.response, body.firstChild);
} else {
body.appendChild(xhr.response);
}
}
};
xhr.open("GET", "http://google.com", true);
xhr.send();
};
</script>;
page ends here
</body></html>
line body.insertBefore(xhr.response, body.firstChild); results to "NotFoundError: An attempt was made to reference a Node in a context where it does not exist". Can you please tell me what is the reason?
Thanks in advance
The insertBefore method expects a DOM element as its first parameter. If the XHR response is a HTML string, then you need to create one using this. Depending on your required DOM output you could do something like this:
var newElem = document.createElement("div");
newElem.innerHTML = xhr.response;
body.insertBefore(newElem, body.firstChild);
I'm trying to have a div refresh after a callback using ajax functions. Basically, I want /includes/view_game/achievements.inc.php to be reloaded in the div #achievements_tab. The callback (I didn't include it in codes below) works well and triggers the AchievementRefresh function found below (the opacity of the div changes to 0.5, but it remains like this and the refresh is not made).
Those two functions are used for another similar ajax refresh on my site that works well. So I tried to modify the code, but since it's for a slightly different purpose, maybe I have the wrong approach.
function AjaxPost(url, success_function) {
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("Your browser doesn't support AJAX. You should upgrade it!")
return
}
xmlHttp.onreadystatechange = success_function;
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
This AjaxPost function is used in the other function below:
function AchievementRefresh() {
div('achievements_tab').style.opacity = 0.5;
div('highscore_pages').innerHTML = '<img src="'+site_url+'/images/loader.gif" />';
AjaxPost(site_url+"/includes/view_game/achievements.inc.php?", '',
function () {
div('achievements_tab').innerHTML = xmlHttp.responseText;
div('achievements_tab').style.opacity = 1;
}
)
}
Use load
$('#achievements_tab').load('/includes/view_game/achievements.inc.php');
See: http://api.jquery.com/load/
Edit
E.g.
function AchievementRefresh() {
$('#achievements_tab').css('opacity', 0.5);
$('#highscore_pages').html('<img src="'+site_url+'/images/loader.gif" />');
$('#achievements_tab').load('/includes/view_game/achievements.inc.php')
.success(function() {
$('#achievements_tab').css('opacity', 1);
});
}
Try this.
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
div('achievements_tab').innerHTML = xmlHttp.responseText;
div('achievements_tab').style.opacity = 1;
}
}
};`
Name and id is example.
Also, some changes:
AjaxPost(site_url+"/includes/view_game/achievements.inc.php");
var params= 'name'+encodeURIComponent(name)+'&id='+encodeURIComponent(id)
Parameters shouldn't be in URL.
xmlhttp.send(params);