How to pass a string in url in Javascript? - 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

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;
}
}

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

Ajax doesn't fire onreadystatechange

I know the URL is working as intended as i logged that to the console and it is fine. However I can't get "Good News" to log to the console when readyState == 4 and status == 200. I tried removing readState and it still wouldn't log. I tried logging the status and It would only fire once with a value of 0. This is the first time I am working with Ajax so any help is appreciated.
function setupRequest(){
var bttn = document.querySelector('#send');
bttn.addEventListener('click', sendData)
}
setupRequest();
function sendData () {
console.log('ran')
var url = 'localhost/bev/drinks.php';
var data = document.getElementById('input').value;
url += '?' + 'alcohol=' + data;
console.log(url)
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log('good news')
console.log(this.responseText)
} else {
console.log(this.status)
}
}
request.open('GET', url, true);
request.send;
console.log('sent')
}
You need to actually call send(). You aren't doing anything whenever you say request.send;
function setupRequest() {
var bttn = document.querySelector('#send');
bttn.addEventListener('click', sendData)
}
setupRequest();
function sendData() {
console.log('ran')
var url = 'https://jsonplaceholder.typicode.com/posts';
var data = document.getElementById('input').value;
//url += '?' + 'alcohol=' + data;
console.log(url)
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log('good news')
console.log(this.responseText)
} else {
console.log(this.status)
}
}
request.open('GET', url, true);
// You wrote (without parentheses):
///////////////////
// request.send; //
///////////////////
// You need to write
request.send();
console.log('sent')
}
<button type="button" id="send">Btn</button>
<input type="text" id="input">

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

jquery to javascript converted but not working

my initial code was in jquery + ajax and i tried to write it in javascript but its not working now. Can anyone tell me where's the mistake and why its not showing anything when i run through the server? i checked in the console and there is no error either
my code in JQ
$(document).ready(function(){
findteacher = function() {
var file = "course.php?course="+ $("#course").val();
$.ajax({
type : "GET",
url : file,
datatype : "text",
success : function(response) {
var file2 = response.split(",");
$("#courseInfo").html("The course: " + file2[0] + " Taught by: " + file2[1]);
}
});
}
clear = function() {
$("#courseInfo").html("");
};
$("#course").click(clear);
$("#go").click(findteacher);
});
My code in JS
function findteacher () {
var file = "course.php" + document.getElementById('course');
function callAjax(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById('courseInfo').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", file, true);
xmlhttp.send(null);
var file2 = callAjax.split(",");
document.getElementById('courseInfo').text("The course: " + file2[0] + " Taught by: " + file2[1]);
}
document.getElementById('go').onclick(findteacher)
}
window.onload = findteacher;
You're missing ?course= in file. You're not getting .value of the course element. callAjax.split(",") makes no sense -- callAjax is a function, not a string -- you should be using xmlhttp.responseText.split(",") in the onreadystatechange function. onclick is a property you assign to, not a method, so .onclick(findteacher) should be onclick = findteacher; and you shouldn't do this inside the function, it should be done just once when the page is loaded.
function findteacher () {
var file = "course.php?course=" + document.getElementById('course').value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
var file2 = xmlhttp.responseText.split(",");
document.getElementById('courseInfo').innerHTML = "The course: " + file2[0] + " Taught by: " + file2[1];
}
}
xmlhttp.open("GET", file, true);
xmlhttp.send(null);
}
function clear () {
document.getElementById('courseInfo').innerHTML = '';
}
window.onload = function() {
document.getElementById('go').onclick = findteacher;
document.getElementById('course').onclick = clear;
}

Categories

Resources