JavaScript extracting data from XML (if else statement not working) - javascript

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

Related

How can i display as ajax-response in a reloaded page

I have the following situation in an AJAX-Request:
function getFileContens(OBJ) {
var file = OBJ.id;
PARAMS = "Action=getFileContens";
PARAMS = PARAMS + "&File=" + OBJ.id;
var probenZahl = file.split("__")[4];
document.getElementById("inpProbenAnzahl").value = probenZahl;
//setSessionValue(document.getElementById("inpProbenAnzahl"));
try {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Ihr Webbrowser unterstuetzt leider kein Ajax!");
}
//alert(PARAMS);
req.open("POST", "./php/ajax/Eingabe.php", true);
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
req.onreadystatechange = function() {
cbGetFileContens();
};
req.send(PARAMS);
} catch (e) {
alert("Fehler: " + e);
}
}
function cbGetFileContens() {
if (4 == req.readyState) {
if (200 != req.status) {
alert("Fehler " + req.status + ": " + req.statusText);
} else {
//alert(req.responseText);
var ar_resp = req.responseText.split(";;;");
for (let i = 0; i < ar_resp.length; i++) {
ar_inp = ar_resp[i].split("##");
if (ar_inp[0].trim().length > 2) {
if (document.getElementById(ar_inp[0].trim())) {
document.getElementById(ar_inp[0].trim()).value = ar_inp[1];
}
}
}
location.reload();
//console.log("Hallo");
console.log(req.responseText);
}
}
}
This code shoud display the splitted response-text in a textfield with certain IDs in a HTML-File...
I want to use the Ajax-response-text after reloading the page..
Everything works fine whe i do not reload the page..
Using reloading the text is not displayed..
You can store the response into a session storage.
sessionStorage.setItem('ajax_response', req.responseText)
location.reload();
After, when the page is loaded, you can put the item into your element.
var el = document.getElementById('elemId')
el.innerText = sessionStorage.getItem('ajax_response')

json parsing using javascript

I have trouble in parsing the JSON using the Javascript.My resultant variable 'text' do does not have the result after completion of loop. Can anybody guide me how can I parse this JSON properly.
var xmlr = null;
var text = '';
if (window.XMLHttpRequest) {
xmlr = new XMLHttpRequest();
} else {
xmlr = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlr.onreadystatechange = function () {
if (xmlr.readyState == 4 && xmlr.status == 200) {
var data = JSON.parse(xmlr.responseText);
for (var i = 0; i <= data.length; i++) {
text += '<option>' + data[i].member_first_name + '</option>';
}
console.log(text); // here not get result in text
}
}
xmlr.open("GET", "data.json", true);
xmlr.send();
also content of data.json are
[
{"member_id":"3","member_first_name":"sachin ","member_last_name":"kumar"},
{"member_id":"4","member_first_name":"abhijit","member_last_name":"kumar"},
{"member_id":"5","member_first_name":"nithin","member_last_name":"ev"},
{"member_id":"6","member_first_name":"tukaram","member_last_name":"kumar"},
{"member_id":"7","member_first_name":"manish","member_last_name":"mungle"},
{"member_id":"8","member_first_name":"dsfdgfh","member_last_name":"dfgfhgfh"},
{"member_id":"9","member_first_name":"hjhgjkhkhj","member_last_name":""},
{"member_id":"10","member_first_name":"hjhkjhggf","member_last_name":""},
{"member_id":"11","member_first_name":"klkjlgfhf","member_last_name":"hjghkj"},
{"member_id":"12","member_first_name":"jkhkjhkl","member_last_name":"hgjgffhfkhj"},
{"member_id":"13","member_first_name":"hfgtjgjhg","member_last_name":"fghjgfhjg"},
{"member_id":"14","member_first_name":"hgjgfjhj","member_last_name":"hgjhgjhfg"},
{"member_id":"15","member_first_name":"cvcxvnvnbv","member_last_name":"nbvcbvc"},
{"member_id":"16","member_first_name":"vbvcnbnbm","member_last_name":"vbxgdssdg"},
{"member_id":"17","member_first_name":"lkfndbfbsd","member_last_name":"dfggfhfh"},
{"member_id":"18","member_first_name":"fghjjdfd","member_last_name":"fgfghghf"},
{"member_id":"19","member_first_name":"ghgfjhfj","member_last_name":"fghfhfd"},
{"member_id":"20","member_first_name":"dfhgfhh","member_last_name":"gdfhfd"}
]
To traverse the object array best available in java script that , traverse the object array using for/in loop than for loop, so my final code which traverse the object array as follow:-
var xmlr = null;
var text = '';
if (window.XMLHttpRequest) {
xmlr = new XMLHttpRequest();
} else {
xmlr = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlr.onreadystatechange = function () {
if (xmlr.readyState == 4 && xmlr.status == 200) {
var data = JSON.parse(xmlr.responseText);
for (var key in data) {
text += '<option>' + data[key].member_first_name + '</option>';
}
console.log(text);
}
}
xmlr.open("GET", "data.json", true);
xmlr.send();

Something is preventing my submit button from functioning

I posted earlier regarding a different topic and want to thank all who helped me out. I've cleaned up my code pretty well (I think) but now when I click 'submit' nothing happens. I suspect the issue is regarding sending data with ajax but there is a problem with the way I've written things to send both text and radio data. Before posting this, I did do a thorough search to see if the question may have been answered in another's post but didn't find it - probably because I'm not astute enough with javascript to relate it to my own code. Anyway, here is a sample http://jsfiddle.net/J2yWQ/78/ If someone could find my issue I would really appreciate it.
function emailWarning() {
var check = document.getElementById("check");
check.className = 'show';
}
function validateEmail(xem) {
var re = /\S+#\S+\.\S+/;
return re.test(xem);
}
function postData() {
email = 'email'+document.getElementById('email').value;
var tt = validateEmail(email);
if (tt == true) {
xmlhttp.open('POST', 'payment.php', true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(myProps.join("&"));
} else {
emailWarning();
}
}
var myProps = [];
function insert() {
try {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
myProps = [];
function addProp(id) {
var input = document.getElementById(id);
if(!input) {
input = document.forms[0][id];
}
var value = encodeURIComponent(input.value);
myProps.push(id + "=" + value);
}
addProp('child_name');
addProp('age');
addProp('hometown');
addProp('boy_girl');
addProp('first_name');
addProp('last_name');
addProp('email');
addProp('address1');
addProp('address2');
addProp('city');
addProp('state');
addProp('zip');
addProp('country');
var flagInvalid = false;
var tempArray = document.getElementsByClassName("required");
for (var i = 0; i < tempArray.length; i++) {
if (tempArray[i].value == "") {
flagInvalid = true;
break;
}
}
if (flagInvalid == false) {
postData();
} else {
var showValidationError = function(id) {
var el = document.getElementById(id);
if (el) {
el.className = 'show';
}
else {
alert('Missing element #' + id);
}
}
showValidationError('log');
for (var i = 1; i < 12; i++) {
showValidationError('log' + i);
}
}
} catch (e) {
alert('An error occured in inert: ' + e);
}
}

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

ajax form issue IE

I have the following code that works in every browser but IE. When click on the submit button of the form I get no response at all from IE.
form has this value: onsubmit="sendform(this);return false;"
<script type="text/javascript">
function makeRequest(url) {
var http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
alert(http_request.status);
//alert(http_request.responseText);
toggleDiv('stylized');
showtoggleDiv('success');
} else {
alert('There was a problem with the request.');
}
}
};
http_request.open('GET', url, true);
http_request.send(null);
}
function sendform(el) {
var sub = el.getElementsByTagName('input');
query = new Array();
for (i in sub) {
if (sub[i].name) {
query.push(sub[i].name + '=' + sub[i].value);
}
}
query = '?' + query.join('&');
makeRequest("http://markburnettinternational.com/sitelokpw/members/test.php" + query);
}
</script>
<script language="javascript">
function toggleDiv(divid) {
if (document.getElementById(divid).style.display == 'none') {
document.getElementById(divid).style.display = 'block';
} else {
document.getElementById(divid).style.display = 'none';
}
}
</script>
<script>
function showtoggleDiv(divid) {
document.getElementById(divid).style.display = 'block';
}
</script>
Turn on the browser's debugger and put a breakpoint in sendform() and walk through it and see what happens. Alternately turning on the javascript console can give you vital feedback about what's going on.
There are at least three problems with this piece of code:
var sub = el.getElementsByTagName('input');
query = new Array();
for (i in sub) {
if (sub[i].name) {
query.push(sub[i].name + '=' + sub[i].value);
}
}
First, always declare your variables within the local scope using var, so use
var query = new Array();
for (var i in sub) {
Second, getElementsByTagName returns a NodeList, which is an array-like object. Never iterate over array(-like object)s using a for … in loop, always use an ordinary for loop.
Third, always use encodeURIComponent to properly encode query parameters:
for (var i = 0, len = sub.length; i < len; i++) {
if (sub[i].name) {
query.push(sub[i].name + '=' + encodeURIComponent(sub[i].value));
}
}
This might solve your IE issue.

Categories

Resources