Save and retrieve user input from database with javascript? - javascript

I'm working on a small, temporary site that will be used for collecting some names.
The idea is that people fill in the number of their class and their name and once they press a button, these two values are added to the page and can be viewed by everyone who visits the site.
I've already made a concept of this using javascript: www.googledrive.com/host/0B_eZKT0Ni3-tOXF5OVVQeWZRRjQ
The only problem is that the items aren't really stored on the site. As far as I know, you can only accomplish this using a database, but I have no experience with linking a database to a webpage.
Can someone help me with this or does someone know a source where I can find a solution for this? My searches turned up nothing.
I'm sorry if I'm sounding like a "help vampire". I only turned to you guys for a solution because I can't find it anywhere else.
HTML:
<body>
<div id="wrapper">
<div id="header">
<h2 id="title">Italiëreis 2015: opdiening tijdens quiz</h2>
</div>
<div id="content">
<!-- eerste ploeg -->
<div class="L">
<p id="kop">Ploeg 1</p>
<p class="klas"><input type="text" id="klas1" class="text" maxlength="2" placeholder="Klas"/></p>
<p class="naam"><input type="text" id="naam1" class="text" placeholder="Naam"/></p>
<input type="button" onclick="changeText1()" value="Schrijf in" class="button" />
<br>
<p>Reeds ingeschreven mensen:</p>
<div class="overflow">
<ol id="lijst1"></ol>
</div>
</div>
<!-- tweede ploeg -->
<div class="L">
<p id="kop">Ploeg 2</p>
<p class="klas"><input type="text" id="klas2" class="text" maxlength="2" placeholder="Klas"/></p>
<p class="naam"><input type="text" id="naam2" class="text" placeholder="Naam"/></p>
<input type="button" onclick="changeText2()" value="Schrijf in" class="button"/>
<br>
<p>Reeds ingeschreven mensen:</p>
<div class="overflow">
<ol id="lijst2"></ol>
</div>
</div>
<!-- derde ploeg -->
<div class="L">
<p id="kop">Ploeg 3</p>
<p class="klas"><input type="text" id="klas3" class="text" maxlength="2" placeholder="Klas"/></p>
<p class="naam"><input type="text" id="naam3" class="text" placeholder="Naam"/></p>
<input type="button" onclick="changeText3()" value="Schrijf in" class="button"/>
<br>
<p>Reeds ingeschreven mensen:</p>
<div class="overflow">
<ol id="lijst3"></ol>
</div>
</div>
<!-- vierde ploeg -->
<div class="L">
<p id="kop">Ploeg 4</p>
<p class="klas"><input type="text" id="klas4" class="text" maxlength="2" placeholder="Klas"/></p>
<p class="naam"><input type="text" id="naam4" class="text" placeholder="Naam"/></p>
<input type="button" onclick="changeText4()" value="Schrijf in" class="button"/>
<br>
<p>Reeds ingeschreven mensen:</p>
<div class="overflow">
<ol id="lijst4"></ol>
</div>
</div>
</div>
<div id="footer">
<div id="credits">Code geschreven door Bert-Jan van Dronkelaar - 6E</div>
</div>
</div>
CSS is irrelevant.
Javascript:
//eerste ploeg
function changeText1() {
var klas1 = document.getElementById('klas1').value;
var naam1 = document.getElementById('naam1').value;
if (document.getElementById('klas1').value != "" && document.getElementById('naam1').value != "") {
var node = document.createElement("LI");
var textnode1 = document.createTextNode(klas1 + " " + naam1);
node.appendChild(textnode1);
document.getElementById("lijst1").appendChild(node);
}
}
//tweede ploeg
function changeText2() {
var klas2 = document.getElementById('klas2').value;
var naam2 = document.getElementById('naam2').value;
if (document.getElementById('klas2').value != "" && document.getElementById('naam2').value != "") {
var node = document.createElement("LI");
var textnode2 = document.createTextNode(klas2 + " " + naam2);
node.appendChild(textnode2);
document.getElementById("lijst2").appendChild(node);
}
}
//derde ploeg
function changeText3() {
var klas3 = document.getElementById('klas3').value;
var naam3 = document.getElementById('naam3').value;
if (document.getElementById('klas3').value != "" && document.getElementById('naam3').value != "") {
var node = document.createElement("LI");
var textnode3 = document.createTextNode(klas3 + " " + naam3);
node.appendChild(textnode3);
document.getElementById("lijst3").appendChild(node);
}
}
//vierde ploeg
function changeText4() {
var klas4 = document.getElementById('klas4').value;
var naam4 = document.getElementById('naam4').value;
if (document.getElementById('klas4').value != "" && document.getElementById('naam4').value != "") {
var node = document.createElement("LI");
var textnode4 = document.createTextNode(klas4 + " " + naam4);
node.appendChild(textnode4);
document.getElementById("lijst4").appendChild(node);
}
}

#SpencerWieczorek is not wrong, PHP and MySql will work for what you need. However, there is a bit of a learning curve there.
For a beginner, I'd recommend using Parse. It's free and it makes saving and retrieving data trivial. Below is simple app that lets the user input a class year and their name and saves them so others can see them on the same page.
The snippet here wont work due to SO restrictions...
...but here is a working jsfiddle
This is accomplished with plain ole javascript BTW
To get this going on your own you'll need to:
You'll need to go to https://www.parse.com/#signup and create an account with them
Go to https://www.parse.com/apps/new and create an app
add this in your html's head tag <script type="text/javascript" src="https://www.parsecdn.com/js/parse-1.3.0.min.js"></script>
Go to https://www.parse.com/apps/quickstart#parse_data/web/new, select your app from the dropdow (top-ish right) the Parse.initialize() function will be shown here with your app's Application ID and JavaScript key, copy this line for later
Replace the Parse.initialize() function in my example with the one you copied in step 4
Read up on the their javascript guide here to see what all you can do with parse
for a more indepth look, check out the Parse JavaScript SDK & Cloud Code Reference
You can also interact with parse with other scripting languages if you'd like.
Parse is free up to a certain amount of usage. I have one app that's used daily by 100+ users and doesn't come anywhere near having to pay anything.
Parse.initialize("Application ID", "JavaScript key");
function saveInput(){
//get our new values
var klassYear = document.getElementById('klassYear').value.trim();
var studentName = document.getElementById('studentName').value.trim();
// dont continue if either value is blank
if(klassYear=="" ||studentName=="" ){
alert ('Please fill in both fields.') ;
return;
}
// create the `Parse` object
var Klass = Parse.Object.extend("Klass");
var _klass = new Klass();
// set the object's values to our input values
_klass.set("klassYear", klassYear);
_klass.set("studentName", studentName);
// save the object
_klass.save(null, {
success: function(_klass) {
// if the save succeeded, add the new info to our page
retrieveSavedInputs()
},
error: function(_klass, error) {
// save failed, do error handeling here
console.log('Failed to create new object, with error code: ' + error.message);
}
});
}
function retrieveSavedInputs(){
// create a query to search for our `Klass` items
var Klass = Parse.Object.extend("Klass");
var query = new Parse.Query(Klass);
query.find({
success: function(results) {
// get our table's `tbody` and clear it
var myTbl = document.getElementById('mytbl');
myTbl.innerHTML='';
// `results` is an array of all the matches
// loop through each
for(var i =0; i < results.length; i++){
// get the values from the saved object
// note that `klassYear` and `studentName`
// are not available within the scope of the `success` function
var k = results[i].get("klassYear")
var s = results[i].get("studentName")
// create a table row with the info and add it at the top of `contents`
myTbl.innerHTML = '<tr><td>'+k+'</td><td>'+s+'</td></tr>' + myTbl.innerHTML;
}
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
}
});
}
// load all previously saved items
window.onload = retrieveSavedInputs();
//clcik handeler for the btn
document.getElementById("myBtn").addEventListener('click', saveInput , false);
table{
margin-top:50px;
}
Class Year: <input type="text" id="klassYear" value=""/> <br>
Name: <input type="text" id="studentName" value=""/> <br>
<input type="button" id="myBtn" value="Submit" class="button" />
<br> Add a ame and year above and see it added to the list below
<div id="myDiv"></div>
<table width="400" border="1">
<thead>
<tr>
<th scope="col">Class Year</th>
<th scope="col">Student Name</th>
</tr>
</thead>
<tbody id="mytbl">
</tbody>
</table> Class Year: <input type="text" id="klassYear" value=""/> <br>
Name: <input type="text" id="studentName" value=""/> <br>
<input type="button" id="myBtn" value="Submit" class="button" />
<br> Add a ame and year above and see it added to the list below
<div id="myDiv"></div>
<table width="400" border="1">
<thead>
<tr>
<th scope="col">Class Year</th>
<th scope="col">Student Name</th>
</tr>
</thead>
<tbody id="mytbl">
</tbody>
</table>

Related

Javascript document.getElementById function not returning checkbox value to HTML form

I have been searching for an answer everywhere but just can not find what I need.
I have a webpage that has an HTML table on the left column and an HTML form on the right column. When I click on a row in the table on the left I want it to display the values in the form on the right.
I have this working perfectly for the text fields on the form, but not for the two checkboxes. My javascript will return either true or false or checked and unchecked to the document.getElementById within the script itself by using alert(); but I have no idea what it needs to allow the checkboxes to display these values. I thought the document.getElementById would return the values but it seems it does not.
I have tried all kinds of conveluted ways to get this to work but can not seem to get the correct code needed.
I am new to all this so there is most likely something really simple I am missing.
This is the HTML form code:
<div class="column right">
<table>
<tr></tr>
<tr>
<div class="lockinv">
<form autocomplete="off" name="lockform" class="keyassign" action="includes/lockinventory.inc.php"
method="post">
<label id="inventory" for="locknum">Lock Number</label>
<input id="invlocknum" type="text" name="locknum" value="" required>
<label id="inventory" for="locktype">Lock Type</label>
<input id="invlocktype" type="text" name="locktype" value="" required>
<label id="inventory" for="keycode">Key Code</label>
<input id="invkeycode" type="text" name="keycode" value="" required>
<label id="inventory" for="lockengraved">Lock Engraved</label>
<input id="invlockengraved" type="hidden" name="lockengraved" value="0">
<input id="invlockengraved" type="checkbox" name="lockengraved" value="1">
<label id="inventory" for="lockmastered">Lock Mastered</label>
<input id="invlockmastered" type="hidden" name="lockmastered" value="0">
<input id="invlockmastered" type="checkbox" name="lockmastered" value="1">
<label id="inventory" for="locknote">Lock Note</label>
<textarea id="inventorynote" name="locknote" rows="5" cols="60"></textarea>
<div class="wheel">
<?php
if (isset($_GET["error"])) {
if($_GET["error"] == "lockexists") {
echo "<p>Lock Already In Inventory!</p>";
}
else if ($_GET["error"] == "lockexistsfailed") {
echo "<p>Lock Already In Inventory!</p>";
}
}
?>
</div>
<input id="bt6" type="submit" name="submit" value="Save">
<button id="bt6" type="reset" name="button">Cancel</button>
</form>
</div>
</tr>
</table>
</div>
This is my JavaScript code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<script language="javascript"></script>
<script>
$(function () {
$('#lockTable td').click(function () {
var currentRow = $(this).closest("tr");
var locknum = currentRow.find("td:eq(0)").text();
var locktype = currentRow.find("td:eq(1)").text();
var keycode = currentRow.find("td:eq(2)").text();
var engraved = currentRow.find("td:eq(3)").find(":checkbox");
var mastered = currentRow.find("td:eq(4)").find(":checkbox");
var locknote = currentRow.find("td:eq(5)").text();
var lockengraved = engraved.prop("checked");
if (lockengraved === true) {
$grved = "checked";
} else {
$grved = "unchecked";
}
var lockmastered = mastered.prop("checked");
if (lockmastered === true) {
$msted = "checked";
} else {
$msted = "unchecked";
}
document.getElementById('invlocknum').value = locknum;
document.getElementById('invlocktype').value = locktype;
document.getElementById('invkeycode').value = keycode;
document.getElementById("invlockengraved").value = $grved;
document.getElementById('invlockmastered').value = $msted;
document.getElementById('inventorynote').value = locknote;
alert(document.getElementById("invlockengraved").value);
alert(document.getElementById("invlockmastered").value);
});
});
</script>
<p id="invlocknum"></p>
<p id="invlocktype"></p>
<p id="invkeycode"></p>
<p id="invlockengraved"></p>
<p id="invlockmastered"></p>
<p id="invlocknote"></p>
<p id="info"></p>
<p id="result"></p>
I found the answer to my issue. I had to modify my if statement in the Javascript to the following. Works the way I want it to. Thanks to all that helped.
var lockengraved = engraved.prop("checked");
if (lockengraved === true) {
document.getElementById("invlockengraved").checked = lockengraved;
}else if (lockengraved === false) {
document.getElementById("invlockengraved").checked = lockengraved;
}

How to make a dropdown autocomplete navigable by keyboard

Here, I have a nice autocomplete dropdown that, given a city typed by the user, the page will show all possible city-state-country triplets. For example the name Guadalajara would suggest
Guadalajara de Buga, Valle del Cauca Department, Colombia
Guadalajara, Castilla La Mancha, Spain
and
Guadalajara, Jalisco, Mexico
The code works perfectly from both the backend and the frontend, the only problem left is that the autosuggest drop down menu will only work with the mouse and not with the keyboard. The Up and Down arrow keys will not allow to navigate through the most appropriate choice and pressing esc doesn't cancel the menu.
I tried everything and I have no idea about what is missing to make this work with the keyboard as well. I would like to find a solution with pure vanilla JavaScript and that would involve the least possible changes in the rest of working code. Here the entire code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Vanilla Javascript Cities Test</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma#0.8.2/css/bulma.min.css">
</head>
<body id="body">
<div class="title has-text-centered" id="main"></div>
<section id="form" class="section" onclick="clearCities()">
<div class="container">
<h1 class="title">Vanilla Cities Javascript</h1>
<!-- Row for City, State and Country -->
<div id="location">
<div class="field">
<div class="control">
<div id="cities-dropdown" class="dropdown">
<div class="dropdown-trigger">
<input name="cities" id="cities" onkeyup="getCities()" maxlength="50" class="input" type="text" placeholder="Enter a city" aria-haspopup="true" aria-controls="dropdown-menu3" -autocomplete="off" required
>
</div>
<div class="dropdown-menu" id="dropdown-menu3" role="menu">
<div id="cities-dropdown-content" class="dropdown-content">
<!-- content -->
<a class="dropdown-item"></a>
</div>
</div>
</div> Clear
</div>
<span class="is-size-7 has-text-info">(If your location doesn't appear immediately, try to type slower).</span>
</div>
<!-- City Field -->
<div class="field">
<div class="control">
<input name="city" id="city" class="input" type="text" placeholder="City" required>
</div>
</div>
<!-- State Field -->
<div class="field">
<div class="control">
<input name="state" id="state" class="input" type="text" placeholder="State" required>
</div>
</div>
<!-- Country Field -->
<div class="field">
<div class="control">
<input name="country" id="country" class="input" type="text" placeholder="Country" required>
</div>
</div>
</div>
</div>
</section>
</body>
<script>
function getCities(){
var inputCity = document.getElementById('cities').value;
const city = changeCase(inputCity);
if(city.length <= 2){
return false;
}
// Create request to get cities locations
var request = new XMLHttpRequest();
request.addEventListener("load", transferComplete);
request.open("GET", "/cities/?cityname=" + city);
request.send();
// Called when transfer is complete
function transferComplete(event){
//alert(event.srcElement.response);
locations = JSON.parse(event.srcElement.response);
// Return false if no matching city was found
if(locations.length == 0){
return false;
}
// Append choices
dropContent = document.getElementById('cities-dropdown-content');
dropContent.innerHTML = "";
for (var i = 0; i < locations.length; i++) {
var link = document.createElement("a");
link.setAttribute("onclick", "setCity(" + JSON.stringify(locations[i].name) + "," + JSON.stringify(locations[i].state) + "," + JSON.stringify(locations[i].country) + ")");
link.setAttribute("class", "dropdown-item");
link.innerHTML = locations[i].name + ", " + locations[i].state.name + ", " + locations[i].country.name
dropContent.append(link);
}
document.getElementById("cities-dropdown").classList.add("is-active");
}
// document.getElementById("products-list").innerHTML = html;
}
function setCity(city, state, country){
document.getElementById('cities').value = city+', '+state.name+', '+country.name;
document.getElementById('city').value = city;
document.getElementById('state').value = state.name;
document.getElementById('country').value = country.name;
document.getElementById('cities-dropdown-content').innerHTML = "";
document.getElementById("cities-dropdown").classList.remove("is-active");
}
function clearCities(){
document.getElementById('cities-dropdown-content').innerHTML = "";
document.getElementById("cities-dropdown").classList.remove("is-active");
}
function deleteEntry(e){
e.preventDefault();
document.getElementById('cities').value = '';
}
function changeCase(inputCity){
return inputCity
.replace(/([a-z])([A-Z])/g, function (allMatches, firstMatch, secondMatch) {
return firstMatch + " " + secondMatch;
})
.toLowerCase()
.replace(/([ -_]|^)(.)/g, function (allMatches, firstMatch, secondMatch) {
return (firstMatch ? " " : "") + secondMatch.toUpperCase();
}
);
}
var eraser = document.getElementById("clear");
eraser.addEventListener('click', deleteEntry);
</script>
I hope to find the simpler and least invasive solution to complete a code that just have this left.
I would change your dropdown and input to the semantic html datalist element:
<label for="ice-cream-choice">Choose a flavor:</label>
<input list="ice-cream-flavors" id="ice-cream-choice" name="ice-cream-choice" />
<datalist id="ice-cream-flavors">
<option value="Chocolate">
<option value="Coconut">
<option value="Mint">
<option value="Strawberry">
<option value="Vanilla">
</datalist>
Then both search and keyboard accessibility should work more or less out of the box.
If you really don't want to do that, you have to attach event listeners (vanilla js) to the different elements of your dropdown and input field and write a rather long thing to be able to tab or arrow key your way down and up and back into the search field. I would say it's too much work compared to the reward.
Better to use some time to css-animate the datalist so it behaves a bit smoother and style it neatly.

how to add one on name attribute with javascript?

I have a dynamic form section which I need the name attribute to be dynamic as well.
the number should always get +1 each time the user create a new section !
name="training**1**[institut]"
This is crucial to have a proper SQL insert ... otherwise the array won't have a classical database logics !
JSFIDDLE here
Any idea ? thanks a lot from France !
<form method="post" action="">
<!-- INFO SECTION -->
<div id="infos">
<h2>Infos personnelles</h2>
<input placeholder="Prénom">
<input placeholder="Nom">
</div>
<!-- TRAINING SECTION -->
<div id="training">
<h2>Formation</h2>
<!-- Template -->
<div id="new-training" style="display:none">
<div>
</br>
<p></p>
<input id="mytext" type="text" name="training[1][institut]" placeholder="Diplôme" value="">
<input name="training[1][institut]" placeholder="Institut">
</div>
</div>
</div>
<p id="addnew">
+ Ajouter une formation
</p>
<p>
<br>
<input type="submit" value="Sauvergarder" name="submit">
</p>
</form>
<script> // 1st : Enregistrer / supprimer une formation
var ct = 1;
function addTraining()
{
ct++;
var div1 = document.createElement('div');
div1.id = ct;
// link to delete extended form elements
var delLink = 'Supprimer cette formation';
div1.innerHTML = document.getElementById('new-training').innerHTML + delLink;
document.getElementById('training').appendChild(div1);
}
function removeTraining(eleId)
{
d = document;
var ele = d.getElementById(eleId);
var parentEle = d.getElementById('training');
parentEle.removeChild(ele);
}
The best solution (my opinion) is to use a simple templating engine
https://jsfiddle.net/nget5dq2/1/
Addition to your HTML:
<template id="new_el_template" hidden>
<div id="row-{cid}">
<input id="mytext-{cid}" type="text" name="training[{cid}][institut]" placeholder="Diplôme" value="">
<input name="training[{cid}][institut]" placeholder="Institut">
</div>
Supprimer cette formation
</template>
JS
var ct = 1;
function addTraining() {
ct++;
let div = document.createElement('div');
div.innerHTML = document.getElementById('new_el_template').innerHTML.replace(/\{cid\}/gi, ct);
document.getElementById('training').appendChild(div);
}
function removeTraining(eleId) {
document.getElementById('row-' + eleId).parentNode.remove();
}
And yes, you can go ahead and generate the initial element directly from the template.
write the name attribute this way you should get all the data from the form when u post it.
<input id="mytext" type="text" name="training[diploma][]" placeholder="Diplôme" value="">
<input name="training[institut][]" placeholder="Institut">
Here is a working example with comments added throughout..
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<form method="post" action="">
<!-- INFO SECTION -->
<div id="infos">
<h2>Infos personnelles</h2>
<input placeholder="Prénom">
<input placeholder="Nom">
</div>
<!-- TRAINING SECTION -->
<div id="training">
<h2>Formation</h2>
<!-- Template -->
<div id="new-training" >
<div>
</br>
<p></p>
<input id="mytext" type="text" name="training[1][institut]" placeholder="Diplôme" value="">
<input name="training[1][institut]" placeholder="Institut">
</div>
</div>
</div>
<p id="addnew">
<a style="color: blue" onclick="addTraining()">+ Ajouter une formation</a>
</p>
<p>
<br>
<input type="submit" value="Sauvergarder" name="submit">
</p>
</form>
</body>
<script>
const addTraining = () => {
//Get parent container to place new input into
const parent = document.getElementById('training');
//Create DIV to wrap around input elements
let div = document.createElement('div')
//Create new input with a unique name attribute
let newInput1 = document.createElement('input');
let newInput2 = document.createElement('input');
//You can get an array of all existing elements and add 1 to create a unique name for each
let num = parent.querySelectorAll('div').length + 1,
newName = 'training['+ num +'][institut]';
//Set name attribute
newInput1.setAttribute('name', newName);
newInput2.setAttribute('name', newName);
//Set other attributes you alreadt had
newInput1.setAttribute('placeholder', 'Diplôme');
newInput2.setAttribute('placeholder', 'Institut');
newInput1.setAttribute('id', 'myText');
newInput1.setAttribute('type', 'text');
//Append elements
parent.appendChild(div);
div.appendChild(newInput1);
div.appendChild(newInput2)
}
</script>
</html>

java script local storage stop working

Newbie here. Using html and Javascript. It was working until I added a side menu. I had it set up with the submit button inside the side menu under the download function. I only included code for the first few questions and answers. The image local storage work sometimes. I'm running it on notepad++ and with chrome.
function save() {
//question1
var question1 = document.getElementById("question1")
var correctanswer1 = document.getElementById("correctanswer1");
var incorrect11 = document.getElementById("incorrect11");
var incorrect12 = document.getElementById("incorrect12");
var incorrect13 = document.getElementById("incorrect13");
try {
//question1
localStorage.setItem("question1", question1.value);
sessionStorage.setItem("question1", question1.value);
localStorage.setItem("correctanswer1", correctanswer1.value);
sessionStorage.setItem("correctanswer1", correctanswer1.value);
localStorage.setItem("incorrect11", incorrect11.value);
sessionStorage.setItem("incorrect11", incorrect11.value);
localStorage.setItem("incorrect12", incorrect12.value);
sessionStorage.setItem("incorrect12", incorrect12.value);
localStorage.setItem("incorrect13", incorrect13.value);
sessionStorage.setItem("incorrect13", incorrect13.value);
//question 1
question1value = "";
correctanswer1value = "";
incorrect11.value = "";
incorrect12.value = "";
incorrect13.value = "";
} catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
console.log("Error: Local Storage limit exceeds.");
} else {
console.log("Error: Saving to local storage.");
}
}
}
<div id="sidebar">
<ul>
Top of Page
<p>Download </p>
<p>
Submit </ul>
</p>
</div>
<div class="center">
Enter Question 1:
<input type="text" id="question1" name="Question 1" size="40">
<br>
<br> Next, add a correct answer
<font color="#51096F"> FIRST </font> and then the incorrect answers for your question.
<br>
<p>
<input type="text" id="correctanswer1" name="correctanswer1" size="50" style="border:2px solid #660570">
</p>
<p>
<input type="text" id="incorrect11" name="incorrect11" size="50">
</p>
<p>
<input type="text" id="incorrect12" name="incorrect12" size="50">
</p>
<p>
<input type="text" id="incorrect13" name="incorrect13" size="50">
</p>
<br>
<img id="uploadPreview1" style="width: 100px; height: 100px;" />
<input id="uploadImage1" type="file" name="myPhoto1" onchange="PreviewImage1();" />
<script type="text/javascript">
function PreviewImage1() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadImage1").files[0]);
oFReader.onload = function(oFREvent) {
document.getElementById("uploadPreview1").src = oFREvent.target.result;
sessionStorage.setItem("image", oFREvent.target.result);
localStorage.setItem("image", oFREvent.target.result);
};
};
</script>
</div>

Credit Card Swipe in Javascript not working

I am using Javascript to get the credit card information from Magentic Strip Reader device. (I am using USB attached device)
I have written a code in HTML Javascript but it failed to run. I mean my page is on HTTPS when I connected the device after opening this page. The device lights turns to green which means this page is security proof.
But when I swipe the card it did not show nothing in the field. I also have a function to focus on the field. But I don't know whats wrong it, Please see my code below and give me any suggestions.
HTML:
<span style='required'>*</span> - Indicates required field.
<div class='fields'>Swiped Information</div>
<input type=text name='swiped' id='swiped'>
<div class='fields'>First Name</div>
<input type=text name='first_name' id='first_name'><span style='required'>*</span>
</div>
<div class='fields'>Last Name</div>
<input type=text name='last_name' id='last_name'><span style='required'>*</span>
</div>
<div class='fields'>Expiration</div>
<input type=text size=8 name='expiration' id='expiration'><span style='required'>*</span>(MMYY)
</div>
<div class='fields'>CVV Code</div>
<input type=text size=8 name='cvv' id='cvv'><span style='required'>*</span>
</div>
<div class='fields'>Credit Card Number</div>
<input type=text name='card' id='card'><span style='required'>*</span>
</div>
<hr>
<div class='buttons'></div>
<a onclick="readCard();" style="cursor:pointer; color:red;">Swipe Credit Card</a>
</div>
Javascript code:
<script type="text/javascript">
function readCard () {
document.getElementById('swiped').focus();
var card_data = document.getElementById('swiped').value;
if(card_data != ''){
var details1 = card_data.split("^");
var card_number = details1[0];
card_number = card_number.substring(2);
var names = details1[1].split("/");
var first_name = names[1];
var last_name = names[0];
var details2 = details1[2].split(";");
details2 = details2[1].split("=");
var exp_date = details2[1];
exp_date = exp_date.substring(0, exp_date.length - 1);
exp_date = exp_date.substring(2, 3) + "/" + exp_date.substring(0,2);
document.getElementById('card').value = card_number;
document.getElementById('first_name').value = first_name;
document.getElementById('last_name').value = last_name;
document.getElementById('expiration').value = exp_date;
}
}
</script>
If the swiper model is IDMB, then it is not encrypted but may be set to HID and not KBE (keyboard emulated). Are you able to swipe into a text editor, notepad? If not, you may be able to switch it from HID to KBE with MagTek's demo application.
http://www.magtek.com/support/software/demo_programs/usb_swipe_insert.asp

Categories