Passing arraylist values from one javascript to another - javascript

I have an arraylist of values which must be passed from one html (javascript) to another.
My code is :
function show_confirm()
{
//var r=confirm("Do you wish to use the existing Details?");
apprise('Do you wish to use the existing details?', {'verify':true}, function(r)
{
if(r)
{
// user clicked 'Yes'
alert("yes");
var a=camera.getDetails();
//window.locaton="http://www.google.co.in/";
var s=a.get(0);
alert(s);
//alert("rettttttttt" + a);
window.location="my_details.html?" + s;
//document.getElementById("location").value=a.get(0) + " ";
//alert(a.get(0) + " ");
//fetch my details from native
}
else
{
// user clicked 'No'
// display new form
alert("no");
}
});
}
</script>
and in my_details.html :
function submitForm(){
//var policyNumber=document.getElementById("number").value;
//var a=camera.getDetails();
var q=window.location.search;
if (q.substring(0, 1) == '?') {
q = query.substring(1);
}
alert("qqqqqqqqqq "+ q);
</script>
How to pass data between scripts?
I resolved it in the following way:
var c=new Array(a); (eg: a={"1","2"})
window.location="my_details.html?"+ c + "_";
and in my_details.html :
var q=window.location.search;
alert("qqqqqqqqqqqqq " + q);
var arrayList = (q)? q.substring(1).split("_"):[];
var list=new Array(arrayList);
alert("dataaaaaaaaaaaa " + list + "llll " );
and in "list" its dusplaying me "1%202";
How can i remove this %20 =space value ??
thanks
Sneha

You mean this?
function show_confirm() {
//var r=confirm("Do you wish to use the existing Details?");
apprise('Do you wish to use the existing details?', {'verify':true}, function(r) {
if(r) {
// user clicked 'Yes'
var a=camera.getDetails();
window.location="my_details.html?" + a.join("_");
}
else {
alert("no");
}
});
}
function submitForm(){
var q=window.location.search;
var arrayList = (q)? q.substring(1).split("_"):[];
}

Related

How to refresh a div to load new record when theres new record in Database

I have a div in a page where I show a list of records which are stored in my Database ( firebase). Whenever there is a new record in the database, I want the div to auto load in the new record without refreshing the whole page. So how can I do that?
Javascript code on showing records
query.on("child_added", function(messageSnapshot) {
var keys = Object.keys(messageSnapshot);
var messageData = messageSnapshot.val();
var key = messageSnapshot.getKey();
console.log("key is " + messageSnapshot.getKey());
console.log("messagesnapshot is " + messageSnapshot);
var obj = {
key: key,
};
arr.push(obj);
ref.child(key + "/User Information").once('value').then(function(snapshot) {
var name = snapshot.val().firstName
s = "<li><a href='#'>" + no + '. ' + name + ' ' + key + "</a></li>";
no++;
sources.push(s);
// for ( property in messageSnapshot) {
// console.log( property ); // Outputs: foo, fiz or fiz, foo
//}
console.log("arr.length is " + arr.length);
}).then(function(pagination) {
Pagination();
});
});
function Pagination() {
var arrLength = arr.length;
var container = $("#mylist");
// var sources = function () {
// var result = [];
//
// for (var i = 1; i < arrLength; i++) {
// result.push(i);
// }
//
// return result;
// }();
var options = {
dataSource: sources,
pageSize: 10,
callback: function(data, pagination) {
//window.console && console.log(response, pagination);
var dataHtml = '';
$.each(data, function(index, item) {
dataHtml += item;
});
console.log(dataHtml);
container.prev().html(dataHtml);
}
};
//$.pagination(container, options);
container.addHook('beforeInit', function() {
window.console && console.log('beforeInit...');
});
container.pagination(options);
container.addHook('beforePageOnClick', function() {
window.console && console.log('beforePageOnClick...');
//return false
});
return container;
}
Html code div
<div data-role="page" id="pageone">
<div data-role="header">
<button onclick="goBack()">Back</button>
<h1>Pending Transaction</h1>
</div>
<div id="mylist"></div>
</div>
At first your local code must be aware of changes in the Database, so the plain answer is:
Your JS-Code must periodically ask your DB for changes, if changes are available you can call that changes and update your content via an AJAX-Request and put it into the div#mylist
This "periodically ask" is called long polling, aspnet has for example the framework called SignalR

Cannot open file "/dev/ttyO2" when trying to use the serial port on the Beaglebone Black

I am trying to open the serial port 2 on my beagle bone, using the following code:
var b = require('bonescript');
var x = '/dev/ttyO2';
var SerialPort = require("serialport").SerialPort;
var serialPort = new SerialPort('/dev/ttyO2', {
baudrate: 115200,
parser: b.serialParsers.readline("\n")
});
The complete code:
var b = require('bonescript');
var x = '/dev/ttyO2';
var SerialPort = require("serialport").SerialPort;
var serialPort = new SerialPort('/dev/ttyO2', {
baudrate: 115200,
parser: b.serialParsers.readline("\n")
});
b.pinMode("P9_17", b.OUTPUT);
var countTry =2;
var i = 0; // to loop over the array
var waiting_interval = 3000; // waiting for every slave to reply
var deli;
var slaves = ["S1", "S2" , "S3", "S4", "S5", "S6"];
var counter=[0 , 0 , 0 , 0 ,0 ,0];
var slave_exists = false;
serialPort.on('open',function onSerialOpen(){
console.log("opened");
serialPort.on('data', function listenToSlaves(data){
i--;
if(data.search("END" + slaves[i]) ==0){
console.log("ENDED");
slave_exists = true;
counter[i]=0;
}
else{
// if(data!="END" + slaves[i]){
if(data.search("END" + slaves[i])!==0){
deli = data.indexOf(":");
var parameter = data.substring(0, deli);
var value = data.substring(deli +1);
console.log("parameter is: " + parameter + " - Value is: " + value);
}
}
if(slave_exists){
counter[i] =0;
}
i++;
});
writeToSlaves();
});
function writeToSlaves(){
//If the previous slave (the slave before the one I am sending to
//in the next step doesnt exist, add the counter or consideer
//it not existing)
if(!slave_exists){
counter[i-1]+=1;
if(counter[i-1]>=countTry){
console.log("--------counter[" + i + "]: " + counter[i]);
// in case that the slave returned no data after trying
//to send him several times
console.log(slaves[i-1] + " doesn't exist");
}
}
//sending to the following slave
b.digitalWrite("P9_17", b.HIGH);
serialPort.write(slaves[i], function(){ slave_exists = false;});
b.digitalWrite("P9_17", b.LOW);
console.log("I wrote to slave: " + i);
if(i<slaves.length - 1) i++;
else i=0;
setTimeout(writeToSlaves, waiting_interval);
}
but I am always facing this error:events.js:72
throw er; // Unhandled 'error' event
^
Error: Cannot open /dev/ttyO2
I am running another file first (the code down), the I try to rerun the previous code, and it runs perfect. I need to do that whenever I want to run the first code!
The code that runs from the first time is here:
( I tried the following code alone, it writes to the serial port but doesnt recieve, no event at recieption):
var b = require('bonescript');
var rxport = '/dev/ttyO2';
var txport = '/dev/ttyO2';
var options = { baudrate: 115200, parity: 'even', parser: b.serialParsers.readline('\n') };
var teststring = "This is the string I'm sending out as a test";
b.serialOpen(rxport, options, onRxSerial);
function onRxSerial(x) {
console.log('rx.eventrx= ' + x.event);
if(x.err) throw('***FAIL*** ' + JSON.stringify(x));
if(x.event == 'open') {
//readReapeatedly();
b.serialOpen(txport, options, onTxSerial);
}
if(x.event == 'data') {
console.log("I am receiving on rxport");
console.log('rx (' + x.data.length +
') = ' + x.data.toString('ascii'));
}
}
function onTxSerial(x) {
console.log('tx.event = ' + x.event);
if(x.err) throw('***FAIL*** ' + JSON.stringify(x));
if(x.event == 'open') {
writeRepeatedly();
}
if(x.event == 'data') {
// console.log('tx (' + x.data.length +
// ') = ' + x.data.toString('ascii'));
console.log(x.data);
}
}
function printJSON(x) {
console.log(JSON.stringify(x));
}
function writeRepeatedly() {
console.log("write to serial");
b.serialWrite(txport, teststring, onSerialWrite);
console.log("I have sent data");
}
function onSerialWrite(x) {
console.log("Iam in the onSerialWrite function");
if(x.err) console.log('onSerialWrite err = ' + x.err);
if(x.event == 'callback') {setTimeout(writeRepeatedly, 5000);
console.log("HERE");
}
}
The problem was solved.
In /boot/uboot/uEnv.txt, Update the line:"#cape_enable=capemgr.enable_partno= " to be:
"cape_enable=capemgr.enable_partno=BB-UART1,BB-UART2,BB-UART4, BB-UART5 "
or add the last line to the mentioned file. In some cases, you need to try this line instead of the mentioned:
"optargs=capemgr.enable_partno=BB-UART1,BB-UART2,BB-UART4, BB-UART5" (this is my case - but it disabled the HDMI interface of my BBB).
You can specify the UART you want to enable.
A helpful webpage is here.

BarcodeScanner2 = TypeError: Cannot set property 'innerHTML' of null

I am trying to develop a barcode scanning app using phonegap-1.4.1 in android. I am trying to store all the values in an array code[] and later on I am displaying the values using the array. I am creating a local storage of the values. Here is my declaration of an array and a counter.
localStorage["counter"]=0;
var code = ["Test1", "Test2","Test3", "Test4"];
localStorage.setItem("code", JSON.stringify(code));
Here is my javascript file for scanning the barcode and I am using an recursive function in this so that the app scanning continues and the values are stored in the array.
var scanCode = function () {
window.plugins.barcodeScanner.scan(
function (result) {
if(result.cancelled == true ) {
window.location.href = 'page5.html';
} else {
var test2 = JSON.parse(localStorage.getItem("code"));
var k = parseInt(localStorage.getItem("counter"));
document.getElementById(test2[k]).innerHTML = "result.text";
k++;
localStorage["counter"] = k;
alert("Scanned Code: " + result.text + ". Format: " + result.format + ". Cancelled: " + result.cancelled);
scanCode();}
}, function (error) {
alert("Scan failed: " + error);
window.location.href = 'page5.html';
});
}
And after storing the values I am displaying the values in some page5.html as
<tr>
<td >1</td>
<td>
<p id="Test1"></p></td>
</tr>
But I am getting the error as BarcodeScanner2 = TypeError: Cannot set property 'innerHTML' of null. Somebody please help me on this issue. Thanks in advance.
Add below javascript Function in your html file ( top of the page).
function SaveDataToLocalStorage(barcodeValue)
{
var oldItems = JSON.parse(localStorage.getItem('barcodes')) || [];
var newItem = {
'barcode': barcodeValue
};
oldItems.push(newItem);
localStorage.setItem('barcodes', JSON.stringify(oldItems));
}
Now Change Your barcode Scan Code as below :
var scanCode = function () {
window.plugins.barcodeScanner.scan(function (result) {
if(result.cancelled == true ) {
window.location.href = 'page5.html';
} else {
// below function save your data in localstorage.
SaveDataToLocalStorage(result.text);
scanCode();
}
}, function (error) {
alert("Scan failed: " + error);
window.location.href = 'page5.html';
});
}
Now, if you want to display all barcodes in page5.html just read all barcodes from localstorage and display it in page.
use following function page5.html to display all barcodes in page5.html
function displayValues()
{
var oldItems = JSON.parse(localStorage.getItem('barcodes')) || [];
for(var i=oldItems.length-1;i>=0;i--)
{
var html=document.getElementById("allCodes").innerHTML;
document.getElementById("allCodes").innerHTML=html+"<br>"+oldItems[i].barcode;
}
}
make one div name allCodes in page5.html
Your page5.html
<body>
<div id="allCodes">
</div>
</body>
<script>
function displayValues()
{
var oldItems = JSON.parse(localStorage.getItem('barcodes')) || [];
for(var i=oldItems.length-1;i>=0;i--)
{
var html=document.getElementById("allCodes").innerHTML;
document.getElementById("allCodes").innerHTML=html+"<br>"+oldItems[i].barcode;
}
}
displayValues();
</script>
//Display in table :
function displayValues()
{
var oldItems = JSON.parse(localStorage.getItem('barcodes')) || [];
if(oldItems.length>0)
{
document.getElementById("allCodes").innerHTML="<table border='2'>";
}
for(var i=oldItems.length-1;i>=0;i--)
{
var html=document.getElementById("allCodes").innerHTML;
html=html+"<tr><td>"+oldItems[i].barcode+"</td></tr>";
document.getElementById("allCodes").innerHTML=html;
}
if(oldItems.length>0)
{
var old=document.getElementById("allCodes").innerHTML;
document.getElementById("allCodes").innerHTML=old+"</table>"
}
}
The error is clearly related to document.getElementById(test2[k]) returning no element, hence, there is no element with the id given. In your sample this would be Test1.
Set the id of the paragraph to Test1 instead of Text and it find the element.

How to delete a specific value in a cookie - jquery

I am developing a shopping cart system, where the user can add or remove products to his or her basket.
I am storing 2 things for each product in the product cookie: product barcode and price.
My code so far looks like this:
var addToBasketHandler = $(".add-product");
var removeFromBasketHandler = $(".unselect");
var Basket = {
select: function (box, cookie) {
box.addClass("selected");
var ean = box.attr('ean');
var value = box.find($(".price strong")).html().replace(/[^0-9\.]/g, '');
if ($.cookie(cookie) == undefined) {
$.cookie(cookie, ean + "~" + value);
} else if ($.cookie(cookie).indexOf(ean) == -1) {
$.cookie(cookie, $.cookie(cookie) + "|" + ean + "~" + value);
}
},
deselect: function (box, cookie) {
box.removeClass("selected");
// code to delete the cookie value
}
};
$(document).ready(function () {
$(addToBasketHandler).click(function () {
var box = $(this).parents(".box-offer");
Basket.select(box, "productCookie");
});
$(removeFromBasketHandler).click(function () {
var box = $(this).parents(".box-offer");
Basket.deselect(box, "productCookie");
});
});
And after adding 3 products to my cart, my cookie looks like this:
productCookie = 9918430821007~12.00 | 7C9918430831006~3.00 | 7C7501031311309~50.30
Please help on how I could remove only the selected product from this cookie list above.
FYI I am using jquery + jquery cookie
Try
deselect: function (box, cookie) {
box.removeClass("selected");
var ean = box.attr('ean');
var value = box.find($(".price strong")).html().replace(/[^0-9\.]/g, '');
var val = ean + "~" + value; //value to be removed
if ($.cookie(cookie) !== undefined) {
var cookie_val = $.cookie(cookie);
if (cookie_val.indexOf(val) !== -1) { //check value present in cookie
var arr = cookie_val.replace(' ', '').split('|'); //remove spaces and split with |
var index = arr.indexOf(val);//get index of value to be deleted
arr.splice(index, 1); //remove value from array
$.cookie(cookie, arr.join(' | ')); //convert array to sting using join and set value to cookie
}
}
}

jqgrid jquery set a new css class for a errors in dialog box

For checking server side validation errors, I am using "afterSubmit" property of jqGRid.
afterSubmit: checkForErrors
And my checkForErrors is something like this:
function checkForErrors(response,postdata){
var success = true;
var message = ""
var json = eval('(' + response.responseText + ')');
if(json.errors.length>0) {
success = false;
for(i=0; i < json.errors.length; i++) {
message += json.errors[i] + '<br/>';
}
}
var new_id = null;
return [success,message,new_id];
}
The only thing i need to fix is change the default error class/style used by jqgrid (ie. ui-state-error), to my custom css class. How can i do that.
Thanks!
Try this:
function checkForErrors(response,postdata){
var success = true;
var message = ""
var json = eval('(' + response.responseText + ')');
if(json.errors.length>0) {
success = false;
for(i=0; i < json.errors.length; i++) {
message += json.errors[i] + '<br/>';
}
}
var new_id = null;
//Here pass the right class name instead of ".dialog" which you are using in your code
$(".dialog").find(".ui-state-error").removeClass("ui-state-error").addClass("newClass");
return [success,message,new_id];
}

Categories