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;
}
Related
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()
}
I am unable to get an alert of "Thank you for your enquiry!" after the function successfully executes and is sent to the database. My codes are as follows:
function addenquiry() {
Texttitle = $("#Texttitle").val();
Textenquiry = $("#Textenquiry").val();
if (validate()) {
var xmlhttp = new XMLHttpRequest();
var url = serverURL() + "/addenquiry.php";
url += "?userid=" + userid + "&Texttitle=" + Texttitle + "&Textenquiry=" + Textenquiry;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
addEnquiry(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
}
function addEnquiry(response) {
var arr = JSON.parse(response);
if (arr[0].result == 1) {
alert("Thank You for your enquiry!")
}
else {
alert("Sorry please try again");
}
}
Not sure where i have gone wrong, the title and message is successfully recorded in the database but i am not getting the alert, hope to receive some guidance and help from someone. Thank you!
Trying to get my code to connect to API and retrieve a list of local farmers markets but keep getting Reference error that xmlhttp is not defined on line 40. Haven't caught any spelling errors and have tried moving chunks of code to see if they work at different positions.
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<title>Markets</title>
<script>
window.onload = function() {
function myFunction(arr) {
out = "<h1>Markets</h1>";
var i;
for (i = 0; i < array.results.length; i++) {
out = out + "<em>" + item.marketname + "</em><br>" + details.marketdetails.Address + "</p>"
arr.results.forEach(printDetails)
}
document.getElementById("market_details").innerHTML = out;
}
var mybutton = document.getElementById("submit_btn")
mybutton.onclick = function() {
var xmlhttp = new XMLHttpRequest();
var zip = document.getElementById("zip").value
var url = "http://search.ams.usda.gov/farmersmarkets/v1/data.svc/zipSearch?zip=" + zip;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
itemsProcessed = 0
function printDetails(item, index, array) {
console.log(item.marketname)
var xmlhttp = new XMLHttpRequest();
var url2 = "http://search.ams.usda.gov/farmersmarkets/v1/data.svc/mktDetail?id=" + id;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myDArr = JSON.parse(xmlhttp.responseText);
details = myDArr
//console.log(myDArr.marketdetails)
};
xmlhttp.open("GET", url2, true);
xmlhttp.send();
itemsProcessed++
}
}
</script>
</head>
<body>
<h1> Find Your Local Market!<h1>
Enter Zip Code:<input id="zip"></p><br>
<button id = "submit_btn">Submit</button>
<div id="market_details"></div>
</body>
The first problem is that you define the xmlhttp inside the onclick handler and you use it outside the handler:
mybutton.onclick = function() {
var xmlhttp = new XMLHttpRequest(); //<-- This must be used from inside the current function
//Your code here
xmlhttp.open("GET", url, true); //<-- put this inside the function
xmlhttp.send(); //<-- put this inside the function
}
The second problem is that you open and send the XMLHttpRequest inside the onreadystatechange handler:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myDArr = JSON.parse(xmlhttp.responseText);
details = myDArr
//console.log(myDArr.marketdetails)
};
itemsProcessed++
}
xmlhttp.open("GET", url2, true);//<-- put this outside the onreadystatechange handler
xmlhttp.send();//<-- put this outside the onreadystatechange handler
I hope this will help you.
The code below runs fine with a hard-coded tag name. I need to be able to call "loadDoc" with a variable that will return the tag I specify. I am rather new to JQuery and I'm not sure how to accomplish this.
Many thanks.
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp);
}
}
xhttp.open("GET", "pyg280c.xml", true);
xhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var htext = "";
var x = xmlDoc.getElementsByTagName("PYP280CR");
for (i = 0; i <x.length; i++) {
htext += "<p>" + x[i].getElementsByTagName("PCST")[0].childNodes[0].nodeValue + "</p>";
}
document.getElementById("helptext").innerHTML = htext;
}
Since you say it works fine when you hardcode the tag name then as #Hackerman said pass the tagname into the loadDoc function. Pass it on to the myFunction function and simply use the tag name variable in the getElementByTagName(tag) function (no quotes around variables). It should work.
function loadDoc(myTagName) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp, myTagName);
}
}
xhttp.open("GET", "pyg280c.xml", true);
xhttp.send();
}
function myFunction(xml, tag) {
var i;
var xmlDoc = xml.responseXML;
var htext = "";
var x = xmlDoc.getElementsByTagName("PYP280CR");
for (i = 0; i <x.length; i++) {
htext += "<p>" + x[i].getElementsByTagName(tag)[0].childNodes[0].nodeValue + "</p>";
}
document.getElementById("helptext").innerHTML = htext;
}
FYI - You mentioned jQuery. There is no jQuery in your code. jQuery probably would have made this easier.
Jquery version including some default ajax error handling:
function loadDoc(tag){
$.ajax({
url: "pyg280c.xml",
type: "GET",
dataType: "xml",
success: function(xml){
var xmlDOC = $.parseXML(xml.responseXML);
var x = $(xmlDOC).find("PYP280CR");
var htexts = $.map(x, function(el, idx){
return $(el).find(tag).children()[0].val();
}
htext = htexts.join(" ");
$('#helptext').html(htext);
},
error: function (xhr, ajaxOptions, thrownError){
console.log('status = ' + xhr.status);
console.log('error = ' + thrownError);
}
}
I have some problems with returning a value from a function into a variable. It is apparently "undefined". This apparently happens due to the asynchronity of JavaScript. But in my case I don't know how to circumvent it with "callbacks" or "promises". Please see code below. I would like to return the exchange rate saved in "value" back to "rate" and use it further in my code. Any ideas?
var rate = rateCalc();
var currency = "EUR";
function rateCalc(){
var value;
if (currency != "EUR") {
var xmlhttp = new XMLHttpRequest();
var rateURL = "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D"+"EUR"+"HKD"+"%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var json = JSON.parse(xmlhttp.responseText);
value = json.query.results.row.rate;
alert("At this position the value is defined: "+ value);
return value;
}
}
xmlhttp.open("GET", rateURL, true);
xmlhttp.send();
}
else {
value = 1;
return value;
}
}
alert("The return statement somehow didn't work: "+ rate);
I'm a newbie, by the way. So sorry, if this question has already been asked like a million times before.
Thanks
René
You can't return anything from a async function in JS. So create a new function and use it as a callback function. See the below example.
var rate = rateCalc();
var currency = "EUR";
function rateCalc(){
var value;
if (currency != "EUR") {
var xmlhttp = new XMLHttpRequest();
var rateURL = "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D"+"EUR"+"HKD"+"%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var json = JSON.parse(xmlhttp.responseText);
value = json.query.results.row.rate;
alert("At this position the value is defined: "+ value);
valueCallBack(value); //Callback function
}
}
xmlhttp.open("GET", rateURL, true);
xmlhttp.send();
}
else {
value = 1;
return value;
}
}
function valueCallBack(value){
console.log("value is " + value);
}
Update : You can use the Promise API introduced in the ES6 or use JQUERY deferred objects.
xmlhttp.send() shouldn't be empty. Try this. I hope it will do the job!
xmlhttp.send(null);
You can send the response value to another function so when you have a value it will be displayed without it being undefined.
Try this:
rateCalc();
var currency = "EUR";
function rateCalc() {
var value;
if (currency != "EUR") {
var xmlhttp = new XMLHttpRequest();
var rateURL = "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D"+"EUR"+"HKD"+"%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var json = JSON.parse(xmlhttp.responseText);
value = json.query.results.row.rate;
show(value);
}
};
xmlhttp.open("GET", rateURL, true);
xmlhttp.send();
} else {
value = 1;
show(value);
}
}
function show(rate) {
alert("Value: "+ rate);
}
So this is how I changed the code now. The call back function is used for all further calculations with the called back value. Thanks again to #Jijo John and #nx0side.
var currency = "HKD";
var value;
if (currency != "EUR")
{
var xmlhttp = new XMLHttpRequest();
var rateURL = "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D"+"EUR"+"HKD"+"%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json";
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var json = JSON.parse(xmlhttp.responseText);
value = json.query.results.row.rate;
valueCallBack(value); //Callback function
}
}
xmlhttp.open("GET", rateURL, true);
xmlhttp.send();
}
else
{
valueCallBack(1);
}
//in this function all further calculations with "value" need to take place.
function valueCallBack(value)
{
//example
var result = 70000/value;
console.log("Result is " + result);
}