Using the input box instead of pop function - javascript

How can I use an input box instead of prompt on this code?
Code is
here.
Once I click on the link; a prompt pops up and asks to type a number or Q to quit. How would I change that to input box?
function Stack() {
var items = [];
this.push = function(element){
items.push(element);
};
this.pop = function(){
return items.pop();
};
this.peek = function(){
return items[items.length-1];
};
this.isEmpty = function(){
return items.length == 0;
};
this.size = function(){
return items.length;
};
this.clear = function(){
items = [];
};
this.print = function(){
alert("Stack Elements are:"+items.toString());
};
}
Declare stack object:
var stack = new Stack();
while(1)
{
var element = prompt("Enter stack element,(q or Q to exit)", "");
if(element == 'q' || element =='Q')
{
break;
}
else
{
if(element=='*'
|| element=='+' || element=='-' || element=='/')
{
//Check if stack is empty
if(stack.isEmpty() || stack.size<2 )
{
alert("Invalid Operation, Stack is empty or size is less than 2");
}
else
{
var op1 = stack.pop();
var op2 = stack.pop();
if(element=='*')
{
var res = op1 * op2;
}
else if(element=='+')
{
var res = op1 + op2;
}
else if(element=='-')
{
var res = op1 - op2;
}
else if(element=='/')
{
var res = op1 / op2;
}
stack.push(res);
stack.print();
}
}
else
{
stack.push(element);
stack.print();
}
}
}

try following example :
FIDDLE
var stack = new Stack();
function Stack() {
var items = [];
this.push = function(element) {
items.push(element);
};
this.pop = function() {
return items.pop();
};
this.peek = function() {
return items[items.length - 1];
};
this.isEmpty = function() {
return items.length == 0;
};
this.size = function() {
return items.length;
};
this.clear = function() {
items = [];
};
this.print = function() {
theList.options.length = 0;
for (var i = 0; i < items.length; i++) {
var theOption = new Option(items[i]);
theList.options[theList.options.length] = theOption;
}
};
}
function pushStack(newVal) {
if (newVal == '*' || newVal == '+' || newVal == '-' || newVal == '/') {
//Check if stack is empty
if (stack.isEmpty() || stack.size < 2) {
alert("Invalid Operation, Stack is empty or size is less than 2");
} else {
var op1 = stack.pop();
var op2 = stack.pop();
if (newVal == '*') {
var res = op1 * op2;
} else if (newVal == '+') {
var res = op1 + op2;
} else if (newVal == '-') {
var res = op1 - op2;
} else if (newVal == '/') {
var res = op1 / op2;
}
stack.push(res);
}
} else {
stack.push(newVal);
}
}
function popStack() {
var popVal = stack.pop();
if (popVal == undefined)
return "Empty stack!";
else
return popVal;
}
function showStack() {
stack.print();
}
<FORM>
<INPUT type="text" name="txtPush" id="txtPush" />
<INPUT type=button value="Push" onClick='pushStack(txtPush.value); txtPush.value=""; showStack(theList);' />
<SELECT name="theList" id="theList" size=12>
<OPTION>Displays the current state of the stack!</OPTION>
</SELECT>
</FORM>

Related

Javascript condition not working as expected

I have a JS code which works fine when
checkQueryString != "M"
but When the value becomes checkQueryString == "M" it doesn't goes inside the loop
Here is my code.
function GridExpInfo_ClientAdd(record) {
var checkQueryString = '<%= Request.QueryString["Mode"] %>';
if (checkQueryString != "M") {
if ($('input:checked').length > 0) {
document.getElementById("GridExpInfo_tplRowEdit3_ctl00_txtExpRefNo").disabled = true;
document.getElementById("GridExpInfo_tplRowEdit3_ctl00_txtExpRefDt").disabled = true;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').value = "";
var last_value = 0;
var last_text;
var checkboxlist = document.getElementById('ddlStatus');
var checkOptions = checkboxlist.getElementsByTagName('input');
var listSelected = checkboxlist.getElementsByTagName('label');
for (i = 0; i < checkOptions.length; i++) {
if (checkOptions[i].checked == true) {
last_text = listSelected[i].innerText;
last_value = checkOptions[i].value;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').innerHTML = "";
var ObjPriOptionExp = document.createElement("OPTION");
ObjPriOptionExp.text = last_text;
ObjPriOptionExp.value = last_value;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').add(ObjPriOptionExp);
}
}
}
if(checkQueryString == "M")
{
alert('Value is M now');
}
else {
alert('Kindly select the stage');
}
}
}
So my question is, why it doesn't goes inside if when it matches to M
Because
if (checkQueryString == "M") {
alert('Value is M now');
} else {
alert('Kindly select the stage');
}
Has inside if (checkQueryString == "M")
So try this
function GridExpInfo_ClientAdd(record) {
var checkQueryString = '<%= Request.QueryString["Mode"] %>';
if (checkQueryString != "M") {
if ($('input:checked').length > 0) {
document.getElementById("GridExpInfo_tplRowEdit3_ctl00_txtExpRefNo").disabled = true;
document.getElementById("GridExpInfo_tplRowEdit3_ctl00_txtExpRefDt").disabled = true;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').value = "";
var last_value = 0;
var last_text;
var checkboxlist = document.getElementById('ddlStatus');
var checkOptions = checkboxlist.getElementsByTagName('input');
var listSelected = checkboxlist.getElementsByTagName('label');
for (i = 0; i < checkOptions.length; i++) {
if (checkOptions[i].checked == true) {
last_text = listSelected[i].innerText;
last_value = checkOptions[i].value;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').innerHTML = "";
var ObjPriOptionExp = document.createElement("OPTION");
ObjPriOptionExp.text = last_text;
ObjPriOptionExp.value = last_value;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').add(ObjPriOptionExp);
}
}
}
} else if (checkQueryString == "M") {
alert('Value is M now');
} else {
alert('Kindly select the stage');
}
}

Is there a polyfill for findAll

I am using JavaScript findAll for a selector engine. Is there any polyfill for the findAll function. I tried to create my own selector engine with this code:
function CTfind(string, context){
var result = [], finalResult = [];
if(typeof string === "object"){
result.push(string);
return result;
}
if(/<([a-zA-Z]+)(\s*)?\/>/ig.test(string)){
var str = string.replace(/<([a-zA-Z]+)(\s*)?\/>/ig, "$1");
var ret = document.createElement(str);
if(typeof context === "object"){
for(i in context)
ret[i] = context[i];
}
document.body.appendChild(ret);
result.push(ret);
return result;
} else{
if(typeof string !== "string" && typeof string !== "object") return false;
var documentElements = context.getElementsByTagName("*"),
toMatch = string.split(", ");
for(i = 0; i < documentElements.length; i++){
for(e = 0; e < toMatch.length; e++){
var stringParts = toMatch[e].split(" ");
for(s = 0; s < stringParts.length; s++){
var parts;
if(/(\.|\#|\:)/g.test(stringParts[s])){
parts = stringParts[s].match(/([A-Za-z]+|[\.\#\:]+[^\.\#\:]+)/g);
} else if(/^(?!(\.|\#|\:)$).*$/g.test(stringParts[s])){
parts = stringParts[s];
var onlyElem = true;
}
if(onlyElem === true){
console.log(documentElements[i].nodeName);
if(documentElements[i].nodeName.toLowerCase() === parts){
result.push(documentElements[i]);
}
} else{
var containsClass = false,
containsElem = false,
containsID = false,
containsPseudo = false,
matchID = false,
matchElem = false,
matchClass = false,
matchPseudo = false;
if(/\./.test(stringParts[s])){
containsClass = true;
}
if(/\#/.test(stringParts[s])){
containsID = true;
}
if(/\:/.test(stringParts[s])){
containsPseudo = true;
}
if(/[^\.\#\:](.*)/.test(stringParts[s])){
containsElem = true;
}
if(containsElem === true){
var elem;
for(g = 0; g < parts.length; g++){
if(/^([^\.\#\:][A-Za-z])*$/.test(parts[g])){
elem = parts[g];
} else{
elem = documentElements[i].nodeName.toLowerCase();
}
}
if(documentElements[i].nodeName.toLowerCase() === elem){
matchElem = true;
}
} else{
matchElem = true;
}
if(containsID === true){
var id = filter(parts, "#");
id = id[0].substr(1);
if(getAttr(documentElements[i], "id") === id){
matchID = true;
}
} else{
matchID = true;
}
if(containsClass === true){
var classes = filter(parts, ".");
if(typeof classes === "string"){
classes = classes[0].split(".");
for(c = 0; c < classes.length; c++){
if(classes[c] !== ""){
if(hasClass(documentElements[i], classes[c])){
matchClass = true;
}
}
}
}
} else{
matchClass = true;
}
if(matchClass && matchID && matchElem){
result.push(documentElements[i]);
}
console.log(result);
}
}
if(stringParts.length > 1){
console.log(result);
if(isDescendant(result[0], result[result.length - 1])){
finalResult.push(result[result.length - 1]);
}
}
}
}
return finalResult;
}
};
But I thought using Javascript findAll would be much easier. Also, I can't use querySelector because sometimes I need to find it in a specific node.

JS/JSp issue in IE 10 for scrollbar and sorting

I am facing issue in table where we are using scroll bar and sorting.
In compatible mode sorting option is coming where as not coming in non compatible mode
Please suggest changes in js or jsp
function makeScrollableTable(tbl, scrollFooter, height, hasSelectAllButton, hasAddButton, columnNo) {
var c, pNode, hdr, ftr, wrapper, rect;
//alert("Shree");
if (typeof tbl == 'string') tbl = document.getElementById(tbl);
pNode = tbl.parentNode;
fixTableWidth(tbl);
c = container.length;
container[c] = document.createElement('<SPAN style="height: 100; overflow: auto;">');
container[c].id = tbl.id + "Container";
pNode.insertBefore(container[c], tbl);
container[c].appendChild(tbl);
container[c].style.width = tbl.clientWidth + 2 * tbl.clientLeft + scrollbarWidth();
hdr = tbl.cloneNode(false);
hdr.id += 'Header';
hdr.appendChild(tbl.tHead.cloneNode(true));
tbl.tHead.style.display = 'none';
if (!scrollFooter || !tbl.tFoot) {
ftr = document.createElement('<SPAN style="width:1;height:1;clip: rect(0 1 1 0);background-color:transparent;">');
ftr.id = tbl.id + 'Footer';
ftr.style.border = tbl.style.border;
ftr.style.width = getActualWidth(tbl) + 2 * tbl.clientLeft;
ftr.style.borderBottom = ftr.style.borderLeft = ftr.style.borderRight = 'none';
} else {
ftr = tbl.cloneNode(false);
ftr.id += 'Footer';
ftr.appendChild(tbl.tFoot.cloneNode(true));
ftr.style.borderTop = 'none';
tbl.tFoot.style.display = 'none';
}
wrapper = document.createElement('<table border=0 cellspacing=0 cellpadding=0>');
wrapper.id = tbl.id + 'Wrapper';
pNode.insertBefore(wrapper, container[c]);
wrapper.insertRow(0).insertCell(0).appendChild(hdr);
wrapper.insertRow(1).insertCell(0).appendChild(container[c]);
wrapper.insertRow(2).insertCell(0).appendChild(ftr);
wrapper.align = tbl.align;
tbl.align = hdr.align = ftr.align = 'left';
hdr.style.borderBottom = 'none';
tbl.style.borderTop = tbl.style.borderBottom = 'none';
// adjust page size
if (c == 0 && height == 'auto') {
onResizeAdjustTable();
onResizeHandler = window.onresize;
window.onresize = onResizeAdjustTable;
} else {
container[c].style.height = height;
}
//added by Venkatesh Bhat e-mail:vb106#dcx
//alert("");
if (hasSelectAllButton) {
//include select all button
var selButton = document.createElement('<input id="_myButton11" type="button" value="Select All" onClick="selectAll();">');
insertNode(selButton);
}
if (hasAddButton) {
var btext = '<input id="_myButton12" type="button" value="Add" onClick="posCursor(\'' + tbl.id + '\',\'' + columnNo + '\');">';
var addButton = document.createElement(btext);
insertNode(addButton);
}
}
//added by Venkatesh Bhat e-mail:vb106#dcx
function insertNode(toInsert) {
var tbs = document.getElementsByTagName('input');
for (var i = 0; i < tbs.length; i++) {
if (tbs[i].type == "button") {
var backButton = tbs[i];
var text = backButton.value.toUpperCase();
if (text == "BACK") {
var pNode = backButton.parentNode;
pNode.insertBefore(toInsert, backButton);
var textNode = document.createTextNode(" ");
pNode.insertBefore(textNode, backButton);
return;
}
}
}
}
//added by Venkatesh Bhat e-mail:vb106#dcx
function posCursor(tbl, columnNo) {
var table = document.getElementById(tbl);
var rows = table.rows;
for (var i = 0; i < rows.length; i++) {
//cells = rows[i].cells;
//if(columnNo > cells.length) continue;
var cell = rows[i].cells[columnNo];
if (getFocus(cell) == true) {
selectCheckBox(rows[i].cells[0]);
return;
}
}
}
//added by Venkatesh Bhat e-mail:vb106#dcx
function selectCheckBox(node) {
var children = node.children;
//check if this is a leaf node
if (children.length == 0) {
//if so then see if this is a checkbox input node
if (node.tagName == "INPUT" && node.type == "checkbox") {
node.checked = true;
return true;
} else {
return false;
}
} else {
//this is a parent node
for (var i = 0; i < children.length; i++) {
if (selectCheckBox(children[i]) == true) return true;
}
}
return false;
}
//added by Venkatesh Bhat e-mail:vb106#dcx
function getFocus(node) {
var children = node.children;
//check if this is a leaf node
if (children.length == 0) {
//if so then see if this is a text input node
if (node.tagName == "INPUT" && node.type == "text" && node.value == "") {
node.focus();
return true;
} else {
return false;
}
} else {
//this is a parent node
for (var i = 0; i < children.length; i++) {
if (getFocus(children[i]) == true) return true;
}
}
return false;
}
//added by Venkatesh Bhat e-mail:vb106#dcx
function selectAll() {
//added by Venkatesh Bhat e-mail:vb106#dcx
var button = document.getElementById('_myButton11');
var butText = button.value;
var tbs = document.getElementsByTagName('input');
if (butText == 'Deselect All') {
button.value = "Select All";
for (var i = 0; i < tbs.length; i++) {
if (tbs[i].type == "checkbox") {
tbs[i].checked = false;
}
}
} else {
button.value = "Deselect All";
for (var i = 0; i < tbs.length; i++) {
if (tbs[i].type == "checkbox") {
tbs[i].checked = true;
}
}
}
}
function onResizeAdjustTable() {
if (onResizeHandler) onResizeHandler();
var rect = container[0].getClientRects()(0);
var h = document.body.clientHeight - (rect.top + (document.body.scrollHeight - rect.bottom));
container[0].style.height = (h > 0) ? h : 1;
}
function printPage() {
var tbs = document.getElementsByTagName('TABLE');
var e;
for (var i = 0; i < container.length; i++) container[i].style.overflow = '';
window.print();
for (var i = 0; i < container.length; i++) container[i].style.overflow = 'auto';
}

Any Good Number Picker for JQuery (or Javascript)?

Are there any good number picker for jquery (or standalone js)?
I would like a number picker where there is a max and min number that the user can choose from. Also, it have other options such as displaying odd number or even number or prime number or a range of number whereby some numbers in between are skipped.
Using a select to do this you can create an array with the numbers to skip and do a for loop to write the options:
int minNumber = 0;
int maxNumber = 10;
int[] skipThese = { 5, 7 };
for (int i = minNumber; i <= maxNumber; i++)
{
if(!skipThese.Contains(i)) Response.Write(String.Concat("<option value=\"", i, "\">", i, "</option>"));
}
You can do this with razor or any other way to output the HTML.
You can also do this with jQuery, dynamicaly, following the same idea:
$(document).ready(function() {
var minNumber = 0;
var maxNumber = 10;
var skipThese = [5, 7];
for (var i = minNumber; i <= maxNumber; i++) {
if ($.inArray(i, skipThese) == -1) $('#selectListID').append("<option value=\"" + i + "\">" + i + "</option>");
}
});
Edit:
Or you can use the C# code above in an aspx page and load it with AJAX from the page:
Create a select box in the page:
<select name="numPicker" id="numPicker">
<option>Loading...</option>
</select>
In a script in this page you could use jQuery's ajax() to fetch the data and populate the <select>:
$(document).ready(function() {
var numPickerSelect = $("#numPicker");
$.ajax({
url: 'url/to/page.aspx',
type: 'post'
success: function(data) {
numPickerSelect.find('option').remove(); // Remove the options in the select field
numPickerSelect.append(data); // Load the content generated by the server into the select field
},
error: function() {
alert('An error has ocurred!');
}
});
//Or use this (not sure if will work)
numPickerSelect.load("url/to/page.aspx");
});
I have used this. You should be able to modify to add extra options such as min and max fairly easily.
// Make a control only accept numeric input
// eg, $("#myedit").numeric()
// $("#myedit").numeric({alow: ' ,.'})
// $("#myedit").numeric({decimals: 2})
(function($) {
$.fn.alphanumeric = function(p) {
if (p == 'destroy') {
$(this).unbind('keypress');
$(this).unbind('blur');
return;
}
p = $.extend({
ichars: "!##$%^&*()+=[]\\\';,/{}|\":<>?~`.- ",
nchars: "",
allow: "",
decimals: null
}, p);
return this.each
(
function() {
if (p.nocaps) p.nchars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (p.allcaps) p.nchars += "abcdefghijklmnopqrstuvwxyz";
s = p.allow.split('');
for (i = 0; i < s.length; i++) if (p.ichars.indexOf(s[i]) != -1) s[i] = "\\" + s[i];
p.allow = s.join('|');
var reg = new RegExp(p.allow, 'gi');
var ch = p.ichars + p.nchars;
ch = ch.replace(reg, '');
var dp = p.decimals;
var isInteger = function(val) {
var objRegExp = /(^-?\d\d*$)/;
return objRegExp.test(val);
};
var isNumeric = function(val) {
// If the last digit is a . then add a 0 before testing so if they type 25. it will be accepted
var lastChar = val.substring(val.length - 1);
if (lastChar == ".") val = val + "0";
var objRegExp = new RegExp("^\\s*-?(\\d+(\\.\\d{1," + dp + "})?|\\.\\d{1," + dp + "})\\s*$", "g");
if (dp == -1)
objRegExp = new RegExp("^\\s*-?(\\d+(\\.\\d{1,25})?|\\.\\d{1,25})\\s*$", "g");
var result = objRegExp.test(val);
return result;
};
$(this).blur(function(e) {
var text = $(this).val();
if (dp != null) {
if (dp == 0) {
if (!isInteger(text)) {
$(this).val('');
e.preventDefault();
}
}
else {
if (!isNumeric(text)) {
$(this).val('');
e.preventDefault();
}
}
} else {
var c = text.split('')
for (i = 0; i < text.length; i++) {
if (ch.indexOf(c[i]) != -1) {
$(this).val('');
e.preventDefault();
};
}
}
});
$(this).keypress
(
function(e) {
switch (e.which) {
//Firefox fix, for ignoring specific presses
case 8: // backspace key
return true;
case 46: // delete key
return true;
};
if (dp != null) {
if (e.which == 32) { e.preventDefault(); return false; }
var range = getRange(this);
var typed = String.fromCharCode(e.which);
var text = $(this).val().substr(0, range.start) + typed + $(this).val().substr(range.start);
if (dp == 0) {
if (!isInteger(text)) e.preventDefault();
}
else {
if (!isNumeric(text)) e.preventDefault();
}
return;
}
if (!e.charCode) k = String.fromCharCode(e.which);
else k = String.fromCharCode(e.charCode);
if (ch.indexOf(k) != -1) e.preventDefault();
if (e.ctrlKey && k == 'v') e.preventDefault();
}
);
$(this).bind('contextmenu', function() { return false });
}
);
};
$.fn.numeric = function(p) {
if (p == 'destroy') {
$(this).unbind('keypress');
$(this).unbind('blur');
return;
}
var az = "abcdefghijklmnopqrstuvwxyz";
az += az.toUpperCase();
var opts = {};
if (!isNaN(p)) {
opts = $.extend({
nchars: az
}, { decimals: p });
} else {
opts = $.extend({
nchars: az
}, p);
}
return this.each(function() {
$(this).alphanumeric(opts);
}
);
};
$.fn.integer = function(p) {
if (p == 'destroy') {
$(this).unbind('keypress');
$(this).unbind('blur');
return;
}
var az = "abcdefghijklmnopqrstuvwxyz";
az += az.toUpperCase();
p = {
nchars: az,
allow: '-',
decimals: 0
};
return this.each(function() {
$(this).alphanumeric(p);
}
);
};
$.fn.alpha = function(p) {
if (p == 'destroy') {
$(this).unbind('keypress');
$(this).unbind('blur');
return;
}
var nm = "1234567890";
p = $.extend({
nchars: nm
}, p);
return this.each(function() {
$(this).alphanumeric(p);
}
);
};
})(jQuery);

Uncaught SyntaxError: Unexpected token

I have following script which is used to post comments. But when I try to submit the comment Google Chrome throws this error:
Uncaught SyntaxError: Unexpected token <
jax.processResponse
xmlhttp.onreadystatechange
I simply don't know what this error is all about.
function Jax() {
var loadingTimeout = 400;
var iframe;
this.loadingFunction = function () {};
this.doneLoadingFunction = function () {};
this.stringify = function (arg) {
var c, i, l, o, u, v;
switch (typeof arg) {
case "object":
if (arg) {
if (arg.constructor == Array) {
o = "";
for (i = 0; i < arg.length; ++i) {
v = this.stringify(arg[i]);
if (o && (v !== u)) {
o += ","
}
if (v !== u) {
o += v
}
}
return "[" + o + "]"
} else {
if (typeof arg.toString != "undefined") {
o = "";
for (i in arg) {
v = this.stringify(arg[i]);
if (v !== u) {
if (o) {
o += ","
}
o += this.stringify(i) + ":" + v
}
}
return "{" + o + "}"
} else {
return
}
}
}
return "";
case "unknown":
case "undefined":
case "function":
return u;
case "string":
arg = arg.replace(/"/g, '\\"');
l = arg.length;
o = '"';
for (i = 0; i < l; i += 1) {
c = arg.charAt(i);
if (c >= " ") {
if (c == "\\" || c == '"') {
o += "\\"
}
o += c
} else {
switch (c) {
case '"':
o += '\\"';
break;
case "\b":
o += "\\b";
break;
case "\f":
o += "\\f";
break;
case "\n":
o += "\\n";
break;
case "\r":
o += "\\r";
break;
case "\t":
o += "\\t";
break;
default:
c = c.charCodeAt();
o += "\\u00";
o += Math.floor(c / 16).toString(16);
o += (c % 16).toString(16)
}
}
}
return o + '"';
default:
return String(arg)
}
};
this.getRequestObject = function () {
if (window.XMLHttpRequest) {
http_request = new XMLHttpRequest()
} else {
if (window.ActiveXObject) {
var msxmlhttp = new Array("Msxml2.XMLHTTP.4.0", "Msxml2.XMLHTTP.3.0", "Msxml2.XMLHTTP", "Microsoft.XMLHTTP");
for (var i = 0; i < msxmlhttp.length; i++) {
try {
http_request = new ActiveXObject(msxmlhttp[i])
} catch (e) {
http_request = null
}
}
}
}
if (!http_request) {
alert("Unfortunatelly you browser doesn't support this feature.");
return false
}
return http_request
};
this.$ = function (sId) {
if (!sId) {
return null
}
var returnObj = document.getElementById(sId);
if (!returnObj && document.all) {
returnObj = document.all[sId]
}
return returnObj
};
this.addEvent = function (obj, type, fn) {
if (obj.attachEvent) {
obj["e" + type + fn] = fn;
obj[type + fn] = function () {
obj["e" + type + fn](window.event)
};
obj.attachEvent("on" + type, obj[type + fn])
} else {
obj.addEventListener(type, fn, false)
}
};
this.removeEvent = function (obj, type, fn) {
if (obj.detachEvent) {
obj.detachEvent("on" + type, obj[type + fn]);
obj[type + fn] = null
} else {
obj.removeEventListener(type, fn, false)
}
};
this.submitITask = function (comName, func, postData, responseFunc) {
var xmlReq = this.buildXmlReq(comName, func, postData, responseFunc, true);
this.loadingFunction();
if (!this.iframe) {
this.iframe = document.createElement("iframe");
this.iframe.setAttribute("id", "ajaxIframe");
this.iframe.setAttribute("height", 0);
this.iframe.setAttribute("width", 0);
this.iframe.setAttribute("border", 0);
this.iframe.style.visibility = "hidden";
document.body.appendChild(this.iframe);
this.iframe.src = xmlReq
} else {
this.iframe.src = xmlReq
}
};
this.extractIFrameBody = function (iFrameEl) {
var doc = null;
if (iFrameEl.contentDocument) {
doc = iFrameEl.contentDocument
} else {
if (iFrameEl.contentWindow) {
doc = iFrameEl.contentWindow.document
} else {
if (iFrameEl.document) {
doc = iFrameEl.document
} else {
alert("Error: could not find sumiFrame document");
return null
}
}
}
return doc.body
};
this.buildXmlReq = function (comName, func, postData, responseFunc, iframe) {
var xmlReq = "";
if (iframe) {
xmlReq += "?"
} else {
xmlReq += "&"
}
xmlReq += "option=" + comName;
xmlReq += "&no_html=1";
xmlReq += "&task=azrul_ajax";
xmlReq += "&func=" + func;
xmlReq += "&" + jax_token_var + "=1";
if (postData) {
xmlReq += "&" + postData
}
return xmlReq
};
this.submitTask = function (comName, func, postData, responseFunc) {
var xmlhttp = this.getRequestObject();
var targetUrl = jax_live_site;
xmlhttp.open("POST", targetUrl, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
jax.doneLoadingFunction();
jax.processResponse(xmlhttp.responseText)
} else {}
}
};
var id = 1;
var xmlReq = this.buildXmlReq(comName, func, postData, responseFunc);
this.loadingFunction();
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(xmlReq)
};
this.processIResponse = function () {
jax.doneLoadingFunction();
var resp = (this.extractIFrameBody(this.iframe).innerHTML);
resp = resp.replace(/</g, "<");
resp = resp.replace(/>/g, ">");
resp = resp.replace(/&/g, "&");
resp = resp.replace(/"/g, '"');
resp = resp.replace(/'/g, "'");
this.processResponse(resp)
};
this.BetterInnerHTML = function (o, p, q) {
function r(a) {
var b;
if (typeof DOMParser != "undefined") {
b = (new DOMParser()).parseFromString(a, "application/xml")
} else {
var c = ["MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XMLDOM"];
for (var i = 0; i < c.length && !b; i++) {
try {
b = new ActiveXObject(c[i]);
b.loadXML(a)
} catch (e) {}
}
}
return b
}
function s(a, b, c) {
a[b] = function () {
return eval(c)
}
}
function t(b, c, d) {
if (typeof d == "undefined") {
d = 1
}
if (d > 1) {
if (c.nodeType == 1) {
var e = document.createElement(c.nodeName);
var f = {};
for (var a = 0, g = c.attributes.length; a < g; a++) {
var h = c.attributes[a].name,
k = c.attributes[a].value,
l = (h.substr(0, 2) == "on");
if (l) {
f[h] = k
} else {
switch (h) {
case "class":
e.className = k;
break;
case "for":
e.htmlFor = k;
break;
default:
e.setAttribute(h, k)
}
}
}
b = b.appendChild(e);
for (l in f) {
s(b, l, f[l])
}
} else {
if (c.nodeType == 3) {
var m = (c.nodeValue ? c.nodeValue : "");
var n = m.replace(/^\s*|\s*$/g, "");
if (n.length < 7 || (n.indexOf("<!--") != 0 && n.indexOf("-->") != (n.length - 3))) {
b.appendChild(document.createTextNode(m))
}
}
}
}
for (var i = 0, j = c.childNodes.length; i < j; i++) {
t(b, c.childNodes[i], d + 1)
}
}
p = "<root>" + p + "</root>";
var u = r(p);
if (o && u) {
if (q != false) {
while (o.lastChild) {
o.removeChild(o.lastChild)
}
}
t(o, u.documentElement)
}
};
this.processResponse = function (responseTxt) {
var result = eval(responseTxt);
for (var i = 0; i < result.length; i++) {
var cmd = result[i][0];
var id = result[i][1];
var property = result[i][2];
var data = result[i][3];
var objElement = this.$(id);
switch (cmd) {
case "as":
if (objElement) {
eval("objElement." + property + "= data ; ")
}
break;
case "al":
if (data) {
alert(data)
}
break;
case "ce":
this.create(id, property, data);
break;
case "rm":
this.remove(id);
break;
case "cs":
var scr = id + "(";
if (this.isArray(data)) {
scr += "(data[0])";
for (var l = 1; l < data.length; l++) {
scr += ",(data[" + l + "])"
}
} else {
scr += "data"
}
scr += ");";
eval(scr);
break;
default:
alert("Unknow command: " + cmd)
}
}
};
this.isArray = function (obj) {
if (obj) {
return obj.constructor == Array
}
return false
};
this.buildCall = function (comName, sFunction) {};
this.icall = function (comName, sFunction) {
var arg = "";
if (arguments.length > 2) {
for (var i = 2; i < arguments.length; i++) {
var a = arguments[i];
if (this.isArray(a)) {
arg += "arg" + i + "=" + this.stringify(a) + "&"
} else {
if (typeof a == "string") {
var t = new Array("_d_", encodeURIComponent(a));
arg += "arg" + i + "=" + this.stringify(t) + "&"
} else {
var t = new Array("_d_", encodeURIComponent(a));
arg += "arg" + i + "=" + this.stringify(t) + "&"
}
}
}
}
if (jax_site_type == "1.5") {
this.submitTask(comName, sFunction, arg)
} else {
this.submitITask(comName, sFunction, arg)
}
};
this.call = function (comName, sFunction) {
var arg = "";
if (arguments.length > 2) {
for (var i = 2; i < arguments.length; i++) {
var a = arguments[i];
if (this.isArray(a)) {
arg += "arg" + i + "=" + this.stringify(a) + "&"
} else {
if (typeof a == "string") {
a = a.replace(/"/g, """);
var t = new Array("_d_", encodeURIComponent(a));
arg += "arg" + i + "=" + this.stringify(t) + "&"
} else {
var t = new Array("_d_", encodeURIComponent(a));
arg += "arg" + i + "=" + this.stringify(t) + "&"
}
}
}
}
this.submitTask(comName, sFunction, arg)
};
this.create = function (sParentId, sTag, sId) {
var objParent = this.$(sParentId);
objElement = document.createElement(sTag);
objElement.setAttribute("id", sId);
if (objParent) {
objParent.appendChild(objElement)
}
};
this.remove = function (sId) {
objElement = this.$(sId);
if (objElement && objElement.parentNode && objElement.parentNode.removeChild) {
objElement.parentNode.removeChild(objElement)
}
};
this.getFormValues = function (frm) {
var objForm;
objForm = this.$(frm);
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (elt) {
var len = this.length;
var from = Number(arguments[1]) || 0;
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0) {
from += len
}
for (; from < len; from++) {
if (from in this && this[from] === elt) {
return from
}
}
return -1
}
}
var postData = new Array();
if (objForm && objForm.tagName == "FORM") {
var formElements = objForm.elements;
var assCheckbox = new Array();
var assCntIdx = 0;
var arrayHiddenValues = new Array();
var arrayHiddenCount = 0;
if (formElements.length > 0) {
for (var i = 0; i < formElements.length; i++) {
if (!formElements[i].name) {
continue
}
if (formElements[i].type && (formElements[i].type == "radio" || formElements[i].type == "checkbox") && formElements[i].checked == false) {
continue
}
var name = formElements[i].name;
if (name) {
if (formElements[i].type == "select-multiple") {
postData[i] = new Array();
for (var j = 0; j < formElements[i].length; j++) {
if (formElements[i].options[j].selected === true) {
var value = formElements[i].options[j].value;
postData[i][j] = new Array(name, encodeURIComponent(value))
}
}
} else {
if (formElements[i].type == "checkbox") {
if (assCheckbox.indexOf(formElements[i].name) == -1) {
assCheckbox[assCntIdx] = formElements[i].name;
assCntIdx++
}
} else {
if (formElements[i].type == "hidden") {
if (arrayHiddenValues.indexOf(formElements[i].name) == -1) {
arrayHiddenValues[arrayHiddenCount] = formElements[i].name;
arrayHiddenCount++
}
} else {
var value = formElements[i].value;
value = value.replace(/"/g, """);
postData[i] = new Array(name, encodeURIComponent(value))
}
}
}
}
}
}
if (arrayHiddenValues.length > 0) {
for (var i = 0; i < arrayHiddenValues.length; i++) {
var hiddenElement = document.getElementsByName(arrayHiddenValues[i]);
if (hiddenElement) {
if (hiddenElement.length > 1) {
var curLen = postData.length;
postData[curLen] = new Array();
for (var j = 0; j < hiddenElement.length; j++) {
var value = hiddenElement[j].value;
value = value.replace(/"/g, """);
postData[curLen][j] = new Array(arrayHiddenValues[i], encodeURIComponent(value))
}
} else {
var value = hiddenElement[0].value;
value = value.replace(/"/g, """);
postData[postData.length] = new Array(arrayHiddenValues[i], encodeURIComponent(value))
}
}
}
}
if (assCheckbox.length > 0) {
for (var i = 0; i < assCheckbox.length; i++) {
var objCheckbox = document.getElementsByName(assCheckbox[i]);
if (objCheckbox) {
if (objCheckbox.length > 1) {
var tmpIdx = 0;
var curLen = postData.length;
postData[curLen] = new Array();
for (var j = 0; j < objCheckbox.length; j++) {
if (objCheckbox[j].checked) {
var value = objCheckbox[j].value;
value = value.replace(/"/g, """);
postData[curLen][j] = new Array(assCheckbox[i], encodeURIComponent(value));
tmpIdx++
}
}
} else {
if (objCheckbox[0].checked) {
var value = objCheckbox[0].value;
value = value.replace(/"/g, """);
postData[postData.length] = new Array(assCheckbox[i], encodeURIComponent(value))
}
}
}
}
}
}
return postData
}
}
function jax_iresponse() {
jax.processIResponse()
}
var jax = new Jax();
Please help me.
I'm not sure anyone should read obfuscated, minified code, but i found this:
**xmlhttp.onreadystatechange**=function(){
if(xmlhttp.readyState==4){
if(xmlhttp.status==200){
jax.doneLoadingFunction();
**jax.processResponse**(xmlhttp.responseText)}
else{}
}
};
Which returns a js error on line 1 :))
Are you allowed to use ** with variable names in js?
check if your bug is not here line 296
var result = eval(responseTxt);
What are you getting as a response? is it html, json?
Check also for notices in your backend script,
You can check this with the console/inspector in chrome (f12) , network tab.
It could be even be a debug output/notice/error from your backend script.
If you open it with firefox, i think firebug shows you a JSON tab if your response is in correct json format.

Categories

Resources