Wrox Programmer Forums
Go Back   Wrox Programmer Forums > Web Programming > JavaScript > Ajax
|
Ajax the combination of XHTML, CSS, DOM, XML, XSLT, XMLHttpRequest, and JavaScript
Welcome to the p2p.wrox.com Forums.

You are currently viewing the Ajax section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old January 13th, 2010, 12:37 PM
Authorized User
 
Join Date: Sep 2003
Posts: 39
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to Greywacke
Arrow attempting to load xml data into two twodimentional arrays

hi here,
there is a dynamic xml file i'm struggling to parse for the 5 sidebar components on the pages at http://www.ferrety.co.za/fab/?p=0.

the xml files the javascript is supposed to parse are the following 5:
http://www.ferrety.co.za/fab/scripts/ajax_stats.php?q=0
http://www.ferrety.co.za/fab/scripts/ajax_stats.php?q=1
http://www.ferrety.co.za/fab/scripts/ajax_stats.php?q=2
http://www.ferrety.co.za/fab/scripts/ajax_stats.php?q=3
http://www.ferrety.co.za/fab/scripts/ajax_stats.php?q=4

here is the javascript used:
Code:
// Regions AJAX & DHTML
// xml request
var http_request = false;
var parents = new Array();
function makeRequest(method, url, parameters) {
    http_request = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            // set type accordingly to anticipated content type
            http_request.overrideMimeType('text/xml');
            //http_request.overrideMimeType('text/html');
        }
    } 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('Cannot create XMLHTTP instance');
        return false;
    }
    http_request.onreadystatechange = alertContents;
    url += (method=="GET")?parameters:"";
    http_request.open(method, url, true);
    if (method == "POST") {
        http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http_request.setRequestHeader("Content-length", parameters.length);
        http_request.setRequestHeader("Connection", "close");
    }
    http_request.send((method=="GET")?null:parameters);
}
// xml parser, battling to parse the xml returned from the post and get requests
function alertContents() {
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {
            var xmldoc = http_request.responseXML;
            //if (this.responseText) alert(this.responseText);
            // parse months if available
            var i = 0;
            var arrMonths = new Array();
            var rows1 = xmldoc.getElementsByTagName("statmonths");
            for (var r = 0; r < rows1.length; r++) {
                if (rows1[r].attributes.length > 0) {
                    arrMonths[i] = rows1[r].attributes.getNamedItem("name").nodeValue;
                    i++;
                }
                for (var c = 0; c < rows1[r].childNodes.length; c++) {
                    var month = rows1[r].childNodes[c];
                    if (month.attributes.length > 0) {
                        arrMonths[i] = new Array();
                        for (n = 0; n > month.attributes.length; n++) {
                            if (month.attributes[n]) arrMonths[i][n] = month.attributes[n].value;
                        }
                        i++;
                    }
                }
            }
            // parse records
            var x = 0;
            var arrStats = new Array();
            var rows2 = xmldoc.getElementsByTagName("statistics");
            for (var r = 0; r < rows2.length; r++) {
                if (rows2[r].attributes.length > 0) {
                    arrStats[x] = rows2[r].attributes.getNamedItem("name").nodeValue;
                    x++;
                }
                for (var c = 0; c < rows2[r].childNodes.length; c++) {
                    var record = rows2[r].childNodes[c];
                    if (record.nodeName == "record") {
                        arrStats[x] = new Array();
                        for (e = 0; e > record.attributes.length; e++) {
                            if (record.attributes[x]) arrStats[x][e] = record.attributes[x].value;
                        }
                        x++;
                    }
                }
            }
            alert(arrMonths.join(",",";")+"\n"+
                  arrStats.join(",",";"));
            //if (xmldoc.getElementsByTagName("sql")[0]) if (xmldoc.getElementsByTagName("sql")[0].firstChild) var sql = xmldoc.getElementsByTagName("sql")[0].firstChild.data; if (sql != "") alert(sql);
        } else {
            alert('There was a problem with the request.');
        }
        document.getElementById("ajaxbg").style.visibility = "hidden";
        sessrem = sesstot;
    }
}
// instantiate ajax requests
function ajaxRequest(comp) {
    document.getElementById("ajaxbg").style.visibility = "visible";
    switch (comp) {
        case 1: // top10regions
            var sel = document.getElementById("list_regionst10months");
            var poststr = "m=" + encodeURIComponent((sel == undefined)?"":sel.options[sel.selectedIndex].value);
            makeRequest("POST", "scripts/ajax_stats.php?q=1", poststr);
            break;
        case 2: // top10services
            var sel = document.getElementById("list_servicest10months");
            var poststr = "m=" + encodeURIComponent((sel == undefined)?"":sel.options[sel.selectedIndex].value);
            makeRequest("POST", "scripts/ajax_stats.php?q=2", poststr);
            break;
        case 3: // top10suppliers
            var sel = document.getElementById("list_supplierst10months");
            var poststr = "m=" + encodeURIComponent((sel == undefined)?"":sel.options[sel.selectedIndex].value);
            makeRequest("POST", "scripts/ajax_stats.php?q=3", poststr);
            break;
        case 4: // latest10transactions
            makeRequest("GET", "scripts/ajax_stats.php?q=4", "");
            break;
        default: // top10consumers
            var sel = document.getElementById("list_consumerst10months");
            var poststr = "m=" + encodeURIComponent((sel == undefined)?"":sel.options[sel.selectedIndex].value);
            makeRequest("POST", "scripts/ajax_stats.php?q=0", poststr);
    }
}
// onload event handler
window.onload = function () {
    ajaxRequest(0); // top10consumers
    ajaxRequest(1); // top10regions
    ajaxRequest(2); // top10services
    ajaxRequest(3); // top10suppliers
    ajaxRequest(4); // latest10transactions
}
i am attempting to return the arrays as the following:
Code:
arrMonths:
selectid,
{monthname, monthvalue, (selected)},
{monthname, monthvalue},
etc.

arrStats:
divid,
{statname, statvalue}, {statname, statvalue},
{statname, statvalue}, {statname, statvalue},
etc.
they make the httpRequests, and only receive one. i'm struggling to parse the documents into two arrays, the last document would have the first array undefined. the arrays are multidimentional.
what might i be doing wrong here? i keep getting the first array as empty, the second only the div name alerted and empty attributes following it.
__________________
Sincerely,
Pierre "Greywacke" du Toit
pierre@greywacke.co.za
don't worry about my 0 thankyou's either way, i would say thank you should you help, and i will gladly help others when this work rush is over.

Last edited by Greywacke; January 14th, 2010 at 06:21 AM.. Reason: code updated
 
Old January 13th, 2010, 07:19 PM
Authorized User
 
Join Date: Sep 2003
Posts: 39
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to Greywacke
Question success! well somewhat...

now i have managed to get the 5 multiple calls, just battling to parse the xml... i am struggling to parse the month tags and their attributes as well as the statistic attributes and their tags, and have been struggling the past few days - here is the most recent code:

here is the complete script for the overview page. once this is completed, i will integrate it into the other 6 pages.
Code:
// Regions AJAX & DHTML
// xml request
function makeRequest(method, url, parameters) {
    var http_request = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            // set type accordingly to anticipated content type
            http_request.overrideMimeType('text/xml');
            //http_request.overrideMimeType('text/html');
        }
    } 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('Cannot create XMLHTTP instance');
        return false;
    }
    http_request.onreadystatechange = function() {
        alertContents(http_request);
    }
    url += (method=="GET")?parameters:"";
    http_request.open(method, url, true);
    if (method == "POST") {
        http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http_request.setRequestHeader("Content-length", parameters.length);
        http_request.setRequestHeader("Connection", "close");
    }
    http_request.send((method=="GET")?null:parameters);
}
// xml parser, battling to parse the xml returned from the post and get requests
function alertContents(http_request) {
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {
            var xmldoc = http_request.responseXML;
            //alert(http_request.responseText);
            // parse months if available
            var i = 0;
            var arrMonths = new Array();
            var rows1 = xmldoc.getElementsByTagName("statmonths");
            for (var r = 0; r < rows1.length; r++) {
                if (rows1[r].attributes) {
                    arrMonths[i] = rows1[r].attributes.getNamedItem("name").nodeValue;
                    i++;
                }
                var months = rows1[r].getElementsByTagName("month");
                for (var c = 0; c < months.length; c++) {
                    var month = months[c];
                    if (month.attributes) {
                        arrMonths[i] = new Array();
                        for (n = 0; n > month.attributes.length; n++) {
                            arrMonths[i][n] = month.attributes[n].value;
                        }
                        i++;
                    }
                }
            }
            // parse records
            var x = 0;
            var arrStats = new Array();
            var rows2 = xmldoc.getElementsByTagName("statistics");
            for (var r = 0; r < rows2.length; r++) {
                if (rows2[r].attributes) {
                    arrStats[x] = rows2[r].attributes.getNamedItem("name").nodeValue;
                    x++;
                }
                var records = rows2[r].getElementsByTagName("record");
                for (var c = 0; c < records.length; c++) {
                    var record = records[c];
                    if (record.attributes) {
                        arrStats[x] = new Array();
                        for (e = 0; e > record.attributes.length; e++) {
                            arrStats[x][e] = record.attributes[e].value;
                        }
                        x++;
                    }
                }
            }
            alert(arrMonths.join(",",";")+"\n"+arrStats.join(",",";"));
            insertstats(arrMonths,arrStats);
            //if (xmldoc.getElementsByTagName("sql")[0]) if (xmldoc.getElementsByTagName("sql")[0].firstChild) var sql = xmldoc.getElementsByTagName("sql")[0].firstChild.data; if (sql != "") alert(sql);
        } else {
            alert('There was a problem with the request.');
        }
        document.getElementById("ajaxbg").style.visibility = "hidden";
        sessrem = sesstot;
    }
}
// instantiate ajax requests
function ajaxRequest(obj) {
    document.getElementById("ajaxbg").style.visibility = "visible";
    var job = obj.value;
    switch (job || obj) {
        case 0: // top10consumers
            var sel = document.getElementById("list_consumerst10months");
            var poststr = "m=" + encodeURIComponent((sel == undefined)?"":sel.options[sel.selectedIndex].value);
            makeRequest("POST", "scripts/ajax_stats.php?q=0", poststr);
            break;
        case 1: // top10regions
            var sel = document.getElementById("list_regionst10months");
            var poststr = "m=" + encodeURIComponent((sel == undefined)?"":sel.options[sel.selectedIndex].value);
            makeRequest("POST", "scripts/ajax_stats.php?q=1", poststr);
            break;
        case 2: // top10services
            var sel = document.getElementById("list_servicest10months");
            var poststr = "m=" + encodeURIComponent((sel == undefined)?"":sel.options[sel.selectedIndex].value);
            makeRequest("POST", "scripts/ajax_stats.php?q=2", poststr);
            break;
        case 3: // top10suppliers
            var sel = document.getElementById("list_supplierst10months");
            var poststr = "m=" + encodeURIComponent((sel == undefined)?"":sel.options[sel.selectedIndex].value);
            makeRequest("POST", "scripts/ajax_stats.php?q=3", poststr);
            break;
        case 4: // latest10transactions
            makeRequest("GET", "scripts/ajax_stats.php?q=4", "");
            break;
    }
    return true;
}
// dhtml populator
function insertstats(arrM,arrS) {
    // arrM = selectid, {mName, mValue, mSelected}, etc.
    // arrS = divid, {sName, sValue), etc.
}
// onload event handler
window.onload = function () {
    var ret;
    ret = ajaxRequest(0); // top10consumers
    ret = ajaxRequest(1); // top10regions
    ret = ajaxRequest(2); // top10services
    ret = ajaxRequest(3); // top10suppliers
    ret = ajaxRequest(4); // latest10transactions
    return ret;
}
__________________
Sincerely,
Pierre "Greywacke" du Toit
pierre@greywacke.co.za
don't worry about my 0 thankyou's either way, i would say thank you should you help, and i will gladly help others when this work rush is over.

Last edited by Greywacke; January 14th, 2010 at 04:51 AM.. Reason: success! well somewhat...
 
Old January 14th, 2010, 05:58 AM
Authorized User
 
Join Date: Sep 2003
Posts: 39
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to Greywacke
Angry AJAX: definately getting blank/undefined values in subarrays...

this code has been edited, both the alertContents and the insertstats functions... i can now retrieve numeric attributes, but not string attributes apart from the section names... wth? even tried renaming the xml attributes to statnames in case they were clashing somehow, but to no avail.
i keep getting undefined as the those values...
Code:

Code:
function alertContents(http_request) {
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {
            var xmldoc = http_request.responseXML;
            //alert(http_request.responseText);
            // parse months if available
            var i = 0;
            var arrMonths = new Array();
            var rows1 = xmldoc.getElementsByTagName("statmonths");
            for (var r = 0; r < rows1.length; r++) {
                var months = rows1[r].getElementsByTagName("month");
                if (rows1[r].attributes) {
                    arrMonths[i] = rows1[r].attributes.getNamedItem("name").nodeValue;
                    i++;
                }
                for (var c = 0; c < months.length; c++) {
                    var month = months[c];
                    if (month.attributes) {
                        arrMonths[i] = new Array();
                        arrMonths[i][0] = month.attributes.getNamedItem("text").nodeValue;
                        arrMonths[i][1] = month.attributes.getNamedItem("value").nodeValue;
                        if (month.attributes.getNamedItem("selected")) arrMonths[i][2] = month.attributes.getNamedItem("selected").nodeValue;
                        i++;
                    }
                }
            }
            // parse records
            var x = 0;
            var arrStats = new Array();
            var rows2 = xmldoc.getElementsByTagName("statistics");
            for (var r = 0; r < rows2.length; r++) {
                var records = rows2[r].getElementsByTagName("record");
                if (rows2[r].attributes) {
                    arrStats[x] = rows2[r].attributes.getNamedItem("name").nodeValue;
                    x++;
                }
                for (var c = 0; c < records.length; c++) {
                    var record = records[c];
                    if (record.attributes) {
                        arrStats[x] = new Array();
                        arrStats[x][0] = record.attributes.getNamedItem("statname").nodeValue;
                        if (arrMonths[0]) {
                            arrStats[x][1] = record.attributes.getNamedItem("leads").nodeValue;
                        } else {
                            arrStats[x][1] = record.attributes.getNamedItem("amount").nodeValue;
                        }
                        x++;
                    }
                }
            }
            //alert(arrMonths+"\n"+arrStats);
            insertstats(arrMonths,arrStats);
            //if (xmldoc.getElementsByTagName("sql")[0]) if (xmldoc.getElementsByTagName("sql")[0].firstChild)
            //var sql = xmldoc.getElementsByTagName("sql")[0].firstChild.data; if (sql != "") alert(sql);
        } else {
            alert('There was a problem with the request.');
        }
        document.getElementById("ajaxbg").style.visibility = "hidden";
        sessrem = sesstot;
    }
}
function insertstats(arrM,arrS) {
    // arrM = selectid, {mName, mValue, mSelected}, etc.
    if (arrM != undefined) {
        sel = document.createElement("select");
        sel.id = arrM[0];
        sel.setAttribute("name",arrM[0]);
        sel.setAttribute("accesskey","h");
        switch (sel.id) {
            case "list_consumerst10months":
                sel.setAttribute("onchange","return ajaxRequest(0);");
                break;
            case "list_regionst10months":
                sel.setAttribute("onchange","return ajaxRequest(1);");
                break;
            case "list_servicest10months":
                sel.setAttribute("onchange","return ajaxRequest(2);");
                break;
            case "list_supplierst10months":
                sel.setAttribute("onchange","return ajaxRequest(3);");
                break;
        }
        for (var i = 1; i < arrM.length; i++) {
            //alert(arrM[i]);
            var opt = document.createElement("option");
            opt.text = arrM[i][0];
            opt.value = arrM[i][1];
            if (arrM[i][2]) opt.selected = true;
            try {
                sel.add(opt, null); // standards compliant; doesn't work in IE
            }
            catch(ex) {
                sel.add(opt); // IE only
            }
        }
        label = document.createElement("label");
        label.setAttribute("for", arrM[0]);
        label.innerHTML = "View Mont<u>h</u>";
        p = document.createElement("p");
        p.appendChild(label);
        p.appendChild(sel);
    }
    // arrS = divid, {sName, sValue), etc.
    var div = document.getElementById(arrS[0]);
    div.innerHTML = "";
    if (arrM[0] != undefined) div.appendChild(p);
    else {
        var sa = document.createElement("div");
        sa.setAttribute("class","statcol2");
        sa.innerHTML = "&nbsp;";
        div.appendChild(sa);
        var sd = document.createElement("div");
        sd.setAttribute("class","statcol1");
        sd.innerHTML = "&nbsp;";
        div.appendChild(sd);
    }
    var ta = document.createElement("div");
    ta.setAttribute("class","statcol2");
    ta.innerHTML = "<strong>Name</strong>";
    div.appendChild(ta);
    var td = document.createElement("div");
    td.setAttribute("class","statcol1");
    td.innerHTML = "<strong>"+((arrM[0])?"Leads":"Amount")+"</strong>";
    div.appendChild(td);
    for (i = 1; i < arrS.length+1; i++) {
        //alert(arrS[i]);
        var sa = document.createElement("div");
        sa.setAttribute("class","statcol2");
        sa.innerHTML = (arrS[i])?arrS[i][2]:"&nbsp;";
        div.appendChild(sa);
        var sd = document.createElement("div");
        sd.setAttribute("class","statcol1");
        sd.innerHTML = (arrS[i])?arrS[i][1]:"&nbsp;";
        div.appendChild(sd);
    }
}
this code can be seen in action at http://www.ferrety.co.za/fab/?p=0.
__________________
Sincerely,
Pierre "Greywacke" du Toit
pierre@greywacke.co.za
don't worry about my 0 thankyou's either way, i would say thank you should you help, and i will gladly help others when this work rush is over.

Last edited by Greywacke; January 14th, 2010 at 09:50 AM.. Reason: url added
 
Old January 14th, 2010, 11:25 AM
Authorized User
 
Join Date: Sep 2003
Posts: 39
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to Greywacke
Talking

awesome, i finally got the ajax working by referencing the attributes directly :D
__________________
Sincerely,
Pierre "Greywacke" du Toit
pierre@greywacke.co.za
don't worry about my 0 thankyou's either way, i would say thank you should you help, and i will gladly help others when this work rush is over.





Similar Threads
Thread Thread Starter Forum Replies Last Post
attempting to load xml data into two twodimentional arrays Greywacke Ajax 0 January 13th, 2010 12:31 PM
Help: Arrays using JavaScript,/XML in IE celticbhoy Ajax 0 December 10th, 2007 01:15 PM
Read data from XML then load it into combo box edizone XML 4 October 4th, 2006 05:11 AM
How Can I Use Arrays with SQL Server Data? Lucy SQL Server ASP 4 June 14th, 2004 01:20 PM
Converting an XML data island to 2 arrays NeilAtWork Classic ASP XML 0 April 14th, 2004 10:38 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.