I have a table with the following data.
description
object 1
object 2
object 3
I try to get this data from my database via socket.io and put the data into a string variable called Objects. The string Objects will look like this object1,object2,object3.
If I try to do alert(objects) the string is undefined.
My HTML code is
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>SlickGrid example 1: Basic grid</title>
<link rel="stylesheet" href="/slick.grid.css" type="text/css"/>
<link rel="stylesheet" href="/css/smoothness/jquery-ui-1.8.16.custom.css" type="text/css"/>
<link rel="stylesheet" href="/examples/examples.css" type="text/css"/>
</head>
<body>
<script src="/lib/jquery-1.7.min.js"></script>
<script src="/lib/jquery.event.drag-2.2.js"></script>
<script src="../lib/jquery-ui-1.8.16.custom.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function($){
var socket = io.connect();
var objects;
var temp=[];
socket.on('load data', function(data){
for (var i = 0; i < data.length; i++) {
temp = data[i];
objects = objects + "," + temp.description;
};
objects = objects.substr(10, objects.length-10);
objects=$.trim(objects);
});
alert(objects); <== undefined
})
</script>
</body>
</html>
I tried document ready (see here below) since alert(objects) is executed before the socket.io, but this doesn't help.
$( document ).ready(function() {
alert(objects);
});
How should I solve this issue?
Thank you for your time!!
You should consider using the socket.io debugging tool inside of the chrome debugger.
$(function(){ // don't pass $ as an argument to this function
var socket = io.connect(), // what are you connecting to?
objects,
temp=[];
socket.on('load data', function(data){
for (var i = 0; i < data.length; i++) {
temp = data[i];
objects = objects + "," + temp.description;
};
objects = objects.substr(10, objects.length-10);
objects=$.trim(objects);
alert(objects); // what is the value of objects here?
});
alert(objects); // socket.on is asynchronous so this line is will pretty much always
// be executed before your callback function for socket.on()
});
Related
i created an array and insert elements by array.push(). when i console.log(array) it gives me following out put output of console.log(array)
when i console.log(array[0]) it gives me undefined. why is happing and a blue i tag appear in picture which says "this value was evaluated on first expanding it may have changed since then in array javascript" what does means. please help me to understand the problem
here the full code
index.html =>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>zip reader</title>
</head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.3/jstree.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<body>
<h3>Choose the local(s) zip file(s)</h3>
<input type="file" id="file" name="file" multiple /><br />
<div id="result_block" class="hidden">
<h3>Content :</h3>
<div id="result">
</div>
</div>
</body>
<script src="jszip.min.js"></script>
<script src="jszip-utils.min.js"></script>
<script src="app1.js"></script>
<script src="FileSaver.min.js"></script>
</html>
app1.js =>
var array = []
var contents = []
var $result = $("#result");
$("#file").on("change", function(evt) {
// remove content
$result.html("");
// be sure to show the results
$("#result_block").removeClass("hidden").addClass("show");
// Closure to capture the file information.
function handleFile(f) {
var $title = $("<h4>", {
text : f.name
});
var $fileContent = $("<ul>");
$result.append($title);
$result.append($fileContent);
var dateBefore = new Date();
JSZip.loadAsync(f) // 1) read the Blob
.then(function(zip) {
var dateAfter = new Date();
$title.append($("<span>", {
"class": "small",
text:" (loaded in " + (dateAfter - dateBefore) + "ms)"
}));
zip.forEach( function (relativePath, zipEntry) {
var y = zipEntry.name
array.push(y);
$fileContent.append($("<li>", {
text : zipEntry.name
}));
});
}, function (e) {
$result.append($("<div>", {
"class" : "alert alert-danger",
text : "Error reading " + f.name + ": " + e.message
}));
});
}
var files = evt.target.files;
for (var i = 0; i < files.length; i++) {
handleFile(files[i]);
}
console.log(array[0])
});
When you console.log an object (including arrays), it isn't being serialized, and only a reference is passed to a console. When you expand it, this reference is used to check the state of this object.
Most probably what's happening is the following sequence:
console.log(array) // passes array reference to a console
console.log(array[0]) // prints undefined immediately
array.push(...) // an actual array modification
you expand the object, and console checks the content of an array
PS.
It's reasonable to ask, what will happen, if the reference will become invalid due to any reason.
For browsers - it's simpler, since the console and JS program run under same parent process, browser is responsible for everything.
But if you'll ever try to debug Node process, which has the same API of passing the reference, you will face strange issues all over around, like this one: No debug adapter, can not send 'variables VSCODE
This is the code that I want to work out, it's about AMap.com geolocation API. I want to know how to get this value (such as gLats in code) out of the function onComplete().
<!DOCTYPE html>
<html>
<head>
<title>amap</title>
<meta charset="utf-8">
<link rel="stylesheet" href="http://cache.amap.com/lbs/static/main1119.css"/>
<script type="text/javascript" src="http://webapi.amap.com/maps?v=1.3&key=key"></script>
<script type="text/javascript" src="http://cache.amap.com/lbs/static/addToolbar.js"></script>
</head>
<body>
<div id='container'></div>
<div id="tip"></div>
<div id="text"></div>
<div id="txt"></div>
<script type="text/javascript">
var map, geolocation;
map = new AMap.Map("", {
resizeEnable: true
});
map.plugin('AMap.Geolocation', function() {
geolocation = new AMap.Geolocation({
});
map.addControl(geolocation);
geolocation.getCurrentPosition();
AMap.event.addListener(geolocation, 'complete', onComplete);
AMap.event.addListener(geolocation, 'error', onError);
});
function onComplete(data) {
var str=['succsee'];
var gLngs=data.position.getLng();
var gLats=data.position.getLat();
str.push('longitude:' + data.position.getLng());
str.push('latitude:' + data.position.getLat());
document.getElementById('tip').innerHTML = str.join('<br>');
document.getElementById('text').innerHTML = str.join('<br>');
}
function onError(data) {
document.getElementById('tip').innerHTML = 'failure';
}
</script>
</body>
</html>
As I can see, you are already accessing the needed values in onComplete():
str.push('longitude:' + data.position.getLng());
str.push('latitude:' + data.position.getLat());
You cannot simply get them, onComplete is a callback that is called when the values are available. So do anything about them in onComplete, you may want to assingn them to global variables, etc, to have them easyly accessible from anywhere in code.
Assigning them to globals is the way to go.
//declare in the global scope
var gLats = null;
var gLngs = null;
...
function onComplete(data)
{
var str=['success'];
gLats=data.position.getLat();
gLngs=data.position.getLng();
...
}
I keep getting undefined before my output text in JS.
Here is my code.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Learning javascript</title>
</head>
<body>
<p id="arrayString"></p>
<!-- Javascript -->
<script type="text/javascript" src="JS/app2.js"></script>
</body>
</html>
This is my JS
var arrayString;
var myArray=["Ms.Vickies", "Old Dutch", "Lays"];
for (var i=0; i<myArray.length; i++) {
arrayString=arrayString+myArray[i];
}
document.getElementById("arrayString").innerHTML=arrayString;
my output is undefinedMs.VickiesOld DutchLays
In addition why no spaces? I am new to JS but am working my way up. Cannot figure this out.
It's because in your first loop iteration, arrayString is undefined. Set it equal to an empty string instead.
Instead of declaring arrayString like so:
var arrayString;
Initialize it with an empty string:
var arrayString = '';
Because you are initiating a null/undefined variable by doing this: var arrayString;
You can fix it by doing this: var arrayString = "";
Better yet, instead of using a for loop, you can do it like this:
var myArray=["Ms.Vickies", "Old Dutch", "Lays"];
document.getElementById("arrayString").innerHTML = myArray.join(" ");
More info: http://www.w3schools.com/jsref/jsref_join.asp
In code ,you have just declared,not initialized.so,just replace
var arrayString;
with
var arrayString = '';
Hope it helps...Thank you.
Why does this work
app.prints(address,list.options[list.selectedIndex].value);
but this doesn't?
app.prints(status,macAddress);
JavaScript
var hey = 5;
var app = {
createList: function () {
for (var i = 0; i < 5; i++) {
list.options[i] = new Option(hey + i, "mac" + i);
}
app.prints(address, list.options[list.selectedIndex].value);
},
prints: function (location, message) {
location.innerHTML = message;
},
manageConnection: function () {
var macAddress = list.options[list.selectedIndex].value;
app.prints(status, macAddress);
}
}
HTML
<!DOCTYPE html>
<!-- Don't panic! All this
code looks intimidating but eventually it will make sense. -->
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="ECMA.js"></script>
<title>My LCD code</title>
</head>
<body onload="app.initialize();">
<p>Welcome to the LCD software</p>
<select id="list" onchange="app.prints
(address,list.options[list.selectedIndex].value);"></select>
<div id="address"></div>
<button id="connect" onclick="app.manageConnection();">Connect</button>
<div id="status">hi</div>
</body>
</html>
The difference is that a global status variable has already been defined by the browser to represent the text in the status bar. And, browsers don't allow a reference to the element to replace it.
To avoid the naming conflict, you can rename the element.
But, you really shouldn't depend on automatic globals for ids. Not all browsers implement the feature, and some only in certain modes.
var list = document.getElementById('list');
var address = document.getElementById('address');
app.prints(address, list.options[list.selectedIndex].value);
I am working on an application where I need to update the the table cell value So I make that table column editable as below.
I am getting these values from the stackMob database(cloud) .Now I want to Update this Device-nickname(editable table column) from the front-end as from the picture. You can see I am getting the Device-nickname as Undefined. So i want to put the name as I want (as I put alpesh for 352700051252111) .Now when editing is done I means when I complete the editing for first row then I want to call a function which will update the Device-nickname for the correspondence IMEI .
For printing and growing the list I used:
for(var i=0; i<=count; i++)
{
$("#ui").append("<tr><td>"+array[i].device_IMEI+"</td> <td>"+array[i].device_model+"</td><td><div contenteditable >"+array[i].device_nickname+"</div></td><tr>");
}
Now My question is:
How can I call a function to update the values when the editing is done for each row. and How can I get the IMEI of that in which editing got done and i want to get also the value after editing of Device-nickname
thanks in advance !!!
full code is
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Dashboard</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="http://static.stackmob.com/js/stackmob-js-0.8.0-bundled-min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<link rel="stylesheet" href= "http://code.jquery.com/ui/1.10.2/themes/dark-hive/jquery-ui.css" />
<!-- <link rel="stylesheet" href= "http://code.jquery.com/ui/1.10.2/themes/redmond/jquery-ui.css" />-->
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<script type="text/javascript" src="http://twitter.github.com/bootstrap/assets/js/bootstrap-modal.js"></script>
<script type="text/javascript" src="style/js/bootstrap.js"></script>
<script type="text/javascript" src="path_to/jquery.js"></script>
<script type="text/javascript" src="path_to/jquery.simplePagination.js"></script>
<link type="text/css" rel="stylesheet" href="path_to/simplePagination.css"/>
<link type="text/css" rel="stylesheet" href="style/css/bootstrap.css"></link>
<script type="text/javascript">
/* <![CDATA[ */
// Initialize StackMob object
// Copy your init data from here: https://dashboard.stackmob.com/sdks/js/config
// Your other app information is here: https://dashboard.stackmob.com/settings
StackMob.init({
appName: "swara_sangam",
clientSubdomain: ".........",
publicKey: "....",
apiVersion: 0
});
/* ]]> */
</script>
<script type="text/javascript">
/* <![CDATA[ */
$(document).ready(function() {
result();
function result() {
var device = StackMob.Model.extend({ schemaName: 'device' });
var mydevice = new device({organization_id:'1' });
var q = new StackMob.Collection.Query();
//q.lt('age', 50)..orderAsc('username');
q.setRange(0,15).orderDesc('lastmoddate');
mydevice.query(q, {
success: function(modal) {
//After StackMob returns "Bill Watterson", print out the result
var array = modal.toJSON();
// console.debug(array);
//$('#data').html(array[0].user_name);
var val = array[0].lastmoddate;
$('#last_mod_date').attr('value', val);
var key;
var count = 0;
for(key in array) {
if(array.hasOwnProperty(key)) {
count ++;
}
}
//alert(count);
for(var i=0; i<=count; i++)
{
// if(array[i].org_img == localStorage.getItem("stackmob.oauth2.user"))
//alert(array[i].org_img);
//$('#last_mod_date').html(array[0].lastmoddate);
//alert(val);
$("#ui").append("<tr><td>"+array[i].device_IMEI+"</td> <td>"+array[i].device_model+"</td><td ><div class="device-name" contenteditable>"+array[i].device_nickname+"</div></td><td>"+array[i].device_org+"</td><td>"+ new Date(array[i].lastmoddate)+"</td><tr>");
//alert("save");
//$("#ui").append("<tr><td>"+array[i].device_IMEI+"</td> <td>"+array[i].device_model+"</td><td><div class='divEditable' contenteditable='true' data-orig='"+array[i].device_nickname+"' >"+array[i].device_nickname+"</div></td><tr>");
alert("save");
//end if condition
} // end for loop
$('.device-name').on('blur', function(event){
alert(event.target.textContent);
alert($(event.target).closest('tr').find('.imei').text());
alert($(event.target).closest('tr').find('.model').text());
})
} //end success
}); // end imagesearch schema query
} // end result function
setInterval(check_newentry,1000);
function check_newentry() {
var device = StackMob.Model.extend({ schemaName: 'device' });
var mydevice = new device({ });
var q = new StackMob.Collection.Query();
q.orderDesc('lastmoddate');
mydevice.query(q, {
success: function(modal) {
//After StackMob returns "Bill Watterson", print out the result
var array = modal.toJSON();
// console.debug(array);
//$('#data').html(array[0].user_name);
// alert(lastmod_date_old +"..."+ lastmod_date);
if(lastmod_date_old < lastmod_date)
{
var val = array[0].lastmoddate;
$('#last_mod_date').attr('value', val);
var key;
var count = 0;
var counter=0;
for(key in array) {
if(array.hasOwnProperty(key)) {
count ++;
}
}
//alert(count);
for(var i=0; i<=count; i++)
{
$("#ui").append("<tr><td>"+array[i].device_IMEI+"</td> <td>"+array[i].device_model+"</td><td>"+array[i].device_nickname+"</td><td>"+array[i].device_org+"</td><td>"+new Date(array[i].lastmoddate)+"</td><tr>");
//------------------------------------------- end device schema code
counter++;
exit();
}
}
}
});
}
});
</script>
</head>
<body>
<div class="modal-body" style=''>
<table class="data table-bordered table table-striped" id="ui" >
<tr style="background-color:blue;color:white;"><td width="25%">Device-imei</td><td>Device-Model</td><td>device-nickname</td><td>Device-org</td><td>Time</td></tr>
</table>
</div>
<!--<div id="last_mod_date" value=""></div>
<div id="latlng" value=""></div> -->
</script>
</body>
</html>
$('.device-name').on('blur', function(event){
alert(event.target.textContent);
alert($(event.target).closest('tr').find('.imei').text());
alert($(event.target).closest('tr').find('.model').text());
})
See http://jsfiddle.net/Jke9J/3/
To get other data you can assign classes for each column, get closest tr after data was changed, and find data by these classes inside found tr
Edit:
See http://jsfiddle.net/Jke9J/7/
SCRIPT:
var editable = document.querySelectorAll('div[contentEditable]');
for (var i=0, len = editable.length; i<len; i++){
editable[i].setAttribute('data-orig',editable[i].innerHTML);
editable[i].onblur = function(){
if (this.innerHTML == this.getAttribute('data-orig')) {
// no change
}
else {
// change has happened, store new value
this.setAttribute('data-orig',this.innerHTML);
}
};
}
Copied from onChange event with contenteditable
You can simplify the above code like
for(var i=0; i<=count; i++)
{
$("#ui").append("<tr><td>"+array[i].device_IMEI+"</td> <td>"+array[i].device_model+"</td><td><div class='divEditable' contenteditable='true' data-orig='"+array[i].device_nickname+"' >"+array[i].device_nickname+"</div></td><tr>");
}
$(document).on('blur','.divEditable',function(){
if($(this).html()!=$(this).data('orig'))
// innnerHTML is changed then reassign the data-orig attr
{
$(this).data('orig',$(this).html());
// code to get closest imei for that row
imei=$(this).closest('tr').find('td:first-child').html();
console.log(imei);// to test
}
});