Two callback functions are being executed in custom AJAX function - javascript

I have created a custom GET and POST function in javascript to handle my AJAX requests. When I try to make a call, fail callback is executed first and then the done callback. The response from AJAX is a valid JSON string and I do not understand why this is happening. Only done callback must be executed if the response is valid JSON.
get('ajax/autocomplete.php', {q: q}, function(data) {
//done, executed second
}, aww());//Error, executed first
function get() {
var data,
done,
fail,
done_index = null,
str = '',
ajax = new XMLHttpRequest(),
url = arguments[0];
for(var i=0; i<arguments.length; i++) {
if(typeof arguments[i] == 'object') {
data = arguments[i];
for(var key in data) {
if(str != "") str += "&";
str += key + "=" + encodeURIComponent(data[key]);
}
if(str != '') url += '?';
} else if(typeof arguments[i] == 'function') {
if(!done_index) {
done = arguments[i];
done_index = i;
}
if(i != done_index) {
fail = arguments[i];
}
}
}
ajax.onreadystatechange = function() {
console.log(ajax.readyState, ajax.status);
if(ajax.readyState === XMLHttpRequest.DONE && ajax.status === 200) {
var response = ajax.responseText;//treat empty response as valid JSON
if(response.length == 0) response = '""';
try {
var json = JSON.parse(response);
return (done) ? done(json) : false;
} catch(e) {
console.log(e);
return (fail) ? fail() : false;
}
}
};
ajax.open('get', url + str);
ajax.send();
}

You're calling the aww() function in the argument list to get(), because you have parentheses after it. You should just pass a reference to the function. It should be:
get('ajax/autocomplete.php', {q: q}, function(data) {
}, aww);

Related

Extracting value from Promise [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How can I access the value of a promise?
(14 answers)
How do I promisify native XHR?
(6 answers)
Closed 9 days ago.
I am trying to extract value from a Promise. I am able to print the result before it gets returned in a Promise.
function countTotalInvItem() {
var params = 'service=shopping&request=getshopitems&mode=count';
var jsonRes = xmlHttpSend(params).then((value) => {
if (value instanceof Promise) {
console.log('Promise found');
} else {
console.log('Promise NOT');
if (value != null) {
console.log('Value: ' + value);
} else {
console.log('NULL value');
}
}
});
}
async function xmlHttpSend(params) {
let myPromise = new Promise(function (resolve) {
var xhr = new XMLHttpRequest();
var url = 'portal?' + params;
xhr.onreadystatechange = function (response) {
if (xhr.readyState == 4 && xhr.status == 200) {
var rs = parseReturn(xhr.responseText);
console.log('ResultSet >>> ' + rs.toString());
if (
rs.success === 'true' &&
rs.resultPayloadType === 'json' &&
rs.result !== null
) {
console.log('Parsing JSON ...');
var json = JSON.parse(rs.result);
if (json === null) {
console.log('NO JSON RESULT !!!');
} else {
console.log('JSON Result Parsed: ' + json[0].count);
}
resolve(json);
} else {
console.log('RS has ERROR !!!');
resolve(null);
}
}
};
xhr.open('GET', url, true);
xhr.send();
});
}
function parseReturn(input) {
var kvArrays1 = input.split('&');
var service = null;
var sessionID = null;
var success = false;
var errorCode = -1;
var resultEncoding = null;
var resultPayloadType = null;
var result = null;
if (kvArrays1.length > 0) {
for (let i = 0; i < kvArrays1.length; i++) {
if (kvArrays1[i] != null) {
var kvArrays2 = kvArrays1[i].split('=');
if (kvArrays2 != null) {
switch (kvArrays2[0]) {
case 'service':
if (kvArrays2.length == 2) {
service = kvArrays2[1];
}
break;
case 'sessionID':
if (kvArrays2.length == 2) {
sessionID = kvArrays2[1];
}
break;
case 'success':
if (kvArrays2.length == 2) {
success = kvArrays2[1];
}
break;
case 'errorCode':
if (kvArrays2.length == 2) {
errorCode = kvArrays2[1];
}
break;
case 'resultEncoding':
if (kvArrays2.length == 2) {
resultEncoding = kvArrays2[1];
}
break;
case 'resultPayloadType':
if (kvArrays2.length == 2) {
resultPayloadType = kvArrays2[1];
}
break;
case 'result':
if (kvArrays2.length >= 2) {
result = '';
for (let j = 1; j < kvArrays2.length; j++) {
if (kvArrays2[j] == '') {
result += '=';
} else {
result = kvArrays2[j];
}
}
}
break;
}
}
}
}
}
return new ResultSet(
service,
sessionID,
success,
errorCode,
resultEncoding,
resultPayloadType,
result
);
}
class ResultSet {
constructor(
service,
sessionID,
success,
errorCode,
resultEncoding,
resultPayloadType,
result
) {
this.service = service;
this.sessionID = sessionID;
this.success = success;
this.errorCode = errorCode;
this.resultEncoding = resultEncoding;
this.resultPayloadType = resultPayloadType;
if (result != null) {
if (result.length > 0) {
this.result = atob(result);
}
}
}
toString() {
return (
'service: ' +
this.service +
'; sessionID: ' +
this.sessionID +
'; success: ' +
this.success +
'; errorCode: ' +
this.errorCode +
'; resultEncoding: ' +
this.resultEncoding +
'; resultPayloadType: ' +
this.resultPayloadType +
'; result: ' +
this.result
);
}
}
<!DOCTYPE html>
<html>
<head>
<script>
</script>
</head>
<body>
<div id="demo">
<h2>Count Total Inventory Items</h2>
<button type="button" onclick="countTotalInvItem()">Count</button>
</div>
</body>
</html>
The output as the screenshot shows with the developer console opened.
I am able to receive the response and to print out the 'count' number from the JSON that is returned.
I am missing something to pass the JSON from 'xmlHttpSend' async function to the 'countTotalInvItem' and print it as a value (which should be value of '1') ?
Thanks.
I can't get that code to run properly to try to edit it, but your function xmlHttpSend does not return anything.
It declares a variable (myPromise) but does not use it. If you want this function to return a promise, you can just do:
return new Promise(function (resolve) {
instead of
let myPromise = new Promise(function (resolve) {
It is not necessary to declare xmlHttpSend as async since it returns a promise, the purpose of async is to avoid writing promises explicitly. You should also avoid using var as much as possible, it makes your code harder to understand because of the scope it gives to the variable.
It is the same thing for the != and == in your functions, you should try to use !== and === as much as possible as it is easier to understand and to debug

Nodejs + Q promise + method return based on url type

I am using node js for backend, also using q promise package.
Question : I am trying to get third party product details.
1. www.abcd.com 2. www.xyz.com - this method i handle in backend.
Possible url:
localhost:8080/search?type="abcd";
localhost:8080/search?type="xyz";
localhost:8080/search;
If the above URL type is abcd means need to search some different thridparty(www.abcd.com) http url;
If the above URL type is xyz means need to search some other different thridparty(www.xyz.com) http url
If the above URL didn't get type means need to search www.abcd.com if the result found means then return response, if result not found means need to call www.xyz.com url and then return response. (Note - here two third party api need to call)
Code:
router.get('/search', function(req, res, next) {
if (!( typeof req.query === 'undefined' || req.query === null || req.query == "")) {
var type = req.query;
}
var spec = {
resp : {}
};
Q(spec).then(function(spec) {
var deferred = Q.defer();
var optionsget = {
host : 'abcd.com',
method : 'GET'
};
var reqGet = https.request(optionsget, function(res) {
var getProductInfo = '';
res.on('data', function(d) {
getProductInfo += d;
});
res.on('end', function() {
if (( typeof message == 'undefined') && (!( typeof items === 'undefined' || items === null))) {
spec.resp.list = items;
deferred.resolve(spec);
} else {
spec.resp.message = message;
deferred.reject(spec);
}
});
});
reqGet.end();
reqGet.on('error', function(e) {
console.log(e);
deferred.reject(spec);
});
return deferred.promise;
}).then(function(spec) {
var deferred = Q.defer();
var optionsget = {
host : 'xyz.com',
method : 'GET'
};
var reqGet = https.request(optionsget, function(res) {
var getProductInfo = '';
res.on('data', function(d) {
getProductInfo += d;
});
res.on('end', function() {
if (( typeof message == 'undefined') && (!( typeof items === 'undefined' || items === null))) {
spec.resp.list = items;
deferred.resolve(spec);
} else {
spec.resp.message = message;
deferred.reject(spec);
}
});
});
reqGet.end();
reqGet.on('error', function(e) {
console.log(e);
deferred.reject(spec);
});
return deferred.promise;
}).then(function(spec) {
spec.resp.status = 'Success';
res.send(spec.resp);
}).fail(function(spec) {
spec.resp.status = 'Error';
res.send(spec.resp);
});
});
I this is chilly question. I understand need to check the type and implement. I thought we need to add some different function for both (abcd and xyz) then can call that method based on type.
Please suggest to good way.

Node JS Async Response

I wrote my 1st application in Node.js with MongoDB and I came across the situation where I need to have 2 db.collection.update statements depending on an IF/ELSE condition.
I am trying to return back the operation details in a resJSON JS object but seems like callback is executing before the db.collection.update statements are completed and the default value of resJSON is getting back in response each time.
detail code:
var url = require('url');
var fs = require('fs');
var async = require('async');
var passwordGen = require('../../lib/passwordGen');
var http = require("http");
var server = http.createServer();
server.on('request', request);
server.listen(8080,'127.0.0.1');
function request(request, response) {
var userData = '';
request.on('data', function(data)
{
userData += data;
});
request.on('end', function()
{
async.auto({
allProcess: function(callback){
var resJSON = {'inserted':0,'disabled':0,'error':''};
var jsonData = JSON.parse(userData);
if(jsonData.length > 0){
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:27017/test_db", function(err,db){
if(err) { return console.dir(err); }
var collection = db.collection('users');
var arrDisableRec = [];
for(i=0;i<jsonData.length;i++){
var action = jsonData[i]['action'].toLowerCase();
if(action == 'disable'){
arrDisableRec.push(jsonData[i]['email']);
}else{
var date = new Date();
var obj = {
'createdISO':date,
'created':date,
'updated':date,
'updatedISO':date,
'email':jsonData[i]['email'],
'firstName':jsonData[i]['firstname'],
'lastName':jsonData[i]['lastname'],
'password':passwordGen.getPassword(),
'enabled':true,
'active':true,
'downloaded':true,
'defaultServings':2,
'name':''
};
collection.update(
{'email':jsonData[i]['email']},
{$setOnInsert:obj},
{upsert: true},
function(err,numberAffected,rawResponse) {
if(typeof numberAffected.result.upserted != 'undefined'){
resJSON['inserted'] = resJSON['inserted'] + numberAffected.result.upserted.length;
}
if(typeof numberAffected.result.nModified != 'undefined'){
resJSON['disabled'] = resJSON['disabled'] + parseInt(numberAffected.result.nModified);
}
if(typeof numberAffected.result.writeError != 'undefined'){
resJSON['error'] ='Error Code:'+(numberAffected.result.writeError.code)+', '+numberAffected.result.writeError.errmsg;
}
console.log(resJSON); //shows correct values
}
);
}
if(arrDisableRec.length > 0){
collection.update(
{'email':{$in:arrDisableRec}},
{$set:{'enabled':false}},
{multi:true},
function(err,numberAffected,rawResponse) {
if(typeof numberAffected.result.upserted != 'undefined'){
resJSON['inserted'] = resJSON['inserted'] + numberAffected.result.upserted.length;
}
if(typeof numberAffected.result.nModified != 'undefined'){
resJSON['disabled'] = resJSON['disabled'] + parseInt(numberAffected.result.nModified);
}
if(typeof numberAffected.result.writeError != 'undefined'){
resJSON['error'] ='Error Code:'+(numberAffected.result.writeError.code)+', '+numberAffected.result.writeError.errmsg;
}
console.log(resJSON); //shows correct values
}
);
}
}
});
}
callback(resJSON);
}
},function(resJSON){
response.writeHead(200,{
'Content-Type': 'text/json'
});
response.end(JSON.stringify(resJSON)); //replies back with default resJSON only.
});
});
}
Any suggestions/directions please?
Thanks
You have to call the callback at then end of the callback chain.
For example
console.log(resJSON); //shows correct values
callback(null, resJSON);
you will have to make sure that every callback chain end point calls the callback. To handle the for loop you will have to have a mechanism to join all the end points of all the async calls done inside the for loop.
for example
if(err) {
return callback(err);
}
notice that I used the function callback(err, res) standard node prototype instead of your function callback(res)
better yet, use an async flow library like async or a promise library like bluebird
This is a counter solution for your issue. It should solve your case for now. Try reading async library. It will be very useful for later.
var counter = 0;
function commoncallback(err,numberAffected,rawResponse) {
if(typeof numberAffected.result.upserted != 'undefined'){
resJSON['inserted'] = resJSON['inserted'] + numberAffected.result.upserted.length;
}
if(typeof numberAffected.result.nModified != 'undefined'){
resJSON['disabled'] = resJSON['disabled'] + parseInt(numberAffected.result.nModified);
}
if(typeof numberAffected.result.writeError != 'undefined'){
resJSON['error'] ='Error Code:'+(numberAffected.result.writeError.code)+', '+numberAffected.result.writeError.errmsg;
}
console.log(resJSON); //shows correct values
counter --;
if(counter == 0) callback(resJSON); //call your main call back here
}
for (i=0; i<jsonData.length; i++) {
if(firstCase) {
counter ++;
collection.update({'email':{$in:arrDisableRec}},
{$set:{'enabled':false}},
{multi:true},commoncallback);
} else {
//another update action
counter++;
}
}

Javascript webworker won't load XML file via XMLHttpRequest

I'm am strugling to get a webworker to load an XML file from the same domain on the side of my main page, any help would be greatly appreciated.
function readXML(){
var xhr = new XMLHttpRequest(); //Only for FF
xhr.open("GET","../db/pointer.xml",true);
xhr.send(null);
xhr.onreadystatechange = function(e){
if(xhr.status == 200 && xhr.readyState == 4){
//Post back info to main page
postMessage(xhr.responseXML.getElementsByTagName("value").length);
}
}
When this runs in a script tag on the main page, i get a 3.
When running thru the WebWorker, FireBug gives me
hr.responseXML is null
postMessage(xhr.responseXML.getElementsByTagName("value").length);
In the FireBug console, GET Request responded with
<?xml version="1.0" encoding="UTF-8"?>
<root>
<value>A value</value>
<value>Another Value</value>
<value>A third Value</value>
</root>
So the response is correct but i cannot figure out where it's going wrong.
If i change responseXML to responseText the worker outputs
A value Another Value A third Value
Which is correct! why won't the script open it as an XML document?
UPDATE
function readXML(){
var xhr = new XMLHttpRequest(); //Only for FF
xhr.open("GET","../db/pointer.xml",false);
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xhr.overrideMimeType('text/xml');
xhr.send(null);
xhr.onreadystatechange = function(e){
if(xhr.status == 200 && xhr.readyState == 4){
//Post back info to main page
postMessage(xhr.responseXML.getElementsByTagName("value").length);
}
}
When setRequestHeader & overrideMimeType is changed, the onreadystatechange never fires, doesn't matter if status and readyState are there or not, it won't run. If i remove the onreadystatechange completely and just run xhr.responseXML, i get the null error again.
I still get the correct XML in as response in the console, is this a webworker issue instead of a httprequest problem? Getting desperate here :)
index.html http://www.axlonline.se/worker/index.html
worker.js http://www.axlonline.se/worker/worker.js
According to the standard, Web workers can have not have access to any type of DOM manipulation.
The DOM APIs (Node objects, Document objects, etc) are not available to workers in this version of this specification.
responseXML and channel properties are always null from an ajax request as the parsing of the XML is a DOM API. No matter the request and response headers there will be no way of getting requestXML unless you manually parse it.
Had the same Problem. Apparently XML parsing is not possible in webworkers.
I used sax.js to parse a XML on web worker.
https://github.com/isaacs/sax-js
this is basicly my parser.
function xmlParser(strict){
this.parser = sax.parser(strict, {lowercase:true});
}
xmlParser.prototype.parseFile = function(file, callback){
var _this = this;
$.ajax.get({
cache: false,
url: file,
dataType: "xml",
success: function(data){
var dom = _this.parseText(data.text);
callback( dom );
},
error: function(data){
}
});
}
xmlParser.prototype.parseText = function(xlmText){
var dom = undefined;
var activeNode = dom;
this.parser.onerror = function (e) { };
this.parser.onend = function () {};
this.parser.ontext = function (t) {
if(activeNode != undefined)
activeNode.Text = t;
};
this.parser.onopentag = function (node) {
var node = new xmlNode(node.name, activeNode, node.attributes, dom);
if(dom === undefined){
dom = node;
activeNode = node;
}else{
activeNode.Children.push(node);
activeNode = node;
}
};
this.parser.onclosetag = function (node) {
activeNode = activeNode.Parent;
};
this.parser.write(xlmText).close();
return dom;
}
xmlNode enables a jquery like handling of the tree.
function xmlFilterResult(){
this.length = 0;
}
xmlFilterResult.prototype.push = function(element){
this[this.length++] = element;
}
xmlFilterResult.prototype.attr = function(atribute){
if(this.length == 0)
return '';
return this[0].Attributes[atribute];
}
xmlFilterResult.prototype.text = function(atribute){
if(this.length == 0)
return '';
return this[0].Text;
}
xmlFilterResult.prototype.children = function(search, result){
if(result == undefined)
result = new xmlFilterResult();
if(search == undefined){
for(var i = 0; i < this.length; i++){
this[i].children(search, result);
}
}else{
this.find(search, true, result);
}
return result;
}
xmlFilterResult.prototype.find = function(search, nonrecursive, result){
if(result == undefined)
result = new xmlFilterResult();
if(search.charAt(0) == '.')
return this.findAttr('class', search.substring(1), nonrecursive, result);
else if(search.charAt(0) == '#')
return this.findAttr('id', search.substring(1), nonrecursive, result);
else
return this.findName(search, nonrecursive, result);
}
xmlFilterResult.prototype.findAttr = function(attr, value, nonrecursive, result){
if(result == undefined)
result = new xmlFilterResult();
var child;
for(var i = 0; i < this.length; i++){
child = this[i];
child.findAttr(attr, value, nonrecursive, result);
}
return result
}
xmlFilterResult.prototype.findName = function(name, nonrecursive, result){
if(result == undefined)
result = new xmlFilterResult();
var child;
for(var i = 0; i < this.length; i++){
child = this[i];
child.findName(name, nonrecursive, result);
}
return result
}
// xmlFilterResult.prototype.findID = function(id, nonrecursive){
// var child, result = new xmlFilterResult();
// for(var i = 0; i < this.length; i++){
// child = this[i];
// child.findID(id, nonrecursive, result);
// }
// return result
// }
function xmlNode(name, parent, atributes, root){
this.Name = name;
this.Children = [];
this.Parent = parent;
this.Attributes = atributes;
this.Document = root;
this.Text = '';
}
xmlNode.prototype.attr = function(atribute){
return this.Attributes[atribute];
}
xmlNode.prototype.text = function(atribute){
return this.Text;
}
xmlNode.prototype.children = function(search, result){
if(result == undefined)
result = new xmlFilterResult();
if(search == undefined){
for(i in this.Children)
result.push(this.Children[i]);
}else{
return this.find(search, true, result);
}
return result;
}
xmlNode.prototype.find = function(search, nonrecursive, result){
if(search.charAt(0) == '.')
return this.findAttr('class', search.substring(1), nonrecursive, result);
else if(search.charAt(0) == '#')
return this.findAttr('id', search.substring(1), nonrecursive, result);
else
return this.findName(search, nonrecursive, result);
}
xmlNode.prototype.findAttr = function(attr, value, nonrecursive, result){
var child, i;
if(result == undefined)
result = new xmlFilterResult();
for(i in this.Children){
child = this.Children[i];
if(child.Attributes[attr] == value)
result.push(child);
if(!nonrecursive)
child.findAttr(attr, value, nonrecursive, result);
}
return result
}
xmlNode.prototype.findName = function(name, nonrecursive, result){
var child, i;
if(result == undefined)
result = new xmlFilterResult();
for(i in this.Children){
child = this.Children[i];
if(child.Name == name){
result.push(child);
}
if(!nonrecursive)
child.findName(name, nonrecursive, result);
}
return result
}
Its nothing special but you get the idea of that to do.
You just need to set the content-type header to text/xml on the server side.
responseXML is null if the document that you're requesting isn't XML. Specifically, the content-type should be one of text/html, text/xml, application/xml, or something that ends in +xml. See the spec.
Also, see: responseXML is null and responseXML always null.
And a side note: since web workers are inherently asynchronous, you don't need to set the async flag to true in your open call.

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

Categories

Resources