onload variable initialization - javascript

I have a button which increments a variable value, and I use this variable to load specific content. My problem is that after the page has loaded, I have to click 3 times for the first content load:
1st time I click: I get an undefined result because no ID is loaded
2nd time: the input field value from before I reload the page disappears
3rd time: the first content finally loads
Once the first content has loaded everything works fine. From what I understood it is because the variable isn't initalized at page loading. So I added an onload event but it doesn't work at all.
the script :
var Pokemon_ID = 1
function changePokemon(Pokemon_ID) {
function resetID() {
document.getElementById("id-input").innerHTML = Pokemon_ID;
}
document.getElementById("right-btn").onclick = function() {
Pokemon_ID++;
document.getElementById("id-input").value = Pokemon_ID;
document.getElementById("id-input").click();
}
document.getElementById("left-btn").onclick = function() {
if (Pokemon_ID > 1) {
Pokemon_ID--;
}
document.getElementById("id-input").value = Pokemon_ID;
document.getElementById("id-input").click();
}
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { //IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var parts = xmlhttp.responseText.split('|')
document.getElementById("img").innerHTML = parts[0];
document.getElementById("name").innerHTML = parts[1];
document.getElementById("type-display1").innerHTML = parts[2];
document.getElementById("categorie").innerHTML = "Categorie: " + parts[3];
document.getElementById("talent").innerHTML = "Talent: " + parts[4];
document.getElementById("taille").innerHTML = "Taille: " + parts[5];
document.getElementById("poids").innerHTML = "Poids: " + parts[6];
}
}
xmlhttp.open("GET", "get_id.php?q=" + Pokemon_ID, true);
xmlhttp.send();
}
<div id="pokedex" onload="resetID()">
<a id="right-btn" onclick="changePokemon(this.value)"></a>
<a id="left-btn" onclick="changePokemon(this.value)"></a>
<form>
<input type="number" id="id-input" onclick="changePokemon(this.value)">
</form>
</div>
I also tried to declare my variable inside the changePokemon() function, but only the first id was loading I couldn't change the value of Pokemon_ID.
I tried to use const and let but both of them also didn't work

You use the same name Pokemon_ID for the global variable and the parameter to the changePokemon() function. The parameter is a local variable, so assignments to it don't affect the global variable. Give it a different name.
You need to take resetID() out of the changePokemon() function. It needs tobe in the global scope so it can be accessed from onclick.
To change an input, you need to assign to .value, not .innerHTML.
DIVs don't have a load event. You need to put onload="resetID()" in the <body> tag, or write:
window.onload = resetID;
in the Javascript.
var Pokemon_ID = 1
function resetID() {
document.getElementById("id-input").value = Pokemon_ID;
}
function changePokemon(Pokemon_val) {
document.getElementById("right-btn").onclick = function() {
Pokemon_ID++;
document.getElementById("id-input").value = Pokemon_ID;
document.getElementById("id-input").click();
}
document.getElementById("left-btn").onclick = function() {
if (Pokemon_ID > 1) {
Pokemon_ID--;
}
document.getElementById("id-input").value = Pokemon_ID;
document.getElementById("id-input").click();
}
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { //IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var parts = xmlhttp.responseText.split('|')
document.getElementById("img").innerHTML = parts[0];
document.getElementById("name").innerHTML = parts[1];
document.getElementById("type-display1").innerHTML = parts[2];
document.getElementById("categorie").innerHTML = "Categorie: " + parts[3];
document.getElementById("talent").innerHTML = "Talent: " + parts[4];
document.getElementById("taille").innerHTML = "Taille: " + parts[5];
document.getElementById("poids").innerHTML = "Poids: " + parts[6];
}
}
xmlhttp.open("GET", "get_id.php?q=" + Pokemon_val, true);
xmlhttp.send();
}
<div id="pokedex" onload="resetID()">
<a id="right-btn" onclick="changePokemon(this.value)"></a>
<a id="left-btn" onclick="changePokemon(this.value)"></a>
<form>
<input type="number" id="id-input" onclick="changePokemon(this.value)">
</form>
</div>

Related

How to get id variable into ajax

js
function SearchInList(_id,_url,_place){
this.id = _id;
this.url = _url;
this.place = _place; /*How to get this value */
};
SearchInList.prototype.FindMe = function (_str){
this.str = _str;
if (this.str == "") {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var place = this.place;
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("lista-ind").innerHTML = this.responseText; /*in this place */
}
};
xmlhttp.open("GET",this.url+"?id="+this.id,true);
xmlhttp.send();
} else {
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("lista-ind").innerHTML = this.responseText;
}
};
xmlhttp.open("GET",this.url+"?id="+this.id+"&hint="+this.str,true);
xmlhttp.send();
}
};
in HTML I have
<input type="text" placeholder="Search" id="search-ind" ></div>
<div id="lista-ind" class="lista"></div>
<script>
var id = <?php echo $_GET['id']; ?>;
var url = "showresults.php";
var place = "lista-ind";
var searchInd = new SearchInList(id, url);
var searchboxInd = document.getElementById("search-ind");
window.onload = searchboxInd.addEventListener("keyup", function(){
searchInd.FindMe(searchboxInd.value,place);
console.log(searchboxInd.value);
}, false);
window.onload = searchInd.FindMe("",place);
</script>
and when i have in function in onreadystatechange " document.getElementById("lista-ind")" it is working, but when I change to
document.getElementById(this.place) it is not.
how to pass this variable into that function?
this is how i made searching in lists.
thanks.
M.
If place is a global variable, outside the function, you not need this; just the variable name.
document.getElementById(place)
You're instantiating SearchInList without a place and FindMe does not take place as a parameter, so there is no way to get place to use in the object.
The easiest solution would be to add place as a parameter to FindMe
SearchInList.prototype.FindMe = function (_str, _place){
this.str = _str;
this.place = _place;
...

javascript from ajax doesn't get proper execution

Using Ajax, I've created a sort of console that allows me to execute some PHP functions dynamically.
It looks like this
The problem is that after a bunch of commands, the console becomes hard to read. So I've created a javascript function, named "wipe();", which clears the <div> containing the console.
I tested this function with the developpers tools of chrome (the javascript console) and it works perfectly.
But when I try to call this function by making the PHP-AJAX return a "<script>wipe();</script>", it doesn't work. It does nothing.
I've read on the internet that all the "<script></script>" works independently from each other, but that you can call a <script>function</script> from another <script></script> block.
So why is it failing to do that ?
here is the php code :
echo '<script>wipe();</script>';
and here is the the first <script> block:
var xmlhttp = new XMLHttpRequest();
var span = document.getElementById("screen");
function send(data) {
window.setInterval(function() {
var elem = document.getElementById('screen');
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "./_rcons-transmetter.php?data="+data, true)
xmlhttp.onloadend = function() {
span.innerHTML = span.innerHTML+escapeHtml(data)+'<br>'+xmlhttp.responseText+'<br><br>';
}
xmlhttp.send();
}
function wipe(){
span.innerHTML = '';
}
To avoid security issues ( like a cross-site scripting attack) HTML5 specifies that a <script> tag inserted via innerHTML should not execute.
A way to execute the script is to evaluate the html using eval() . Be warned: using eval can be dangerous.
var xmlhttp = new XMLHttpRequest();
var span = document.getElementById("screen");
function send(data) {
window.setInterval(function() {
var elem = document.getElementById('screen');
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "./_rcons-transmetter.php?data=" + data, true)
xmlhttp.onloadend = function() {
span.innerHTML = span.innerHTML + escapeHtml(data) + '<br>' + xmlhttp.responseText + '<br><br>';
evalJSFromHtml(span.innerHTML);
}
xmlhttp.send();
}
function wipe() {
span.innerHTML = '';
}
function evalJSFromHtml(html) {
var newElement = document.createElement('div');
newElement.innerHTML = html;
var scripts = newElement.getElementsByTagName("script");
for (var i = 0; i < scripts.length; ++i) {
var script = scripts[i];
eval(script.innerHTML);
}
}
}
Call the 'wipe' function as a callback function directly from the 'send' function. Check status = 200 for a success response.
var xmlhttp = new XMLHttpRequest();
var span = document.getElementById("screen");
function send(data) {
window.setInterval(function() {
var elem = document.getElementById('screen');
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "./_rcons-transmetter.php?data="+data, true)
xmlhttp.onloadend = function() {
span.innerHTML = span.innerHTML+escapeHtml(data)+'<br>'+xmlhttp.responseText+'<br><br>';
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
wipe(); // 'Wipe' callback function
}
}
xmlhttp.send();
}
function wipe(){
span.innerHTML = '';
}
But when I try to call this function by making the PHP-AJAX return a "wipe();", it doesn't work. It does nothing.
try create script tag and add to document rather than change inner html.
var spaScript = document.getElementById("spaScript");
var wraper = document.createElement("div");
wraper.innerHTML = xmlhttp.responseText;
var script = document.createElement("script");
script.innerHTML = wraper.getElementsByTagName("script")[0].innerHTML;
spaScript.appendChild(script);
Test if wipe() is in the input and if it is trigger it instead of the ajax call
var xmlhttp = new XMLHttpRequest();
var span = document.getElementById("screen");
function send(data) {
if (data.indexOf('wipe()') == -1) {
window.setInterval(function() {
var elem = document.getElementById('screen');
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "./_rcons-transmetter.php?data=" + data, true)
xmlhttp.onloadend = function() {
span.innerHTML = span.innerHTML + escapeHtml(data) + '<br>' + xmlhttp.responseText + '<br><br>';
}
xmlhttp.send();
}
} else {
wipe();
};
}
function wipe() {
span.innerHTML = '';
}
inserting a script tag directly inside an element should not work (and by the way generating an error in the console).
Using the native eval() function on the response text without speciying the tag attribute should solve the problem.
on server side
echo 'wipe()';
on client side
eval(xmlhttp.responseText)

Only one JavaScript function loading on page load.

I have a webpage with a few JavaScript functions set to load on document.ready.
However, if I have 4 of these, only the final one seems to load.
Here is the code I have.
$(document).ready(function ()
{
var nation = "ireland";
var irelandMatches = [];
var matchOrderReversed = false;
loadDoc();
showRSS("Irish Times");
loadWeather();
loadTwitter();
The loadDoc() and loadTwitter() methods load, but weather and showRSS do not. If I comment out loadTwitter(), then the weather loads fine.
If it makes any difference, all of these methods make use of an XMLHttpRequest, each of which is defined within each method, like so.
function loadYouTube()
{
var html = "";
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)
{
var ret = xmlhttp.responseText;
var spl1 = ret.split("~");
for (i = 0; i <= 10; i++)
{
var spl2 = spl1[i].split("*");
var current = "<a href='" + spl2[1] + "'><img src='" + spl2[2] + "' width='50' height='50'>" + "<a href='" + spl2[1] + "'>" + spl2[0] + "</a> <br/>";
html += current;
}
$("#yt").html(html);
}
}
xmlhttp.open("GET", "getyoutube.php?", true);
xmlhttp.send();
}
Thanks guys :)
It looks like when you define xmlhttp in your loadYouTube() example, you are doing so on the global scope due to the lack of var. So loadDoc() sets window.xmlhttp, then loadWeather() overwrites it shortly after, followed by loadTwitter().
Try something like this in your loading functions:
function loadYouTube()
{
var html = "";
// define xmlhttp in block scope
var xmlhttp;
// rest of function...
}

Javascript interfering with each other

As I know very little about Javascript and Jquery I am hoping to be able to get an answer here.
Here is the code in my <head></head> of my document.
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/functions.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jscolor/jscolor.js"></script>
<script type="text/javascript">
var current_shouts = 0;
function $(eleid) {
return document.getElementById(eleid);
}
function urlencode(u) {
u = u.toString();
var matches = u.match(/[\x90-\xFF]/g);
if (matches) {
for (var mid = 0; mid < matches.length; mid++) {
var char_code = matches[mid].charCodeAt(0);
u = u.replace(matches[mid], '%u00' + (char_code & 0xFF).toString(16).toUpperCase());
}
}
return escape(u).replace(/\+/g, "%2B");
}
function shouts() {
clearTimeout(getshout);
var xmlHttp = (window.XMLHttpRequest) ? new XMLHttpRequest : new ActiveXObject("Microsoft.XMLHTTP");
xmlHttp.open("GET", "../shoutbox/shouts.php?i=" + Math.random());
xmlHttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (parseInt(this.responseText) > current_shouts) {
getshouts();
current_shouts = parseInt(this.responseText);
}
getshout = setTimeout("shouts()", 1000);
}
}
xmlHttp.send(null);
}
function getshouts() {
var xmlHttp = (window.XMLHttpRequest) ? new XMLHttpRequest : new ActiveXObject("Microsoft.XMLHTTP");
xmlHttp.open("GET", "../shoutbox/getshouts.php?i=" + Math.random());
xmlHttp.onreadystatechange = function() {
if (this.readyState == 4) $("shoutbox").innerHTML = this.responseText;
$("shoutbox").scrollTop = $("shoutbox").scrollHeight;
}
xmlHttp.send(null);
}
function push_shout() {
shout();
return false;
}
function shout() {
var xmlHttp = (window.XMLHttpRequest) ? new XMLHttpRequest : new ActiveXObject("Microsoft.XMLHTTP");
xmlHttp.open("POST", "../shoutbox/shout.php");
var data = "user=" + urlencode($("user").value) + "&" + "shout=" + urlencode($("shout").value);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", data.length);
xmlHttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (!this.responseText) $("shout").value = "";
else {
$("console").innerHTML = this.responseText;
setTimeout("$('console').innerHTML = ''", 5000);
}
getshouts();
}
}
xmlHttp.send(data);
return true;
}
var getshout = setTimeout("shouts()", 1000);
</script>
It seems when I put the typed code above everything, it does not work, but the others do, if the code sits as it is shown above it works, but the scripts above it do not work anymore.
I have tried $.noConflict(); but it seems it did nothing, so I am not sure what I am to do here.
Any suggestions?
try something like:
$j = jQuery.noConflict();
then you can use $j to refer to the jQuery object whenever you need to.
I had a problem with jQuery plugins clashing somehow.
I loaded both into the head of the html document, between consecutive separated script tag zones. Then I used:
window.onload = function() {function01(); function02();};
to load each function in an orderly fashion and separately.
It worked for me this time.

Parsing or using variables from a called script?

I have an AJAX function which loads content from a file and displays in the file that called it.
But the script that was called I want to loop an array which is actually set in the script that called it... this is main script that calls the file:
function call_file(file, div_id) {
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(div_id).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", file, true);
xmlhttp.send();
}
var global = new Array();
global[0] = 1;
global[1] = 2;
call_script('html.html', 'main');
html.html is the file that is called which has this:
<script>
i = 0;
for(var id in global) {
alert(i + ' = ' + id);
i++;
}
</script>
Is this at all possible?
One way is to extract the script and eval it yourself. For example:
//....
document.getElementById(div_id).innerHTML = xmlhttp.responseText;
var str = xmlhttp.responseText;
var reg = /<script>([^>]*)<\/script>/img;
while(reg.test(str))eval(RegExp.$1);
//...

Categories