JavaScript error with splitting string into array - javascript

I am running into an issue with splitting a string into an array. To help myself troubleshoot the problem, I included two alert() functions, but only one gets called. Therefore, I know that there is an issue splitting a string into an array (for a basic username/password check). Here is my JS code:
function check() {
var user = document.loginform.usr.value;
var pass = document.loginform.psw.value;
var valid = false;
var txt = new XMLHttpRequest();
var alltext = "";
var allLines = [];
var usrn = [];
var pswd = [];
txt.open("GET", "/c.txt", true);
alltext = txt.responseText;
allLines = alltext.split(/\r\n|\n/);
usrn = allLines[0].split(',');
alert("usrn split");
pswd = allLines[1].split(',');
alert("pswd split");
for (var i=0; i <usrn.length; i++) {
if ((user == usrn[i]) && (pass == pswd[i])) {
valid = true;
break;
}
}
if(valid) {
window.location = "test.html";
return false;
}else{
var div = document.getElementById("login");
div.innerHTML = '<font color="red" size=2><i>Invalid Username/Password!</i></font><br>' + div.innerHTML;
}
}
The file that contains the login credentials (c.txt) is as follows:
User1,User2
pass,password
When User1 enters his/her name into the form, the password should be "pass". However, the script gets stopped at "pswd = allLines[1].split(',');". Am I misunderstanding the lines array?
Any help is appreciated - thanks!

You need to either use a synchronous call by changing the line to
txt.open("GET", "/c.txt", false);
Or use the "onreadystatechange" event to get the response when the server returns it
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alltext = txt.responseText;
allLines = alltext.split(/\r\n|\n/);
usrn = allLines[0].split(',');
alert("usrn split");
pswd = allLines[1].split(',');
alert("pswd split");
for (var i=0; i <usrn.length; i++) {
if ((user == usrn[i]) && (pass == pswd[i])) {
valid = true;
break;
}
}
if(valid) {
window.location = "test.html";
return false;
}else{
var div = document.getElementById("login");
div.innerHTML = '<font color="red" size=2><i>Invalid Username/Password!</i></font><br>' + div.innerHTML;
}
}
}

You need to call txt.send(). Also it is async so txt.responseText will most likely be null.
You can use onreadystatechanged like so to ensure that txt.responseText has a value:
txt.onreadystatechange = function() {
if (txt.readyState == 4) { // 4 = DONE
alert(txt.responseText);
}
}

Okay - after fiddling with the code and doing some more research, I got a working script. This script takes data from a form and checks it against a file (c.txt). If the form entries match a username/password combination in c.txt, it takes you to another webpage.
function check() {
var user = document.loginform.usr.value;
var pass = document.loginform.psw.value;
var valid = false;
var txt;
if(window.XMLHttpRequest){
txt = new XMLHttpRequest();
}else{
txt = new ActiveXObject("Microsoft.XMLHTTP");
}
var allLines = [];
var usrn = [];
var pswd = [];
txt.onreadystatechange=function() {
if(txt.readyState==4 && txt.status==200){
var alltext = txt.responseText;
allLines = alltext.split(/\r\n|\n/);
usrn = allLines[0].split(',');
pswd = allLines[1].split(',');
for (var i=0; i <usrn.length; i++) {
if ((user == usrn[i]) && (pass == pswd[i])) {
valid = true;
break;
}
}
if(valid) {
window.location = "test.html";
return false;
}else{
var div = document.getElementById("login");
div.innerHTML = '<font color="red" size=2><i>Invalid Username/Password!</i></font><br>' + div.innerHTML;
}
}
}
txt.open("GET", "c.txt", false);
txt.send();
}

Related

Function won't return a value [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I'm making a password generator. Trying to implement pass-phrases.
The function loadFile(); won't return a value to my main function, generate();
I think I'm too close to the problem and can't logic it out. I could use some help. Thank you.
Test site: https://jf0.000webhostapp.com/passWordGenerator/
test.js source: https://jf0.000webhostapp.com/passWordGenerator/test.js
The source is getting kind of long, sorry.
//Main generate password function
function generatePassword(){
var x = document.getElementById("passOutput");
var p = document.getElementById("testP");
x.value = generate();
//Make sure they aren't using an insecure number of characters
checkMaxChars();
p.innerText = x.value;
}
//Generate a password. 3 passSets for customization, one for passphrase
function generate(){
var nL = document.getElementById("noLetters");
var nN = document.getElementById("noNumbers");
var nS = document.getElementById("noSymbols");
var pPK = document.getElementById("passWordPhrase");
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var numbers = "0123456789";
var symbols = "!##$%^&*()_+~`|}{[]:;?,.-='";
var maxChars = document.getElementById("maxCharControl").value;
var generatedPass = "";
var holdPass = "";
//Main loop
for(var i = 0;i < maxChars;i++){
//Pick random value for each passSet
var passSet1 = chars.charAt(Math.random() * chars.length);
var passSet2 = numbers.charAt(Math.random() * numbers.length);
var passSet3 = symbols.charAt(Math.random() * symbols.length);
//if a checkbox is selected, clear out that value
if(nL.checked == true){passSet1 = "";}
if(nN.checked == true){passSet2 = "";}
if(nS.checked == true){passSet3 = "";}
//Randomly select a set to be added to holdPass, or not if it is empty.
var r = Math.floor((Math.random() * 4) + 1);
if(r == 1){if (passSet1 == ""){i--}else{holdPass += passSet1;}}
if(r == 2){if (passSet2 == ""){i--}else{holdPass += passSet2;}}
if(r == 3){if (passSet3 == ""){i--}else{holdPass += passSet3;}}
if(r == 4){
if(pPK.checked == true){
//get the value from loadFile(); and apply it to passSet4, add that to holdPass.
}}
}
generatedPass = holdPass;
console.log("Max Characters:" + maxChars);
console.log("passSet1:" + passSet1);
console.log("passSet2:" + passSet2);
console.log("passSet3:" + passSet3);
console.log("Iteration:" + i);
console.log("Random Position:" + r);
console.log("Password:" + holdPass + "::::" + holdPass.length);
//return password
return generatedPass;
}
//Make sure they didn't select all the checkboxes
function checkBoxes(){
var nL = document.getElementById("noLetters");
var nN = document.getElementById("noNumbers");
var nS = document.getElementById("noSymbols");
var pP = document.getElementById("passWordPhrase");
var nA = document.getElementById("noticeArea");
var nT = document.getElementById("noticeAreaText");
if(nL.checked == true && nN.checked == true && nS.checked == true){
nL.checked = false;
nN.checked = false;
nS.checked = false;
nA.style.display = "block";
nT.innerHTML = "You cannot select all checkboxes at once.";
window.setTimeout(hideNotice,5000);
}
else{
nA.style.display = "none";
nT.innerHTML = "";
}
}
//make sure the max characters is greater than 8
function checkMaxChars(){
var maxChars = document.getElementById("maxCharControl").value;
var nA = document.getElementById("noticeArea");
var nT = document.getElementById("noticeAreaText");
var x = document.getElementById("passOutput");
console.log(maxChars);
if (maxChars < 8){
x.value = "";
nA.style.display = "block";
nT.innerHTML = "You cannot generate a password less than 8 characters in length for security reasons.";
window.setTimeout(hideNotice,7000);
}
}
//hides the notice area div once the message is completed
function hideNotice(){
var nA = document.getElementById("noticeArea");
var nT = document.getElementById("noticeAreaText");
nA.style.display = "none";
nT.innerHTML = "";
}
//Load file
function loadFile() {
var xhttp = new XMLHttpRequest();
var x;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
x = this.responseText;
parseResponse(x);
}
}
xhttp.open("GET", "wordList.csv", true);
xhttp.send();
return x;
}
//Format response
function parseResponse(x){
console.log("MADE IT HERE!");
var dS,sV1,rPos;
dS = x.split(",");
for(var i =0;i < dS.length;i++){
sV1 = dS[i];
}
x = sV1;
}
The results of an AJAX request will never be available until after the function that initiated it completes. You are attempting to return x before at the end of the function that initiates the request, which is before the AJAX request has finished.
You need to move that line into your AJAX success handler.
function loadFile() {
var xhttp = new XMLHttpRequest();
var x;
// The onreadystatechange callback function will execute
// at some future point after loadFile has completed, so
// you can only gain access to the AJAX result from within
// that function.
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
x = this.responseText;
parseResponse(x);
return x;
}
}
xhttp.open("GET", "wordList.csv", true);
xhttp.send();
}
Your xhttp request is opened asynchronously with the true in xhttp.open("GET", "wordList.csv", true); so x is returned before a value is assigned to it.
Edit: said synchronously instead of asynchronously because I am dumb

remove blank lines when uploading csv files angular

I got a csv-reader directive and let's user upload a csv file. I noticed that when I upload a file with spaces between words for example:
abc
abc
abc
abc
abc
this gets shown. I want to delete all the blank lines Not sure what to do.
var reader = new FileReader();
reader.onload = function(e) {
var contents = e.target.result;
var rows = contents.split('\n');
// Check if the last row is empty. This works
if(rows[rows.length-1] ===''){
rows.pop()
}
}
// this doesn't work for some reason. It doesn't detect the '' in the middle of the arrays.
for( var i=rows.length-1;i>0;i--){
if(rows[i] === ''){
rows.splice(i,1)
}
}
Try using Array.prototype.filter()
var rows = contents.split('\n').filter(function(str){
return str;
});
From what you have shown it looks like you want to check if each item in the csvModel is an empty string, rather than newValue
Something like:
for( var i=0 ;i< $scope.csvModel.length; i++){
if (csvModel[i] == "") {
$scope.csvModel.splice(i,1);
}
}
var text = [];
var target = $event.target || $event.srcElement;
var files = target.files;
if(Constants.validateHeaderAndRecordLengthFlag){
if(!this._fileUtil.isCSVFile(files[0])){
alert("Please import valid .csv file.");
this.fileReset();
}
}
var input = $event.target;
var reader = new FileReader();
reader.readAsText(input.files[0], 'UTF-8');
reader.onload = (data) => {
let csvData = reader.result;
let csvRecordsArray = csvData.split(/\r\n|\n/);
if (csvRecordsArray[csvRecordsArray.length - 1] === '') {
csvRecordsArray.pop();
}
var headerLength = -1;
if(Constants.isHeaderPresentFlag){
let headersRow = this._fileUtil.getHeaderArray(csvRecordsArray, Constants.tokenDelimeter);
headerLength = headersRow.length;
}
this.csvRecords = this._fileUtil.getDataRecordsArrayFromCSVFile(csvRecordsArray,
headerLength, Constants.validateHeaderAndRecordLengthFlag, Constants.tokenDelimeter);
if(this.csvRecords===null){
this.csvRecords=[];
}
else if(this.csvRecords!==null) {
if ((JSON.stringify(this.csvRecords[0])) === (JSON.stringify(this.csvFormate))) {
alert("format matches");
this.displayCsvContent = true;
for (let i = 0; i < this.csvRecords.length; i++) {
if (i !== 0) {
this.csvRecords[i].push(this.recordInsertedFlag);
}
}
}
else {
alert("format not matches");
}
}
if(this.csvRecords == null){
this.displayCsvContent=false;
//If control reached here it means csv file contains error, reset file.
this.fileReset();
}
};
reader.onerror = function () {
alert('Unable to read ' + input.files[0]);
};

Asynchronous execution of javascript code

I am studying javascript and json but I've some problems: I have a script that works with json but the performances of what I wrote aren't that good. The code works only if I do a debug step by step with firebug or other tools and that makes me think that the execution of the code (or a part of it ... the one that creates the table as you'll see) requires too much time so the browser stops it.
The code is:
var arrayCarte = [];
var arrayEntita = [];
var arraycardbyuser = [];
function displayArrayCards() {
var richiestaEntity = new XMLHttpRequest();
richiestaEntity.onreadystatechange = function() {
if(richiestaEntity.readyState == 4) {
var objectentityjson = {};
objectentityjson = JSON.parse(richiestaEntity.responseText);
arrayEntita = objectentityjson.cards;
}
}
richiestaEntity.open("GET", "danielericerca.json", true);
richiestaEntity.send(null);
for(i = 0; i < arrayEntita.length; i++) {
var vanityurla = arrayEntita[i].vanity_urls[0] + ".json";
var urlrichiesta = "http://m.airpim.com/public/vurl/";
var richiestaCards = new XMLHttpRequest();
richiestaCards.onreadystatechange = function() {
if(richiestaCards.readyState == 4) {
var objectcardjson = {};
objectcardjson = JSON.parse(richiestaCards.responseText);
for(j = 0; j < objectcardjson.cards.length; j++)
arrayCarte[j] = objectcardjson.cards[j].__guid__; //vettore che contiene i guid delle card
arraycardbyuser[i] = arrayCarte;
arrayCarte = [];
}
}
richiestaCards.open("GET", vanityurla, true);
richiestaCards.send(null);
}
var wrapper = document.getElementById('contenitoro');
wrapper.innerHTML = "";
var userTable = document.createElement('table');
for(u = 0; u < arrayEntita.length; u++) {
var userTr = document.createElement('tr');
var userTdcard = document.createElement('td');
var userTdinfo = document.createElement('td');
var br = document.createElement('br');
for(c = 0; c < arraycardbyuser[u].length; c++) {
var cardImg = document.createElement('img');
cardImg.src = "http://www.airpim.com/png/public/card/" + arraycardbyuser[u][c] + "?width=292";
cardImg.id = "immaginecard";
userTdcard.appendChild(br);
userTdcard.appendChild(cardImg);
}
var userdivNome = document.createElement('div');
userdivNome.id = "diverso";
userTdinfo.appendChild(userdivNome);
var userdivVanity = document.createElement('div');
userdivVanity.id = "diverso";
userTdinfo.appendChild(userdivVanity);
var nome = "Nome: ";
var vanityurl = "Vanity Url: ";
userdivNome.innerHTML = nome + arrayEntita[u].__title__;
userdivVanity.innerHTML = vanityurl + arrayEntita[u].vanity_urls[0];
userTr.appendChild(userTdcard);
userTr.appendChild(userTdinfo);
userTable.appendChild(userTr);
}
wrapper.appendChild(userTable);
}
The problem is that the code that should make the table doesn't wait for the complete execution of the code that works with the json files. How can I fix it? I would prefer,if possible, to solve that problem with something easy, without jquery and callbacks (I am a beginner).
You'll have to move som code around to make that work. at first, split it up in some functions, then it is easier to work with. I dont know if it works, but the idea is that first it loads the arrayEntita. When that is done, it fills the other 2 arrays. And when the last array has been filled, it builds the table.
var arrayCarte = [];
var arrayEntita = [];
var arraycardbyuser = [];
function displayArrayCards() {
var richiestaEntity = new XMLHttpRequest();
richiestaEntity.onreadystatechange = function () {
if (richiestaEntity.readyState == 4) {
var objectentityjson = {};
objectentityjson = JSON.parse(richiestaEntity.responseText);
arrayEntita = objectentityjson.cards;
BuildArrayEntita();
}
}
richiestaEntity.open("GET", "danielericerca.json", true);
richiestaEntity.send(null);
}
function BuildArrayEntita() {
for (i = 0; i < arrayEntita.length; i++) {
var vanityurla = arrayEntita[i].vanity_urls[0] + ".json";
var urlrichiesta = "http://m.airpim.com/public/vurl/";
var richiestaCards = new XMLHttpRequest();
richiestaCards.onreadystatechange = function () {
if (richiestaCards.readyState == 4) {
var objectcardjson = {};
objectcardjson = JSON.parse(richiestaCards.responseText);
for (j = 0; j < objectcardjson.cards.length; j++)
arrayCarte[j] = objectcardjson.cards[j].__guid__; //vettore che contiene i guid delle card
arraycardbyuser[i] = arrayCarte;
arrayCarte = [];
//If it is the last call to populate arraycardbyuser, build the table:
if (i + 1 == arrayEntita.length)
BuildTable();
}
}
richiestaCards.open("GET", vanityurla, true);
richiestaCards.send(null);
}
}
function BuildTable() {
var wrapper = document.getElementById('contenitoro');
wrapper.innerHTML = "";
var userTable = document.createElement('table');
for (u = 0; u < arrayEntita.length; u++) {
var userTr = document.createElement('tr');
var userTdcard = document.createElement('td');
var userTdinfo = document.createElement('td');
var br = document.createElement('br');
for (c = 0; c < arraycardbyuser[u].length; c++) {
var cardImg = document.createElement('img');
cardImg.src = "http://www.airpim.com/png/public/card/" + arraycardbyuser[u][c] + "?width=292";
cardImg.id = "immaginecard";
userTdcard.appendChild(br);
userTdcard.appendChild(cardImg);
}
var userdivNome = document.createElement('div');
userdivNome.id = "diverso";
userTdinfo.appendChild(userdivNome);
var userdivVanity = document.createElement('div');
userdivVanity.id = "diverso";
userTdinfo.appendChild(userdivVanity);
var nome = "Nome: ";
var vanityurl = "Vanity Url: ";
userdivNome.innerHTML = nome + arrayEntita[u].__title__;
userdivVanity.innerHTML = vanityurl + arrayEntita[u].vanity_urls[0];
userTr.appendChild(userTdcard);
userTr.appendChild(userTdinfo);
userTable.appendChild(userTr);
}
wrapper.appendChild(userTable);
}
i dont know if this check:
if (i + 1 == arrayEntita.length)
BuildTable();
but else you have to check if alle responseses have returned before executing buildtable();
AJAX requests are asynchronous. They arrive at an unknown period during execution and JavaScript does not wait for the server to reply before proceeding. There is synchronous XHR but it's not for ideal use. You'd lose the whole idea of AJAX if you do so.
What is usually done is to pass in a "callback" - a function that is executed sometime later, depending on when you want it executed. In your case, you want the table to be generated after you receive the data:
function getData(callback){
//AJAX setup
var richiestaEntity = new XMLHttpRequest();
//listen for readystatechange
richiestaEntity.onreadystatechange = function() {
//listen for state 4 and ok status (200)
if (richiestaEntity.readyState === 4 && richiestaEntity.status === 200) {
//execute callback when data is received passing it
//what "this" is in the callback function, as well as
//the returned data
callback.call(this,richiestaEntity.responseText);
}
}
richiestaEntity.open("GET", "danielericerca.json"); //third parameter defaults to true
richiestaEntity.send();
}
function displayArrayCards() {
//this function passed to getData will be executed
//when data arrives
getData(function(returnedData){
//put here what you want to execute when getData receives the data
//"returnedData" variable inside this function is the JSON returned
});
}
As soon as you have made the ajax call, put all of the rest of the code inside the readystatechange function. This way, it will execute everything in order.
Edit: #Dappergoat has explained it better than I can.

jquery doesn't get loaded, if i don't reload page

This code works only if I reload/refresh page, otherwise it doesn't work, I susspect issue is, because I use Jquery + normal javascript.
I have form and there is input which uses autocomplete, but while you go trough form next, it doesn't work.
The point is that input with #SchoolName isn't on first page is on 2nd page (after showcart(); function is trigered)...
Anyone have any ideas why my jquery code doesn't load properly?
I have this code:
<script type="text/javascript" language="javascript">
function autocomplete() {
$("#SchoolName").autocomplete("ajaxFuncs.php", {
cacheLength:1,
mustMatch:1,
extraParams: {getSchoolName:1}
});
};
$(document).ready(function(){
setTimeout("autocomplete()", 500);
});
function showVal(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "* Please type in School Name.";
return;
}
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) { // break this into 2 statements so you can handle HTTP errors
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
} else {
document.getElementById("txtHint").innerHTML = "AJAX Error (HTTP "+xmlhttp.status+")";
}
}
}; // functions declared in this way should be followed by a semi colon, since the function declaration is actually a statement.
// encodeURIComponent() does all the escaping work for you - it is roughly analogous to PHP's urlencode()
// xmlhttp.open("GET","ajaxFuncs2.php?q="+encodeURIComponent(str),true);
xmlhttp.open("GET","ajaxFuncs2.php?q="+encodeURIComponent(str),true);
xmlhttp.send();
}
</script>
<script>
function ajax(doc)
{
doc = null;
if (window.XMLHttpRequest) {
try {
doc = new XMLHttpRequest();
}
catch(e) {
if(SBDebug)
alert("Ajax interface creation failure 1");
}
}
else if (window.ActiveXObject) {
try {
doc = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
try {
doc = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
if(SBDebug)
alert("Ajax interface creation failure 2");
}
}
}
return doc;
}
function postIt(params) {
var doc;
// alert("postIt: " + params);
if(params == "")
params = "nada=0";
doc = ajax(doc);
if (doc) {
var url = window.location.href;
url = url.substr(0, url.lastIndexOf("/") + 1) + "clientCartPost.php";
// alert(url);
doc.open("POST", url, false);
//Send the proper header information along with the request
doc.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
doc.setRequestHeader("Content-length", params.length);
doc.setRequestHeader("Connection", "close");
document.body.style.cursor = "wait";
doc.send(params);
document.body.style.cursor = "default";
if(doc.responseText == "timeout") {
alert("Timed out");
document.location = "index.php";
}
return doc.responseText;
}
return "Connection Failed";
}
function saveCC() {
var doc;
doc = ajax(doc);
if(params == "")
params = "nada=0";
if (doc) {
var params = "";
var eVisi = document.getElementById("visiCard");
var eCard = document.getElementById("x_card_num");
if(eVisi.value.indexOf("*") < 0)
eCard.value = eVisi.value;
for(i=0; i<document.CC.elements.length; i++) {
if(document.CC.elements[i].name == "visiCard")
continue;
params += getElemValue(document.CC.elements[i]) + "&";
}
doc.open("POST", "https://dot.precisehire.com/clientCartStoreCard.php", false);
//Send the proper header information along with the request
doc.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
doc.setRequestHeader("Content-length", params.length);
doc.setRequestHeader("Connection", "close");
document.body.style.cursor = "wait";
doc.send(params);
document.body.style.cursor = "default";
// alert(doc.responseText);
return true;
}
return false;
}
function getElemValue(item)
{
// alert("Getting: " + itemBase + itemID);
// alert(itemBase + "" + itemID);
if(item.type == "radio" || item.type == "checkbox")
{
if(!item.checked)
return "";
}
if(item.type == "select-one")
{
value = item.options[item.selectedIndex].value;
}
else
value = item.value;
return item.name + "=" + escape(value) + "&";
}
function makePie()
{
var contents = postIt("command=getProgress");
document.getElementById("step2").className = "bx2";
document.getElementById("step3").className = "bx2";
document.getElementById("step4").className = "bx2";
if(contents > 0)
document.getElementById("step2").className = "bx1";
if(contents > 1)
document.getElementById("step3").className = "bx1";
if(contents > 2)
document.getElementById("step4").className = "bx1";
}
var gbColor;
function RedIn(start)
{
var id;
if(start)
gbColor = 0;
gbColor += 32;
if(gbColor > 255)
gbColor = 255;
id = 0;
var obj = document.getElementById("red" + id);
while(obj != undefined)
{
obj.style.backgroundColor = 'rgb(255,' + gbColor + ',' + gbColor + ')';
id++;
obj = document.getElementById("red" + id);
}
if(gbColor < 255 && id > 0)
setTimeout("RedIn(0)", 100);
}
function showCart(next)
{
var ca = document.getElementById("cartArea");
var params = "";
for(i=0; i<document.clientCart.elements.length; i++)
{
param = getElemValue(document.clientCart.elements[i]);
if(param != "")
params += param + "&";
}
if(next)
params += "Next=1";
// alert(params);
ca.innerHTML = postIt(params);
makePie();
// RedIn(1);
}
function tabIfComplete(formField, maxSize, nextField, e)
{
if(window.event) // IE
{
keynum = e.keyCode;
}
else if(e.which) // Netscape/Firefox/Opera
{
keynum = e.which;
}
if(keynum < 48)
return;
if(formField.value.length >= maxSize)
{
var nf = document.getElementById(nextField);
if(nf)
nf.focus();
}
}
function sendCommand(command)
{
var ca = document.getElementById("cartArea");
var params = "command=" + command;
var submitOrder = command.indexOf('submitOrder') >= 0;
// alert(command);
if(submitOrder)
{
if(document.getElementById("RESULT").checked)
{
params += "&postSettlement=result";
/*
n = postIt(params);
alert(nOID);
if(nOID > 0)
document.location="orderreview.php?id=" + nOID;
return;
*/
}
else if(document.getElementById("REPORT").checked)
{
params += "&postSettlement=report";
}
else if(document.getElementById("DUPEORDER").checked)
{
params += "&postSettlement=dupeorder";
}
postIt(params);
document.location="cart.php";
return;
}
else if(command.indexOf('priorSearches') >= 0)
{
document.location="orderreview.php?ssnlist=1";
}
else if(command.indexOf('addState') >= 0)
{
for(i=0; i<document.clientCart.elements.length; i++)
{
if(document.clientCart.elements[i].name != "Next")
params += "&" + getElemValue(document.clientCart.elements[i]);
}
}
ca.innerHTML = postIt(params);
makePie();
}
function doReset()
{
var ca = document.getElementById("cartArea");
ca.innerHTML = "";
ca.innerHTML = postIt("reset=1");
makePie();
}
function dupeOrder()
{
var ca = document.getElementById("cartArea");
ca.innerHTML = "";
ca.innerHTML = postIt("dupeOrder=1");
makePie();
}
function resetCart()
{
if(confirm("Empty current cart and start over? Are you Sure?"))
doReset();
}
function saveCart()
{
var ca = document.getElementById("cartArea");
var params = "";
for(i=0; i<document.clientCart.elements.length; i++)
{
params += getElemValue(document.clientCart.elements[i]) + "&";
}
params += "saveExit=1";
ca.innerHTML = postIt(params);
makePie();
RedIn(1);
}
function deleteOrderItem(command)
{
if(!confirm("Delete this search? Are you Sure?"))
return;
var ca = document.getElementById("cartArea");
var params = "command=" + command;
ca.innerHTML = postIt(params);
makePie();
}
// alert("Reloaded");
setTimeout("showCart();", 100);
</script>
Try to move the last line:
setTimeout("showCart();", 100);
...into the $.ready-function:
$(document).ready(function(){
setTimeout("autocomplete()", 500);
});
Otherwise it may happen that showCart() gets called before the elements you access in showCart() are known.
First: Combining jQuery + regular javascript is not a problem -- jquery is made of regular javascript.
Secondly, when you're passing a method into your callback param anything, you can usually just write the name of the method:
$(document).ready(function(){
setTimeout(autocomplete, 500);
});
Third, the issue of using XMLHttpRequest while also using jquery. Jquery has a version of the XHR that is even more cross browser compliant than that is, you should use it:
$.ajax()
Finally, please add an include to the actual jquery file at the beginning of your code..
<script type="text/javascript" src="jquery.js"></script>
Sorry to say, while formatting your code its really pain to do.
I have seen some of issue right now:-
function autocomplete() { first this function has improver closing }; with semi-colon
Below is the repeatitive code:-
//Send the proper header information along with the request
doc.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
doc.setRequestHeader("Content-length", params.length);
doc.setRequestHeader("Connection", "close");
document.body.style.cursor = "wait";
doc.send(params);
document.body.style.cursor = "default";</li>
This you can make into a single function call by passing proper parameters.
3.If you are using JQuery then XMLHttpRequest is not required
4.Yet to update...
Open up a javascript console (Ctrl-Shift-J) in Firefox/Chrome and look in the menu bar for other browsers and see what errors show up

Reading xml document in firefox

I am trying to read customers.xml using javascript.
My professor has taught us to read xml using `ActiveXObjectand he has given us an assignment to create a sample login page which checks username and password by reading customers.xml.
I am trying to use DOMParser so that it works with firefox.
But when I click on Login button I get this error.
Error: syntax error Source File:
file:///C:/Users/Searock/Desktop/home/project/project/login.html
Line: 1, Column: 1 Source Code:
customers.xml
Here's my code.
login.js
var xmlDoc = 0;
function checkUser()
{
var user = document.login.txtLogin.value;
var pass = document.login.txtPass.value;
//xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
/*
xmlDoc = document.implementation.createDocument("","",null);
xmlDoc.async = "false";
xmlDoc.onreadystatechange = redirectUser;
xmlDoc.load("customers.xml");
*/
var parser = new DOMParser();
xmlDoc = parser.parseFromString("customers.xml", "text/xml");
alert(xmlDoc.documentElement.nodeName);
xmlDoc.async = "false";
xmlDoc.onreadystatechange = redirectUser;
}
function redirectUser()
{
alert('');
var user = document.login.txtLogin.value;
var pass = document.login.txtPass.value;
var log = 0;
if(xmlDoc.readyState == 4)
{
xmlObj = xmlDoc.documentElement;
var len = xmlObj.childNodes.length;
for(i = 0; i < len; i++)
{
var nodeElement = xmlObj.childNodes[i];
var userXml = nodeElement.childNodes[0].firstChild.nodeValue;
var passXml = nodeElement.childNodes[1].firstChild.nodeValue;
var idXML = nodeElement.attributes[0].value
if(userXml == user && passXml == pass)
{
log = 1;
document.cookie = escape(idXML);
document.login.submit();
}
}
}
if(log == 0)
{
var divErr = document.getElementById('Error');
divErr.innerHTML = "<b>Login Failed</b>";
}
}
customers.xml
<?xml version="1.0" encoding="UTF-8"?>
<customers>
<customer custid="CU101">
<user>jack</user>
<pwd>PW101</pwd>
<email>jack#rediff.com</email>
</customer>
<customer custid="CU102">
<user>jill</user>
<pwd>PW102</pwd>
<email>jill#rediff.com</email>
</customer>
<customer custid="CU103">
<user>john</user>
<pwd>PW103</pwd>
<email>john#rediff.com</email>
</customer>
<customer custid="CU104">
<user>jeff</user>
<pwd>PW104</pwd>
<email>jeff#rediff.com</email>
</customer>
</customers>
I get parsererror message on line alert(xmlDoc.documentElement.nodeName);
I don't know what's wrong with my code. Can some one point me in a right direction?
Edit :
Ok, I found a solution.
var xmlDoc = 0;
var xhttp = 0;
function checkUser()
{
var user = document.login.txtLogin.value;
var pass = document.login.txtPass.value;
var err = "";
if(user == "" || pass == "")
{
if(user == "")
{
alert("Enter user name");
}
if(pass == "")
{
alert("Enter Password");
}
return;
}
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else // IE 5/6
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = redirectUser;
xhttp.open("GET","customers.xml",true);
xhttp.send();
}
function redirectUser()
{
var log = 2;
var user = document.login.txtLogin.value;
var pass = document.login.txtPass.value;
if (xhttp.readyState == 4)
{
log = 0;
xmlDoc = xhttp.responseXML;
var xmlUsers = xmlDoc.getElementsByTagName('user');
var xmlPasswords = xmlDoc.getElementsByTagName('pwd');
var userLen = xmlDoc.getElementsByTagName('customer').length;
var xmlCustomers = xmlDoc.getElementsByTagName('customer');
for (var i = 0; i < userLen; i++)
{
var xmlUser = xmlUsers[i].childNodes[0].nodeValue;
var xmlPass = xmlPasswords[i].childNodes[0].nodeValue;
var xmlId = xmlCustomers.item(i).attributes[0].nodeValue;
if(xmlUser == user && xmlPass == pass)
{
log = 1;
document.cookie = xmlId;
document.login.submit();
break;
}
}
}
if(log == 0)
{
alert("Login failed");
}
}
Thanks.
parseFromString is parsing the string "customer.xml" in your case, because the first argument needs to be a string containing the actual content of the XML document and not its name.
You can use something like this to get the xml file:
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else // IE 5/6
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET","customer.xml",false);
xhttp.send();
xmlDoc=xhttp.responseXML;
Source

Categories

Resources