how to fix javascript refresh error on google chrome - javascript

I have an error which is giving me a hard time to fix. I have written a program in JavaScript but when I refresh it doesn't affect the page. I even closed and opened the browser more than once but it didn't work, please does anyone have a solution to it?
This is some part of the code
var person = document.getElementById('formant');
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var email = document.getElementById('email').value;
var num = document.getElementById('num').value;
var pass = document.getElementById('pass').value;
var conpass = document.getElementById('conpass').value;
var gen ='';
function setgen(f)
{
gen = document.getElementById(f).value;
}
person.addEventListener('submit', red);
function red(m)
{
m.preventDefault();
var xhr = new XMLHttpRequest();
// var response = document.getElementById().innerHTML;
xhr.open('POST','php/signupajax.php',true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function()
{
if(this.status == 200)
{
if(document.getElementById('pass').value.lenght < 0)
{
alert('less man');
}
console.log(this.responseText);
}
}
xhr.send('fname=' + document.getElementById('fname').value + '&lname=' + document.getElementById('lname').value + '&email=' + document.getElementById('email').value + '&num=' +document.getElementById('num').value+ '&pass=' + document.getElementById('pass').value + '&conpass=' +document.getElementById('conpass').value + '&gen=' + gen);
}
if(document.getElementById('pass').value <6)
{
alert('password not strong');
}
else{
alert('password good');
}

Related

JavaScript helps with conditional syntax

I have a function that calls an API (let's call it API-1) to get the song lyrics.
Since this API sometimes can't find a song in its database, I want to call another API (let's call it API-2) to do the same search.
I need to integrate the code of both APIs inside the function, when the first one doesn't get data.
I tell you some very important information:
In API-1 I must force the data to be fetched as XML and the responseType must be 'document'.
API-2 does not require any of the above conditions, the data is parced as JSON and the responseType it supports is 'text', but does not require it to be set, with 'document' it DOES NOT work, it gives error.
Now I will share the function code for API-1 and then I will share the same function code for API-2.
They both work perfect if I test them independently.
The help I am asking for is to integrate API-2 when API-1 does not fetch data.
Code using API-1
this.refreshLyric = function (currentSong, currentArtist) {
var xhr = new XMLHttpRequest;
xhr.open('GET', proxy_URL + api_URL + 'apiv1.asmx/SearchLyricDirect?artist=' + currentArtistE + '&song=' + ucwords(currentSongE), true);
// ONLY FOR THIS XMLHttpRequest responseType must be empty string or 'document'
xhr.responseType = 'document';
// ONLY FOR THIS XMLHttpRequest force the response to be parsed as XML
xhr.overrideMimeType('text/xml');
xhr.onload = function () {
if (xhr.readyState === xhr.DONE && xhr.status === 200) {
var openLyric = document.getElementsByClassName('lyrics')[0];
var lyric = xhr.responseXML.getElementsByTagName('Lyric')[0].innerHTML;
//check if any data was obtained
if (lyric != '') {
document.getElementById('lyric').innerHTML = lyric.replace(/\n/g, '<br />');
openLyric.style.opacity = "1";
openLyric.setAttribute('data-toggle', 'modal');
} else { /////// HERE INTEGRATE API-2 //////
openLyric.style.opacity = "0.3";
openLyric.removeAttribute('data-toggle');
var modalLyric = document.getElementById('modalLyrics');
modalLyric.style.display = "none";
modalLyric.setAttribute('aria-hidden', 'true');
(document.getElementsByClassName('modal-backdrop')[0]) ? document.getElementsByClassName('modal-backdrop')[0].remove(): '';
}
} else {
document.getElementsByClassName('lyrics')[0].style.opacity = "0.3";
document.getElementsByClassName('lyrics')[0].removeAttribute('data-toggle');
}
};
xhr.send();
}
The same code using API-2
this.refreshLyric = function (currentSong, currentArtist) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
var data = JSON.parse(this.responseText);
var openLyric = document.getElementsByClassName('lyrics')[0];
var lyric = data.mus[0].text;
//check if any data was obtained
if (lyric != '') {
document.getElementById('lyric').innerHTML = lyric.replace(/\n/g, '<br />');
openLyric.style.opacity = "1";
openLyric.setAttribute('data-toggle', 'modal');
} else {
openLyric.style.opacity = "0.3";
openLyric.removeAttribute('data-toggle');
var modalLyric = document.getElementById('modalLyrics');
modalLyric.style.display = "none";
modalLyric.setAttribute('aria-hidden', 'true');
(document.getElementsByClassName('modal-backdrop')[0]) ? document.getElementsByClassName('modal-backdrop')[0].remove(): '';
}
} else {
document.getElementsByClassName('lyrics')[0].style.opacity = "0.3";
document.getElementsByClassName('lyrics')[0].removeAttribute('data-toggle');
}
}
xhttp.open('GET', 'https://api.vagalume.com.br/search.php?apikey=' + API_KEY + '&art=' + currentArtist + '&mus=' + currentSong.toLowerCase(), true);
xhttp.send()
}
The shared codes are of the SAME function (this.refreshLyric), what has to be integrated is only the XMLHttpRequest API.
In the ELSE of line 23 of API-1 I must integrate the code of API-2.
I have already tried it in several ways but I am presented with syntax problems with the IF - ELSE conditionals and errors with the API-2 which is getting the responseType and the MimeType of API-1.
EDIT
FIXED: When API-1 cannot find the lyric, I have created a new function that calls API-2. refreshLyric2(currentSong, currentArtist); :)
this.refreshLyric = function (currentSong, currentArtist) {
var xhr = new XMLHttpRequest;
xhr.open('GET', proxy_URL + api_URL + 'apiv1.asmx/SearchLyricDirect?artist=' + currentArtistE + '&song=' + ucwords(currentSongE), true);
// ONLY FOR THIS XMLHttpRequest responseType must be empty string or 'document'
xhr.responseType = 'document';
// ONLY FOR THIS XMLHttpRequest force the response to be parsed as XML
xhr.overrideMimeType('text/xml');
xhr.onload = function () {
if (xhr.readyState === xhr.DONE && xhr.status === 200) {
var openLyric = document.getElementsByClassName('lyrics')[0];
var lyric = xhr.responseXML.getElementsByTagName('Lyric')[0].innerHTML;
//check if any data was obtained
if (lyric != '') {
document.getElementById('lyric').innerHTML = lyric.replace(/\n/g, '<br />');
openLyric.style.opacity = "1";
openLyric.setAttribute('data-toggle', 'modal');
} else {
//If lyric was not obtained, we call API-2
refreshLyric2(currentSong, currentArtist);
}
} else {
document.getElementsByClassName('lyrics')[0].style.opacity = "0.3";
document.getElementsByClassName('lyrics')[0].removeAttribute('data-toggle');
}
};
xhr.send();
}
refreshLyric2 = function (currentSong, currentArtist) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
var data = JSON.parse(this.responseText);
var openLyric = document.getElementsByClassName('lyrics')[0];
var lyric = data.mus[0].text;
//check if any data was obtained
if (lyric != '') {
document.getElementById('lyric').innerHTML = lyric.replace(/\n/g, '<br />');
openLyric.style.opacity = "1";
openLyric.setAttribute('data-toggle', 'modal');
} else {
openLyric.style.opacity = "0.3";
openLyric.removeAttribute('data-toggle');
var modalLyric = document.getElementById('modalLyrics');
modalLyric.style.display = "none";
modalLyric.setAttribute('aria-hidden', 'true');
(document.getElementsByClassName('modal-backdrop')[0]) ? document.getElementsByClassName('modal-backdrop')[0].remove(): '';
}
} else {
document.getElementsByClassName('lyrics')[0].style.opacity = "0.3";
document.getElementsByClassName('lyrics')[0].removeAttribute('data-toggle');
}
}
xhttp.open('GET', 'https://api.vagalume.com.br/search.php?apikey=' + API_KEY + '&art=' + currentArtist + '&mus=' + currentSong.toLowerCase(), true);
xhttp.send()
}

show next/previous items of an array

I am using next/previous buttons to show the corresponding items of an array. I am experiencing two issues...
1) when the page loads, I need to click previous or next two times before anything will happen
2) Let's say I'm at record ID 10 for example. If I press 'next' 5 times to get to record ID 15, then press 'previous', instead of taking me to 14, it will take me to ID 16. If I then hit previous again (and subsequent times), the ID will then decrease as normal. Same thing with previous: If I start at ID 15 and hit previous down to 10, clicking 'next' will take me to ID 9 instead of 11. Then, subsequent clicks of 'next' will increase the ID as normal.
Hopefully this will help explain what I mean...
https://jsfiddle.net/mjcs351L/
This uses a super hero API. You will need your own to test the code but it's free and doesn't even ask you to sign up: https://www.superheroapi.com/
Thanks in advance for any guidance.
var apiKey = "YOUR API";
var charID = Math.floor((Math.random() * 731) + 1);
var website = "https://www.superheroapi.com/api.php/" + apiKey + "/" + charID;
var req = new XMLHttpRequest();
req.open('GET', website, true);
req.setRequestHeader('Content-Type', 'application/json');
req.addEventListener('load', function() {
var result = JSON.parse(req.responseText);
getinfo();
function getinfo() {
document.getElementById('fullname').innerHTML = result.biography["full-name"];
document.getElementById('name').innerHTML = result.name;
document.getElementById('egos').innerHTML = result.biography["alter-egos"];
document.getElementById('charID').innerHTML = result.id;
document.getElementById('birth').innerHTML = result.biography["place-of-birth"];
document.getElementById('height').innerHTML = result.appearance.height;
document.getElementById('weight').innerHTML = result.appearance.weight;
document.getElementById('gender').innerHTML = result.appearance.gender;
document.getElementById('race').innerHTML = result.appearance.race;
document.getElementById('eye').innerHTML = result.appearance["eye-color"];
document.getElementById('hair').innerHTML = result.appearance["hair-color"];
document.getElementById('occupation').innerHTML = result.work.occupation;
document.getElementById('connections').innerHTML = result.connections["group-affiliation"];
document.getElementById('relatives').innerHTML = result.connections.relatives;
document.getElementById("pic").src = result.image.url;
document.getElementById("pic").style.height = 300;
document.getElementById("pic").style.width = 300;
}
function nextItem() {
var test = charID + 1;
var website = "https://www.superheroapi.com/api.php/" + apiKey + "/" + test;
req.open('GET', website, true);
req.setRequestHeader('Content-Type', 'application/json');
req.addEventListener('load', function() {
var result = JSON.parse(req.responseText);
charID = test;
getinfo();
});
req.send(null);
}
function prevItem() {
var test = charID - 1;
var website = "https://www.superheroapi.com/api.php/" + apiKey + "/" + test;
req.open('GET', website, true);
req.setRequestHeader('Content-Type', 'application/json');
req.addEventListener('load', function() {
var result = JSON.parse(req.responseText);
charID = test;
getinfo();
});
req.send(null);
}
document.getElementById('prev_button').addEventListener('click', function(e) {
prevItem();
});
document.getElementById('next_button').addEventListener('click', function(e) {
nextItem();
});
event.preventDefault();
});
req.send(null);
You should try and follow DRY (don't repeat yourself), it makes it easier to debug code. I've tweaked the code a bit to re-use components.
var apiKey = "YOUR API";
var charID = Math.floor((Math.random() * 731) + 1);
function fetchData(id) {
id = id || charID;
var website = "https://www.superheroapi.com/api.php/" + apiKey + "/" + id;
var req = new XMLHttpRequest();
req.open('GET', website, true);
req.setRequestHeader('Content-Type', 'application/json');
req.addEventListener('load', function() {
var result = JSON.parse(req.responseText);
getinfo(result);
});
req.send(null);
}
fetchData()
function getinfo(result) {
document.getElementById('fullname').innerHTML = result.biography["full-name"];
document.getElementById('name').innerHTML = result.name;
document.getElementById('egos').innerHTML = result.biography["alter-egos"];
document.getElementById('charID').innerHTML = result.id;
document.getElementById('birth').innerHTML = result.biography["place-of-birth"];
document.getElementById('height').innerHTML = result.appearance.height;
document.getElementById('weight').innerHTML = result.appearance.weight;
document.getElementById('gender').innerHTML = result.appearance.gender;
document.getElementById('race').innerHTML = result.appearance.race;
document.getElementById('eye').innerHTML = result.appearance["eye-color"];
document.getElementById('hair').innerHTML = result.appearance["hair-color"];
document.getElementById('occupation').innerHTML = result.work.occupation;
document.getElementById('connections').innerHTML = result.connections["group-affiliation"];
document.getElementById('relatives').innerHTML = result.connections.relatives;
document.getElementById("pic").src = result.image.url;
document.getElementById("pic").style.height = 300;
document.getElementById("pic").style.width = 300;
}
function nextItem(ev) {
ev.preventDefault();
fetchData(++charID)
}
function prevItem(ev) {
ev.preventDefault();
fetchData(--charID)
}
document.getElementById('prev_button').addEventListener('click', prevItem);
document.getElementById('next_button').addEventListener('click', nextItem);

onreadystatechange func. not working

i have written following ajax code but the onreadystatechange func. is not working within the chkPwd script func....only alert box with hiii 1 is shown on browser
function chkPwrd(){
var fname = document.getElementById("fname").value;
var lname= document.getElementById("lname").value;
var umail= document.getElementById("umail1").value;
var upass= document.getElementById("upass").value;
var xhr=new XMLHttpRequest();
if( flag === 1)
{
xhr.open("POST","conCheck?umail="+umail);
xhr.send(null);
alert("HIIII 1");
xhr.onreadystatechange=function()
{alert("HIIII 2");
if(xhr.readyState===4 & xhr.status===200)
{alert("HIIII 3");
var a=xhr.responseText;
if(a.indexOf('5')!==-1)
{alert("Emailid already Exists");
document.getElementById('umail1').style.color="red";
// document.getElementById('umail1').innerHTML="Emailid already Exists";
}
if(a.length===0)
{alert("Registering you..please click OK");
var char="register.jsp?fname="+fname+"&lname="+lname+"&umail="+umail+"&upass="+upass;
window.open(char,"_self");
}}
};}};
You called send before declaring onreadystatechange, that's why it doesn't work :
function chkPwrd() {
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var umail = document.getElementById("umail1").value;
var upass = document.getElementById("upass").value;
var xhr = new XMLHttpRequest();
if (flag === 1) {
xhr.open("POST", "conCheck?umail=" + umail);
alert("HIIII 1");
xhr.onreadystatechange = function() {
alert("HIIII 2");
if (xhr.readyState === 4 & xhr.status === 200) {
alert("HIIII 3");
var a = xhr.responseText;
if (a.indexOf('5') !== -1) {
alert("Emailid already Exists");
document.getElementById('umail1').style.color = "red";
// document.getElementById('umail1').innerHTML="Emailid already Exists";
}
if (a.length === 0) {
alert("Registering you..please click OK");
var char = "register.jsp?fname=" + fname + "&lname=" + lname + "&umail=" + umail + "&upass=" + upass;
window.open(char, "_self");
}
}
};
xhr.send(null);
}
};

Run Javascript script from ajax response

I want to call a JS Script in Ajax response. What it does is pass the document.getElementById script to the Ajax responseText.
The current code returns me this error: Uncaught TypeError: Cannot set property 'innerHTML' of null
This is done with Visual Studio Cordova..
Ajax:
$("#loginBtn").click(function() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.write(this.responseText);
}
}
xmlhttp.open("POST", "http://www.sampleee.esy.es/login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username=" + username + "&" + "password=" + password);
});
PHP:
if($count == 1){
echo "document.getElementById('alertBox').innerHTML = 'Login Success!';
document.getElementById('alertBox').className = 'alert alert-success';
document.getElementById('alertBox').style.display = 'block';
setTimeout(function () {
window.location.href = '../html/dashboard.html';
}, 1000);
";
}else{
echo "document.getElementById('alertBox').innerHTML = 'Invalid login details';
document.getElementById('alertBox').className = 'alert alert-danger';
document.getElementById('alertBox').style.display = 'block';
";
}
You can solve it by a small change, you just have to write JS code in the AJAX success that you wrote in your PHP page. In the PHP page, there is no alertBox element, that's why the error occurred.
Your JS code will be like this:
$("#loginBtn").click(function() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
if(this.responseText=="success"){
document.getElementById('alertBox').innerHTML = 'Login Success!';
document.getElementById('alertBox').className = 'alert alert-success';
document.getElementById('alertBox').style.display = 'block';
setTimeout(function () {
window.location.href = '../html/dashboard.html';
}, 1000);
}elseif(this.responseText=="error"){
document.getElementById('alertBox').innerHTML = 'Invalid login details';
document.getElementById('alertBox').className = 'alert alert-danger';
document.getElementById('alertBox').style.display = 'block'
}
}
}
xmlhttp.open("POST", "http://www.sampleee.esy.es/login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username=" + username + "&" + "password=" + password);
});
And PHP code like:
if($count == 1){
echo "success";
}else{
echo "error";
}
Basically you get that error because the thing you're trying to change is not on the page when you look for it.
What you need to do is, do not write javascript with PHP. You return something like an int from php and then use that to decide what the javascript does.
You have the html on the page and just change the content inside it.
$("#loginBtn").click(function() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var str = this.responseText; //you may need to trim whitespace
var alert = document.getElementById('alertBox');
if (str.trim() == 1) {
alert.innerHTML = 'Login Success!';
alert.className = 'alert alert-success';
alert.style.display = 'block';
setTimeout(function() {
window.location.href = '../html/dashboard.html';
}, 1000);
}
else {
alert.innerHTML = 'Invalid login details';
alert.className = 'alert alert-danger';
alert.style.display = 'block';
}
}
xmlhttp.open("POST", "http://www.sampleee.esy.es/login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username=" + username + "&" + "password=" + password);
});
<div id="alertbox"></div>
PHP Code:
if($count == 1){
echo 1;
}
else{
echo 0;
}
Use eval like below
$("#loginBtn").click(function() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var fun = eval(this.responseText);
}
}
xmlhttp.open("POST", "http://www.sampleee.esy.es/login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username=" + username + "&" + "password=" + password);
});

external function not called - javascript

can anyone tell me why this is not working?
ui = (function() {
collabElement = document.getElementById( 'approveCollab' );
if(collabElement)
collabElement.onclick = function(){editor.collaborate(); removeOverlay();}
deleteElement = document.getElementById( 'approveDelete' );
if(deleteElement)
deleteElement.onclick = function(){editor.deletePost(); removeOverlay();}
})();
"collaborate" is an exported function in "editor.js" file.
removeOverlay()" is a function in the same file.
when "collabElement" is clicked only "removeOverlay" is being called.
there are no errors, just that the function is not called at all.
these are the function being called from editor.js:
function collaborate( event ) {
console.log("started");
var url = '';
var postID = document.querySelector('.save').getAttribute('id');
var recipient = document.querySelector('.collab-input').value;
//validate email syntax
var atpos=recipient.indexOf("#");
var dotpos=recipient.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length){
console.log("wrong email");
document.querySelector('.email-error').style.display = "block";
}
else{
console.log("sending email to " + recipient);
document.querySelector('.email-error').style.display = "none";
if(postID != "new"){
url = url + "?id=" + postID + "&recipient=" + recipient;
var request = new XMLHttpRequest();
request.open("GET", "collaborate"+url, true);
request.send();
}
}
}
function deletePost( event ) {
var url = '';
var postID = document.querySelector('.save').getAttribute('id');
if(postID != "new"){
url = url + "?id=" + postID;
var request = new XMLHttpRequest();
request.open("GET", "delete"+url, true);
request.send();
}
}
If you want to call a function add () to it.
editor.collaborate()
(instead of editor.collaborate, which will just only address the function)
I suspect the problem is that your IIFE is not returning anything; ui will always be undefined. I think you want this:
ui = (function() {
collabElement = document.getElementById( 'approveCollab' );
if(collabElement)
collabElement.onclick = function(){editor.collaborate; removeOverlay();}
//return collabElement so it's assigned to ui
return collabElement;
})();
EDIT
While it's true your IIFE does not return anything, it looks like Peter's answer is more relevent to you at the moment; collaborate is not being called. His appears to be the right answer to this question.

Categories

Resources