JavaScript helps with conditional syntax - javascript

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()
}

Related

Simple XMLHttpRequest the response xhttp.responseText; don't work

this.responseText don't return the content of file. Can anyone help me with this problem? Thanks
Console.log don't return the content of file.
function loadMegaContent() {
var xhttp = new XMLHttpRequest();
var mesaj = "";
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
mesaj = this.responseText
console.log("-WorkGood-" + this.responseText);
document.getElementById("logTextWXY").innerHTML = mesaj;
} else if (this.status == 404) {
mesaj = "The log don't exist in path";
document.getElementById("logTextWXY").innerHTML = mesaj;
}
};
xhttp.open("GET", "/admin/installstatus/fileContent.txt", true);
xhttp.send();
console.log("--mesaj" + mesaj);
}
Error
// The message display by console is next:
<title>Session expired</title>
<meta http-equiv="refresh" content="0;url=/Portal"/>
</head><body><p>Session expired please relogin</p></body></html>
If you just want to get the content of a file asynchronously, use fetch like:
async function loadMegaContent(){
let response = await fetch("/admin/installstatus/fileContent.txt");
if(response.status==200){
let data = await response.text();
console.log("-WorkGood-" + data);
document.getElementById("logTextWXY").innerHTML = data;
}else if (response.status==404){
mesaj = "The log don't exist in path";
document.getElementById("logTextWXY").innerHTML = mesaj;
}
}

How to pass a string in url in Javascript?

I'm trying to make an application that accesses different sites inside of an iframe from a private JSON dns server.
I have completed the main code, but now I am trying to make it able to be accessed through the url. (Ex. https://thissite.info?url='test.json'&dnsserver='https://thissite.info')
I also want it to default to a value if the variable is not defined in the url. For this, I'm using the following code:
function setup(){
var dns = document.getElementById("dns");
var urlbar = document.getElementById("urlbar");
var frame = document.getElementById("viewport");
if (typeof url === "undefined") {
url = 'Welcome Page URL Here';
} else {
urlbar.value = url;
}
if (typeof dnsserver === "undefined") {
dnsserver = 'Default Server Here';
} else {
dns.value = dnsserver;
}
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
console.log(this.status)
if(this.readyState == 4 && this.status == 200){
var response = JSON.parse(this.responseText);
frame.src=response;
console.log("Request Completed with 200");
};
if(this.readyState == 4 && this.status == 404){
console.log("Website Not Found");
frame.src='404.html'
};
}
xmlhttp.open("GET",dnsserver + url + '.json', true);
xmlhttp.send();
console.log("Request Sent");
}
But even if I pass the vars in the URL, it doesn't accept it.
<script type="text/javascript"> $(function () { $("#btnQueryString").bind("click", function () { var url = "Page2.htm?name=" + encodeURIComponent($("#txtName").val()) + "&technology=" + encodeURIComponent($("#ddlTechnolgy").val()); window.location.href = url; }); }); </script> <input type="button" id="btnQueryString

API not responding

The app that I'm working on does not respond with the API address. I only get the ajax responding, but not the weather api that I'm trying to call.
I've tried everything that I could think of with my current knowledge.
let search = document.getElementById("search-bar");
let temp = document.getElementById("temperature");
let input = document.getElementById("input");
let city = document.getElementById("city");
const key = "";
input.addEventListener("keyup", enter);
function enter(event) {
if (event.key==="Enter") {
details();
}
}
function details() {
if (searchInput.value === ""){
} else {
let searchLink = "https://api.openweathermap.org/data/2.5/weather?q={}" + searchInput.value + "&appid=" + key;
httpRequestAsync(searchLink, talk)
}
}
function talk(talking){
let jsonObject = JSON.parse(talking);
city.innerHTML = jsonOject.name;
temp.innerHTML = parseInt(parseInt(jsonObject.main.temp - 273) + "°");
}
function httpRequestAsync(url,callback){
var httpRequest=new XMLHttpRequest();
httpRequest.onreadystatechange = () => {
if (httpRequest.readyState == 4 && httpRequest.status == 200)
callback(httpRequest.responseText);
}
request.open("GET", url, true); // true for asynchronous
request.send();
}
The expected outcome should be the weather api being called and displayed information in the console.
Try replacing last function with this:
function httpRequestAsync(url,callback){
var httpRequest=new XMLHttpRequest();
httpRequest.onreadystatechange = () => {
if (httpRequest.readyState == 4 && httpRequest.status == 200)
callback(httpRequest.responseText);
}
httpRequest.open("GET", url, true); // true for asynchronous
httpRequest.send();
}
I just corrected variable naming

Using Ajax/XMLhttprequest to send data to a php file with mail function

I have been following this tutorial (https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started) but I had no luck. I am trying to communicate with a php file with a javascript file using XMLhttpRequest. This is the code bellow. I still dont understand how to fully transfer the data across.
HTML
form id="uDF" method="post" onsubmit="submitValidation()">
JavaScript
function submitValidation(){
var data = [document.forms ["uDF"] ["uDFName"].value, document.forms ["uDF"] ["uDFNumber"].value,
document.forms ["uDF"] ["uDFEmail"].value, document.forms ["uDF"] ["uDFSubject"].value,
document.forms ["uDF"] ["uDFMessage"].value,]
console.log(data);
var char = ''; // variable used to check whether email has #
var x;
var isEmail = false;
var isNotEmpty = false;
//for loop checks email for # char
for(x = 0; x<data[2].length;x++)
{
char = data[2].charAt(x);
if(char === "#"){
isEmail = true;
break;
}
}
var i;
//for loop check if data is collected
for(i=0;i < 5;i++){
if(data[i] === ""){
isNotEmpty = false;
}else{
isNotEmpty = true;
}
}
if(isEmail === true && isNotEmpty === true)
{
var httpRequest;
httpRequest = new XMLHttpRequest();
if(!httpRequest){
return false;
}
httpRequest.onreadystatechange = function(){
if(httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200)
{
var response = JSON.parse(httpRequest.responseText);
}
httpRequest.open('POST', '../userData.mail.php')
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send('uDFName=' + encodeURIComponent(data[0]) + 'uDFNumber=' + encodeURIComponent(data[1]) + 'uDFNumber=' + encodeURIComponent(data[3])
+ 'uDFNumber=' + encodeURIComponent(data[4]))
}
}else if (!isNotEmpty){
alert("empty fields");
}else if(!isEmail){
alert("Please enter valid email!");
}
}
PHP
$uDFName = (isset($_POST['uDFName'])) ? $_POST['uDFName'] : '';
$uDFNumber = (isset($_POST['uDFNumber'])) ? $_POST['uDFNumber'] : '';
$uDFEmail = "my#email";
$uDFSubject = (isset($_POST['uDFSubject'])) ? $_POST['uDFSubject'] : '';
$uDFMessage = $uDFName . "\r\n" . $uDFNumber . "\r\n" . "just testing";
$message = wordwrap($message, 70, "\r\n");
mail($uDFEmail, $uDFSubject, $uDFMessage);
You have to open and send the request outside of the event handler function. The onreadystatechange handler only executes when the ready state of your request changes.
If you don't open and send the request, the handler function is not executed, and you won't see any results.
This solution should work:
var httpRequest = new XMLHttpRequest();
// this function executes whenever the ready state of the request changes
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
}
}
// open the request ...
httpRequest.open('POST', '../userData.mail.php')
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// ... and send it
httpRequest.send('uDFName=' + encodeURIComponent(data[0]) + 'uDFNumber=' + encodeURIComponent(data[1]) + 'uDFNumber=' + encodeURIComponent(data[3])
+ 'uDFNumber=' + encodeURIComponent(data[4]));

Loop Calling Function in Native Ajax

Here's my native ajax code:
function script_grabbed(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("numvalue").value = xmlhttp.responseText;
var result = document.getElementById("numvalue").value;
if (typeof result !== 'undefined'){
alert('Data Found:' + result);
//start: new request data for #valdata
xmlhttp.open("POST", "inc.php?q="+str, true);
document.getElementById("valdata").value = xmlhttp.responseText;
xmlhttp.send(null);
var dataval = document.getElementById("valdata").value;
if (typeof dataval !== 'undefined'){
alert('Data Bound:' + dataval);
//continue to call maps
script_dkill()
}
//end: new request data for #valdata
}
}
}
xmlhttp.open("POST", "inc_num.php?q="+str, true);
xmlhttp.send(null);
}
From the code, let me explain that:
I want to get data/value from result and dataval. After I get the data, I execute script_dkill() function.
However, It creates loop and never get to script_dkill.
So, the question is: How to get to script_dkill and execute it?
For example:
The script_dkill() has content as follow:
function script_dkill(){
alert('Hallo, you call me!');
}
Any help, please...
You need to use a different XMLHttpRequest object for the second request, since you are using the same object it will call the same onreadystatechange event again and again
function script_grabbed(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("numvalue").value = xmlhttp.responseText;
var result = document.getElementById("numvalue").value;
if (typeof result !== 'undefined') {
alert('Data Found:' + result);
//start: new request data for #valdata
var xmlhttp2 = new XMLHttpRequest();
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
document.getElementById("valdata").value = xmlhttp2.responseText;
var dataval = document.getElementById("valdata").value;
if (typeof dataval !== 'undefined') {
alert('Data Bound:' + dataval);
//continue to call maps
script_dkill()
}
}
}
xmlhttp2.open("POST", "inc.php?q=" + str, true);
xmlhttp2.send(null);
//end: new request data for #valdata
}
}
}
xmlhttp.open("POST", "inc_num.php?q=" + str, true);
xmlhttp.send(null);
}

Categories

Resources