My JavaScript code does not show the expected results - javascript

I am trying to print objects from an API using JSON and AJAX and it works when I use console.log to view it. But my generateCreatureDiv function does not work for some reasons.
This is my code:
$(document).ready(function() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = this.responseText;
var creatureData = JSON.parse(response);
console.log(creatureData);
// get a creature from the data
for (var i = 0; i < creatureData.creatures.length; i++) {
var creature = creatureData.creatures;
console.log(creature[i]);
document.getElementById("CreatureEntry").innerHTML = generateCreatureDiv(creature[i]);
}
function generateCreatureDiv(creature) {
var CreatureDiv = $("<div />");
console.log("hoe");
CreatureDiv.id = "CreatureInfo";
console.log("hoe")
$("CreatureDiv").append("<h1>" + creature.name + "</h1>");
console.log("hoe");
$("CreatureDiv").append("<img>" + creature.image + "</img>");
return CreatureDiv;
console.log("hoe");
}
// create a select option for the object
// Have a
}
};
xhttp.open("GET", "https://api.myjson.com/bins/17f3jl", true);
xhttp.send();
});
<!DOCTYPE html>
<html>
<head>
<script src="./jquery-3.1.1.min.js"></script>
<script src="./script.js"></script>
<script src="./stylesheet.css"></script>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="CreatureEntry">
<select id="SelectOption">
</select>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>

remove the " quotes in $("CreatureDiv") .Its not select with any ID or Class.And on your code Already declare with var CreatureDiv = $("<div />"); .So change as like this
function generateCreatureDiv(creature) {
var CreatureDiv = $("<div />");
console.log("hoe");
CreatureDiv.id = "CreatureInfo";
console.log("hoe")
$(CreatureDiv).append("<h1>" + creature.name + "</h1>");
console.log("hoe");
$(CreatureDiv).append("<img>" + creature.image + "</img>");
return CreatureDiv;
console.log("hoe");
}
And change like this
document.getElementById("CreatureEntry").innerHTML += generateCreatureDiv(creature[i]);
instead of
document.getElementById("CreatureEntry").innerHTML = generateCreatureDiv(creature[i]);
Because innerHTML =generateCreatureDiv(creature[i]); it will reset previous value on each time call

This line is erasing all of the content of your DIV for each element of your array:
document.getElementById("CreatureEntry").innerHTML = generateCreatureDiv(creature[i]);
Remove the first part and just call your method and append the results?
$("CreatureEntry").append(generateCreatureDiv(creature[i]));
Also, you need to remove the quotes wherever you're referencing $("CreatureDiv") and use $(CreatureDiv).

Related

How to return contents of php using javascript $.get

I have a PHP script hosted in the root of a working LAMP server which provides me with the output of a MySQL query. The typical output of values.php:
2017-01-12 22:02:17/12/2017-01-12 22:03:18/12/2017-01-12
22:04:18/12/2017-01-12 22:05:18/12/2017-01-12 22:06:18/12/2017-01-12
22:07:19/12/2017-01-12 22:08:19/12/2017-01-12 22:09:19/12/2017-01-12
22:10:20/12/2017-01-12 22:11:20/12/2017-01-12 22:12:20/12/2017-01-12
22:13:21/12/2017-01-12 22:14:21/12/2017-01-12 22:15:21/12/2017-01-12
22:16:21/12/2017-01-12 22:17:22/12/2017-01-12 22:18:22/11/2017-01-12
22:19:22/11/2017-01-12 22:20:23/12/2017-01-12 22:21:23/11/2017-01-12
22:22:23/11/2017-01-12 22:23:24/11/2017-01-12 22:24:24/11/2017-01-12
22:25:24/11/2017-01-12 22:26:25/11/2017-01-12 22:27:25/11/2017-01-12
22:28:25/11
I am trying to use $.get to break it up and list it on a page. My code is as follows but it won't work:
<!DOCTYPE html>
<html>
<body>
<script>
function() {
var switch1 = true;
$.get('values.php', function(data) {
data = data.split('/');
for (var i in data)
{
if (switch1 == true)
{
document.write(data[i] + " Temp: ");
switch1 = false;
}
else
{
document.writeln(data[i]);
switch1 = true;
}
}
});
};
</script>
</body>
</html>
Any ideas where I am going wrong?
I should have added the code <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jque‌​ry.min.js"></script> in the html. Final code is as follows and works fine:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<script>
var switch1 = true;
$.get('values.php', function(data) {
data = data.split('/');
for (var i in data)
{
if (switch1 == true)
{
document.write(data[i] + " Temp: ");
switch1 = false;
}
else
{
document.write(data[i] + "<br>");
switch1 = true;
}
}
});
</script>
</body>
</html>
Thanks to all.
I don't know what your PHP script actually returns but if I store manually to data it seems to work the way you expected. Can you explain what exactly does not work?
I would shorten code bit though:
var switch1 = true;
var data = "2017-01-12 22:02:17/12/2017-01-12 22:03:18/12/2017-01-12 22:04:18/12/2017-01-12 22:05:18/12/2017-01-12 22:06:18/12/2017-01-12 22:07:19/12/2017-01-12 22:08:19/12/2017-01-12 22:09:19/12/2017-01-12 22:10:20/12/2017-01-12 22:11:20/12/2017-01-12 22:12:20/12/2017-01-12 22:13:21/12/2017-01-12 22:14:21/12/2017-01-12 22:15:21/12/2017-01-12 22:16:21/12/2017-01-12 22:17:22/12/2017-01-12 22:18:22/11/2017-01-12 22:19:22/11/2017-01-12 22:20:23/12/2017-01-12 22:21:23/11/2017-01-12 22:22:23/11/2017-01-12 22:23:24/11/2017-01-12 22:24:24/11/2017-01-12 22:25:24/11/2017-01-12 22:26:25/11/2017-01-12 22:27:25/11/2017-01-12 22:28:25/11"
data = data.split('/').map(function(i){
document.write(i + (switch1 ? " Temp: " : ""));
switch1 = !switch1;
});
Give this a try, should do what you are looking for...
var content = "2017-01-12 22:02:17/12/2017-01-12 22:03:18/12/2017-01-12 22:04:18/12/2017-01-12 22:05:18/12/2017-01-12 22:06:18/12/2017-01-12 22:07:19/12/2017-01-12 22:08:19/12/2017-01-12 22:09:19/12/2017-01-12 22:10:20/12/2017-01-12 22:11:20/12/2017-01-12 22:12:20/12/2017-01-12 22:13:21/12/2017-01-12 22:14:21/12/2017-01-12 22:15:21/12/2017-01-12 22:16:21/12/2017-01-12 22:17:22/12/2017-01-12 22:18:22/11/2017-01-12 22:19:22/11/2017-01-12 22:20:23/12/2017-01-12 22:21:23/11/2017-01-12 22:22:23/11/2017-01-12 22:23:24/11/2017-01-12 22:24:24/11/2017-01-12 22:25:24/11/2017-01-12 22:26:25/11/2017-01-12 22:27:25/11/2017-01-12 22:28:25/11";
var regexp = /(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})\/(\d{2})/g;
var matches;
while ( matches = regexp.exec( content ) ) {
document.write( matches[1] + " Temp: " + matches[2] + "<br/>");
}
Hope this helps!

How to resume scorm 2004 where we left previously?

Hi,
I'm developing scorm based project, I've to play the scorm 2004 packages. courses are playing and capturing the data working properly with the using of LMS functions(LMSFinish(), commit()..etc). Now I've to implement one more function i.e RESUME the package where user left last time.
Sample cmi data
scoid:"1234"
data[cmi.completion_status]:"incomplete"
data[cmi.exit]:"suspend"
data[cmi.location]:"page3"
Hope you help.
Commonly 'cmi.suspend_data' is used so you can store a string (JSON, or other delimiter format if you want or need structure) to resume answers.
'cmi.location' has 1000 characters for you to also store a string and it can be as simple as "3" or "page3" as you have it.
Your navigation in your content presentation/player would need to be able to respond to having a location to go to. And you can use the suspend_data to put student answers back the way they were when they left.
How you decide if you are 'resuming' is a little tricky since anything except 'cmi.entry' = 'ab-initio' is a resume. Some LMS systems return blank or 'resume' so then you know to fetch your 'cmi.location' and 'cmi.suspend_data' if you use it.
This is all code you have to write, or you can read up a bit on my Wiki.
https://github.com/cybercussion/SCOBot/wiki.
I had some workaround for resume and is working for me . I saved suspended_data and then retrieved that data so player resumed for that position .
#kishor-koshti
How did you do that, I mean, tell the player to resume from a given position?
I'm being able to capture the suspended_data but I don't know how to set it back the next time I launch that course.
The API object that I have on javascript seems to be read only.
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<style>
body { margin: 0; }
</style>
<script type="text/javascript">
var API = {};
function setupScormApi() {
API.LMSInitialize = LMSInitialize;
API.LMSGetValue = LMSGetValue;
API.LMSSetValue = LMSSetValue;
API.LMSCommit = LMSCommit;
API.LMSFinish = LMSFinish;
API.LMSGetLastError = LMSGetLastError;
API.LMSGetDiagnostic = LMSGetDiagnostic;
API.LMSGetErrorString = LMSGetErrorString;
}
function LMSInitialize(initializeInput) {
console.log("LMSInitialize: " + initializeInput);
// invokeCSharp("LMSInitialize: " + initializeInput);
return true;
}
function LMSGetValue(varname) {
console.log("LMSGetValue: " + varname);
//invokeCSharp("LMSGetValue: " + varname);
return "";
}
function LMSSetValue(varname, varvalue) {
console.log("LMSSetValue: " + varname + "=" + varvalue);
// invokeCSharp("LMSSetValue: " + varname + "=" + varvalue);
return "";
}
function LMSCommit(commitInput) {
console.log("LMSCommit: " + commitInput);
// invokeCSharp("LMSCommit: " + commitInput);
return true;
}
function LMSFinish(finishInput) {
console.log("LMSFinish: " + finishInput);
// invokeCSharp("LMSFinish: " + finishInput);
return true;
}
function LMSGetLastError() {
console.log("LMSGetLastError: ");
// invokeCSharp("LMSGetLastError: ");
return 0;
}
function LMSGetDiagnostic(errorCode) {
console.log("LMSGetDiagnostic: " + errorCode);
// invokeCSharp("LMSGetDiagnostic: " + errorCode);
return "";
}
function LMSGetErrorString(errorCode) {
console.log("LMSGetErrorString: " + errorCode);
// invokeCSharp("LMSGetErrorString: " + errorCode);
return "";
}
setupScormApi();
</script>
<iframe id="frm1" src="./Content/index_lms.html" style="width: 100%; height: 100%"></iframe>
</body>
</html>
Exec solution by Mehonder
// story_content/user.js
let lastSlideLoaded = ''; //global variable
function Script1() {
if (lastSlideLoaded == '') {
lastSlideLoaded = 'X';
var ACT_firstID = window.globals.parsedParams["last_slide"]; //URL Argument
if (!ACT_firstID == (null || "" || "0")) {
Jump_Slide(ACT_firstID); //Set Slide
}
} else {
SetLastSlide();
}
}
function SetLastSlide() {
// send to last slide info to server//
var xhttp = new XMLHttpRequest();
var PACKID = window.globals.parsedParams["pack_id"];
var LASTID = window.DS.presentation.playerProps.attributes.CurrentSlideId;
var lastSlideURL = "/services_index.php?page=last_slide&pack_id=" + PACKID + "&last_slide=" + LASTID;
xhttp.open('GET', lastSlideURL, true);
xhttp.send();
}
function Jump_Slide(Target_Slide) {     
// trigger slide change event //                              
g = DS.pubSub;              
p = DS.events;              
i =  "_player." + Target_Slide;              
g.trigger(p.request.NEXT_SLIDE, i, "_current")
}

Recursion function in XML using Javascript DOM

i am trying to make html page, that should shows all the nodes in xml file. there are other ways but i want to do it using javascript DOM through recursive function. i've tried this. suggest please.
**
<!DOCTYPE html>
<html>
<head>
<title>Adi the great</title>
<script type="text/javascript">
var httpreq=null;
var response=null;
setTimeout("loadDoc()",100);
setTimeout("loadDocument()",1000);
function loadDoc()
{
if(window.XMLHttpRequest)
httpreq=new window.XMLHttpRequest();
else
httpreq=new ActiveXObect("Microsoft.XMLHTTP");
httpreq.open("get","ADI_SUPPORT.xml",true);
httpreq.send(null);
//httpreq.onreadystatechange=loadDocument;
}
function loadDocument()
{
res=httpreq.responseXML;
play("loaded");
traverse(res.documentElement);
}
function traverse(element)
{
play("inside function with element =>"+element.nodeName);
len = element.childNodes.length;
play(element.nodeName + " is node with len = "+len);
if(len>1)
{
play("len is > 1");
temp="";
for(i=1;i<len;i+=2)
temp+=element.childNodes[i].nodeName+",";
play("temp="+temp);
for(i=1;i<len;i+=2)
{
play("started element "+element.childNodes[i].nodeName+" at i="+i);
traverse(element.childNodes[i]);
play("ended element "+element.childNodes[i].nodeName+" at i="+i);
}
}
else
{
play("node ends with "+element.textContent);
}
}
function play(x) { document.write(x + "<br/>"); }
</script>
</head>
<body>
</body>
</html>
**

Call a cfquery in javascript but, it's not doing anything

I'm trying to create a query using Coldfusion (cfquery) to retrieve several dollar amounts, add them, and then see if it matches the dollar amount being calculated in the application. But, it's not doing anything.
I'm attempting to do all of this in javascript.
Here is the code.
function ValidateFunding(){
var casenum = document.getElementById('CaseNum').value;
var cycle = document.getElementById('Cycle').value;
var year = document.getElementById('FSYear').value;
var cnty = document.getElementById('selCounty');
var cntyID = cnty.options[cnty.selectedIndex].value;
<cfquery name="PSP" datasource="QueryTest">
SELECT g.Fee220 + g.Fee330 + g.Fee456 + g.Fee225 AS GrandTotal
FROM ProgFees g INNER JOIN County ON g.CountyID = cntyID
WHERE g.Year = year
AND g.Cycle = cycle
AND g.CaseNum = casenum
</cfquery>
if (document.getElementById('totbud').value = PSP.GrandTotal){
alert('The fee matches.');
return false;
}
else
{
alert('Fees do not match.');
}
return true;
}
Here is a page I worked up for a test. There are comments in the code to help explain what's going on. Two key lines are the <cfajaxproxy> tag and jd.getData(); is my AJAX call to CF.
<cfscript>
variables.folders = {"client":["Favorites","Not Used"],"org":["2012","2011"],"public":["New","Old"]};
</cfscript>
<cfajaxproxy cfc="cfc.jsondata" jsclassname="emaildata" />
<!DOCTYPE html>
<html>
<head>
<title>DevJSON</title>
<script src="js/jquery.1.7.2.js" type="text/javascript" language="JavaScript"></script>
<script src="js/handlebars.js" type="text/javascript" language="JavaScript"></script>
<link rel="stylesheet" href="css/json.css" type="text/css"/>
<script type="text/javascript">
<!--- toScript will output CF vars as js vars --->
<cfoutput>
var #toScript(variables.folders, 'folders')#;
var #toScript(cgi.http_host & '/data/emaildata.json','jsonPath')#;
</cfoutput>
var jd = new emaildata();
// setup my js object from cfajaxproxy above
var buildGrid = function(dataObj){
var menus;
var source = $('#grid').html();
var template = Handlebars.compile(source);
$("#mainContent").hide();
$("#mainContent").children().remove();
$("#mainContent").append(template(dataObj));
$("#mainContent").fadeIn('slow');
}
// Error handler for the asynchronous functions.
var badJson = function(statusCode, statusMsg){
alert('Status: ' + statusCode + '<br /><br /> ' + statusMsg);
}
// output data
var buildmenu = function(){
$.each(folders, function(fkey,fval) {
if(this.indexOf() < 1){
$('li[data-type="' + fkey + '"] > div').append('<ul class="' + fkey + '"></ul>');
}
$.each(fval, function(dkey, dval){
$('[class="' + fkey + '"]').append('<li id="' + fkey + '">' + dval + '</li>');
});
});
}
$(document).ready(function(){
buildmenu();
$('.directory > ul > li').click( function() {
//set callback, errorhandler and then call the getData function in my CFC
jd.setCallbackHandler(buildGrid);
jd.setErrorHandler(badJson);
jd.getData(this.id);
$(".directory > ul > li").removeClass("highlight");
$(this).addClass('highlight');
});
$("#mainContent").css('display','none');
$('li[data-type]').css('cursor','pointer');
});
</script>
<!--- Setup handlebars template --->
<script id="grid" type="text/x-handlebars-template">
<div class="gridDetail">
{{#each DATA}}
<div class="row">
{{#each this}}
<span class="cell">
{{.}}
</span>
{{/each}}
</div>
{{/each}}
</div>
</script>
</head>

Javascript opener window

I have function that opens up a window, and the values from the newly opened window are listed in the opener window.
The 2nd window - has this function:
function AddOtherRefDoc(name, number) {
var remove = "<a href='javascript:void(0);' onclick='removeRefDoctor(this)'>Remove</a>";
var html = "<li><b> Referral Doctor: </b>"+name+"<b>, Referral No: </b>"+number+ " " +remove+" <input type='text' name='ref_docs' value='"+name+"'></input><input type='text' name='ref_nos' value='"+number+"'></input></li>";
opener.jQuery("#r_docs").append(jQuery(html));
}
The function that calls the one above is:
function addRefDoc(){
var count = 0;
var ref_docarray ;
var ref_noarray ;
<%for(int i1=0; i1<vec.size(); i1++) {
prop = (Properties) vec.get(i1);
String ref_no = prop.getProperty("referral_no","");
String ref_name = (prop.getProperty("last_name", "")+ ","+ prop.getProperty("first_name", ""));
%>
if(document.getElementById("refcheckbox_<%=ref_no%>").checked) {
count++;
if ((ref_doctor!=null)&&(ref_doctor!="")&&(ref_docno!=null)&&(ref_docno!="")) {
ref_docarray = ref_doctor.split(";");
ref_noarray = ref_docno.split(";");
if ((containsElem(ref_docarray,"<%=ref_name%>"))||(containsElem(ref_noarray,<%=ref_no%>))) {
alert("Referral doctor " + "<%=ref_name%>" + " already exists");
} else {
AddOtherRefDoc("<%=ref_name%>", <%=ref_no%>);
}
} else {
AddOtherRefDoc("<%=ref_name%>", <%=ref_no%>);
}
}
<%} %>
self.close();
}
function containsElem(array1,elem) {
for (var i=0;i<array1.length;i++) {
if(array1[i]==elem){
return true;
} else{
return false;
}
}
}
When this function is called, it is supposed to carry the 2 input elements "ref_docs" and "ref_nos" into the page that opened this window. But it is not doing so. It lists the elements alright but when I try to use "ref_docs" and "ref_nos" in another Javascript function in the 1st window, I see that "ref_nos" and "ref_docs" are empty.
What am I doing wrong?
function updateRd(){
var ref_docs = jQuery("#updatedelete").find('input[name="ref_docs"]');
var ref_nos = jQuery("#updatedelete").find('input[name="ref_nos"]'); alert(ref_docs.val() + ref_nos.val());
var rdocs = new Array();
var rnos = new Array();
ref_docs.each(function() { rdocs.push($(this).val()); } );
ref_nos.each(function() { rnos.push($(this).val()); } );
$('#r_doctor').val(rdocs.join(";"));
$('#r_doctor_ohip').val(rnos.join(";")); }
–
This function returns an error saying "ref_docs" and "ref_nos" are undefined.
I think it is trying to use the jQuery on the other page to find "#r_docs" on the current page.
Try:
jQuery(opener.document).find("#r_docs").append(html);
UPDATE:
I created index.html:
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.js"></script>
<script type="text/javascript">
window.jQuery = jQuery;
function openChild ()
{
var mychildwin = window.open("child.html");
}
</script>
</head>
<body>
<input type="button" value="click" onclick="openChild();" />
<div id="r_docs">
Redocs here.
</div>
</body>
</html>
and child.html:
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.js"></script>
<script type="text/javascript">
function AddOtherRefDoc(name, number) {
var remove = "<a href='javascript:void(0);' onclick='removeRefDoctor(this)'>Remove</a>";
var html = "<li><b> Referral Doctor: </b>"+name+"<b>, Referral No: </b>"+number+ " " +remove+" <input type='text' name='ref_docs' value='"+name+"'></input><input type='text' name='ref_nos' value='"+number+"'></input></li>";
jQuery(opener.document).find("#r_docs").append(html);
}
</script>
</head>
<body>
<input type="button" value="click" onclick="AddOtherRefDoc('name', 42);"/>
</body>
</html>
UPDATE2:
in your update function document.updatedelete has no attributes ref_docs and ref_nos.
try:
jQuery("#updatedelete")
.find('input[name="ref_docs"], input[name="ref_nos"]')
Where your form is
<form id="updatedelete" ... >
Your function that accesses the DOM elements is incorrect. updatedelete is not a property of document, nor will accessing a ref_docs or ref_nos property automatically build a collection of input elements. Since you're using jQuery already, try this:
var ref_docs = $('input[name="ref_docs"]');
var ref_nos = $('input[name="ref_nos"]');
That will give you Array (or at least array-like) objects that will let you access your inputs:
var rdocs = new Array();
var rnos = new Array();
ref_docs.each(function() { rdocs.push($(this).val()); } );
ref_nos.each(function() { rnos.push($(this).val()); } );
$('#r_doctor').val(rdocs.join(";"));
$('#r_doctor_ohip').val(rnos.join(";"));

Categories

Resources