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
Related
I'm trying to run this code here, but i keep getting this error
ReferenceError: xmlHttp is not defined
at XMLHttpRequest.ChamadaJSON.xmlhttp.onreadystatechange
I've tried mostly everything but it just continues... Here's the code:
function ChamadaJSON(data) {
var xmlhttp = new XMLHttpRequest();
var url = "http://menuetec.esy.es/test3.php?data="+data;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var responseText = xmlHttp.responseText;
ConectaServidor(responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function ConectaServidor(response) {
var dados = JSON.parse(response);
var i;
var conteudo = "";
var conteudo2 = "";
var conteudo3 = "";
var conteudo4 = "";
for (i = 0; i < dados.length; i++)
{
conteudo += dados[i].tb02_cafe;
conteudo2 += dados[i].tb02_lanchedia;
conteudo3 += dados[i].tb02_almoco;
conteudo4 += dados[i].tb02_lanchenoite;
}
document.getElementById("cafe1").innerHTML = conteudo;
document.getElementById("lanche1").innerHTML = conteudo2;
document.getElementById("almoco1").innerHTML = conteudo3;
document.getElementById("lanchen1").innerHTML = conteudo4;
}}
What's wrong?
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();
}
So I'm studying for an exam and I only have a quick question that has been buggin me for a while. I use AJAX to obtain a XML file to parse it and insert its values into a select element. This is the code:
<html>
<head>
</head>
<body>
<button onclick="EnviaPedido()">Submeter</button>
<select id="select"></select>
<script type="text/javascript">
var xmlHttpObj;
function CreateXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
xmlHttpObj = new XMLHttpRequest()
}
else if (window.ActiveXObject) {
xmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP")
}
return xmlHttpObj;
}
function EnviaPedido() {
xmlHttpObj = CreateXmlHttpRequestObject();
xmlHttpObj.open("POST", "agenda.xml", true);
xmlHttpObj.onreadystatechange = ProcessaReposta;
xmlHttpObj.send();
}
function ProcessaReposta() {
if (xmlHttpObj.readyState == 4 && xmlHttpObj.status == 200) {
var response = xmlHttpObj.responseText;
var xmlDoc;
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(response, "text/xml");
} else {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(response);
}
var select = document.getElementById("select");
var centrosInvestigacao = xmlDoc.getElementsByTagName("centro_de_investigacao");
for(i = 0; i < centrosInvestigacao.length; i++) {
var option = document.createElement("option");
option.innerHTML = centrosInvestigacao[i].childNodes[1].textContent;
select.appendChild(option);
}
}
}
</script>
<body>
</html>
And this is the XML that is returned:
<FCT>
<centro_de_investigacao id="1">
<nome>GECAD</nome>
<local>ISEP</local>
<classificao>Muito bom</classificao>
</centro_de_investigacao>
<centro_de_investigacao id="2">
<nome>DEF</nome>
<local>ISEP</local>
<classificao>Bom</classificao>
</centro_de_investigacao>
<centro_de_investigacao id="3">
<nome>ABC</nome>
<local>FEUP</local>
<classificao>Muito mau</classificao>
</centro_de_investigacao>
</FCT>
So when I want to obtain the 'nome' field why do I have to use
option.innerHTML = centrosInvestigacao[i].childNodes[1].textContent;
instead of
option.innerHTML = centrosInvestigacao[i].childNodes[0].textContent;
I know it's probably a stupid question but it's starting to piss me off not knowing if this is the expected behaviour or if I'm somehow screwing this up.
Thanks.
I made a small snipset of the problem that also shows part of the answer. I would think that the encoding of the XML document you are parsing is "off", in that sence that the first element of your childNodes, is actually a textnode between the last quote of centro_de_investigacao> and the start tag of <nome.
If you check the snipset (you can play around with the index parameter for example), you would see that the first button doesn't need the index increase to 1, but can work as expected with the first element, nl the one at index 0.
So remove the whitespaces from your XML document, and you should be fine.
Whitespaces: tab, space, newline
// mocked, no real data
var xmlHttpObj;
function CreateXmlHttpRequestObject() {
function Mock() {
this.callready = function() {
this.readyState = 4;
this.status = 200;
this.statusMsg = "OK";
if (this.onreadystatechange && this.onreadystatechange.call) {
setTimeout(this.onreadystatechange.bind(this), 0);
}
};
this.open = function(methodType, url, async) {
var el = document.getElementById('dataXml-' + url.split('.')[0]),
content = el ? el.innerHTML : '';
if (typeof async === 'undefined' || async) {
// no action till send is executed
this.responseText = content;
this.responseXml = content;
return;
}
return content;
};
this.send = function(data) {
this.callready();
};
}
return new Mock();
}
function EnviaPedido(index, url) {
xmlHttpObj = CreateXmlHttpRequestObject();
xmlHttpObj.open("POST", url, true);
xmlHttpObj.onreadystatechange = ProcessaReposta.bind(this, index);
xmlHttpObj.send();
}
function ProcessaReposta(index, url) {
if (xmlHttpObj.readyState == 4 && xmlHttpObj.status == 200) {
var response = xmlHttpObj.responseText;
var xmlDoc;
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(response, "text/xml");
} else {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(response);
}
var select = document.getElementById("select");
var centrosInvestigacao = xmlDoc.getElementsByTagName("centro_de_investigacao");
select.options = [];
for (i = 0; i < centrosInvestigacao.length; i++) {
var option = new Option();
var item = centrosInvestigacao[i].childNodes[index];
option.text = item.textContent;
select.options[i] = option;
}
}
}
<template id="dataXml-agenda"><FCT><centro_de_investigacao id="1"><nome>GECAD</nome><local>ISEP</local><classificao>Muito bom</classificao></centro_de_investigacao><centro_de_investigacao id="2"><nome>DEF</nome><local>ISEP</local><classificao>Bom</classificao></centro_de_investigacao><centro_de_investigacao id="3"><nome>ABC</nome><local>FEUP</local><classificao>Muito mau</classificao></centro_de_investigacao></FCT></template>
<template id="dataXml-original-agenda"><FCT>
<centro_de_investigacao id="1">
<nome>GECAD</nome>
<local>ISEP</local>
<classificao>Muito bom</classificao>
</centro_de_investigacao>
<centro_de_investigacao id="2">
<nome>DEF</nome>
<local>ISEP</local>
<classificao>Bom</classificao>
</centro_de_investigacao>
<centro_de_investigacao id="3">
<nome>ABC</nome>
<local>FEUP</local>
<classificao>Muito mau</classificao>
</centro_de_investigacao>
</FCT></template>
<select id="select"></select>
<button id="btnGenerate" type="button" onclick="EnviaPedido(0, 'agenda.xml');">Get info</button>
<button id="btnGenerate" type="button" onclick="EnviaPedido(1, 'original-agenda.xml');">Get info false contentType</button>
So my problem in the code below is in the following if else if statement at the bottom:
1. the code in both of the if statements work perfect.
2. the issue is that when i run the code on one can be use.
if i do 2 separate if statements only the second one works.
if i do 1 if and one else if only the if statement works and the else if does nothing.
a little more info: what I'm trying to do is every time the function times out and loops through again it will check the if statements and if something changed to run the appropriate if clause.
PLEASE LET ME KNOW IF MORE INFO IS NEEDED.
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject()
{
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e)
{
xmlHttp = false;
}
}
else
{
try
{
xmlHttp = new XMLHttpRequest();
}catch(e)
{
xmlHttp = false;
}
}
if(!xmlHttp)
alert("cant create object");
else
return xmlHttp;
}
function process_search()
{
if(xmlHttp.readyState==0 || xmlHttp.readyState==4)
{
search_parameter = encodeURIComponent(document.getElementById("userInput").value);
search_type = encodeURIComponent(document.getElementById("userOptions").value);
xmlHttp.open("GET", "../pages/search_xml.php?search_parameter=" + search_parameter + "&search_type=" + search_type, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
{
setTimeout('process_search()',5000);
}
}
function handleServerResponse()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
xmlResponse = xmlHttp.responseXML;
root = xmlResponse.documentElement;
if(document.getElementsByTagName('find_users')) // FIND USERS
{
first_name = root.getElementsByTagName('first');
last_name = root.getElementsByTagName('last');
users = document.createElement('ul');
users.setAttribute("id", "usersFound");
document.getElementById("underInput").innerHTML = ""; //RESETS THE DIV BEFORE INSERTING DATA
for(var i=0; i< first_name.length; i++)
{
usersList = document.createElement('li');
t = document.createTextNode(first_name.item(i).firstChild.data + " - " + last_name.item(i).firstChild.data + "<br/>");
usersList.appendChild(t);
underInput = document.getElementById("underInput");
underInput.appendChild(usersList);
}
}else if(document.getElementsByTagName('find_config_item')) //FIND CONFIG ITEMS
{
item = root.getElementsByTagName('item');
desc = root.getElementsByTagName('description');
itemsList = document.createElement('ul');
itemsList.setAttribute("id", "itemsFound");
document.getElementById("underInput").innerHTML = ""; //RESETS THE DIV BEFORE INSERTING DATA
for(var i=0; i< item.length; i++)
{
itemList = document.createElement('li'); // CREATE LIST ITEM ELEMENT
t = document.createTextNode(item.item(i).firstChild.data + " - " + desc.item(i).firstChild.data + "<br/>");
itemList.appendChild(t);
underInput = document.getElementById("underInput");
underInput.appendChild(itemList);
}
}
setTimeout('process_search()', 5000);
}
else
{
alert("something is wrong");
}
}
}
You shouldn't really rely on try/catch for this use case. You can be fairly certain the XMLHttpRequest or a Mircrosoft.XMLHTTP object will exist so you could simplify your code to the following:
function createXmlHttpRequestObject () {
return window.XMLHttpRequest ? new XMLHttpRequest() : new XDomainRequest();
}
var xmlHttp = createXmlHttpRequestObject();
Let me know if you would like to see a non ternary version
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