Wrox Programmer Forums

Need to download code?

View our list of code downloads.

Go Back   Wrox Programmer Forums > Web Programming > JavaScript > Ajax
Password Reminder
Register
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read
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 tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developers’ questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
DRM-free e-books 300x50
Reply
 
Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old June 2nd, 2008, 05:53 PM
Registered User
 
Join Date: Jun 2008
Location: London, , .
Posts: 4
Thanks: 0
Thanked 0 Times in 0 Posts
Default Problem with XMLHttpPost using incorrect values

 I have an issue with some ajax code where the variables I am passing to my xmlHTTP function are not getting set correctly and the function thats called on a successful 200 status code is incorrect.

I have a series of linked listboxes and when the top one changes a function is called that takes the selected values, passes them to my ajax function that then returns a list of the correct list items for the 2nd listbox. This 2nd list is then populated and then the change event is again fired that calls the ajax function that returns the correct list items for the 3rd list. A user may have saved values for all 3 lists and when re-visiting the page all lists should show the correct items.

I think the problem is in the actual xmlHTTP function and the values for param1 and param2 which hold the name of the listbox the result function should affect which I am trying to re-pass back in as literals to the result function.

function xmlhttpPost(strURL, strSubmit, strResultFunc, param1, param2, param3) {
    console.debug("IN xmlhttp post URL = " + strURL + " submit = " + strSubmit + " func = " + strResultFunc + " param1 = " + param1 + " param2 = " + param2 + " param3 = " + param3)
    if(bAllowAjax==undefined){
        bAllowAjax = AllowAjax();
    }
    if(!bAllowAjax || typeof(xmlhttp)!="object"){
        //redirect user to the browser compatibility test page as the site will not work for them
        //unless we are already on that page
        cl = window.location.href;
        if(cl.indexOf('/userTest.asp')==-1){
            window.location.href = "/userTest.asp?er=1"
        }
        return;
    }else{
        xmlhttp.open('POST', strURL, true);
        xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xmlhttp.onreadystatechange = function() {
                    if (xmlhttp.readyState == 4) {
                        strResponse = xmlhttp.responseText;
                        console.debug("xmlhttp.readyState = 4 ListToPopulate = " + param1 + ", PageName = " + param2);
                        var statusCode = -1;
                        try{
                            statusCode = xmlhttp.status;
                            console.debug("xmlhttpPost; xmlhttpPost.status " + xmlhttp.status);
                            switch (xmlhttp.status) {
                                    // Page-not-found error
                                    case 404:
                                            alert('Error: Not Found. The requested URL ' +
                                                    strURL + ' could not be found.');
                                            break;
                                    // Display results in a full window for server-side errors
                                    case 500:
                                            handleErrFullPage(strResponse);
                                            break;
                                    default:
                                            // Call JS alert for custom error or debug messages
                                            if (strResponse.indexOf('Error:') > -1 ||
                                                    strResponse.indexOf('Debug:') > -1) {
                                                    alert(strResponse);
                                            }
                                            // Call the desired result function
                                                else {
                                                    if(strResultFunc!=''){
                                                        console.debug("xmlhttpPost; call function " + strResultFunc + " ( "+ strResponse + ", " + ListToPopulate + ", "+ param2 + ")");
                                                        console.trace();
                                                        //var thisFunc = strResultFunc+"(strResponse,'"+ param1+"','"+param2+"')";
                                                        //var thisFunc = strResultFunc+"(strResponse,'"+param1+"',"+param2+ ");}"
                                                        //console.debug("set thisFunc = " + thisFunc)
                                                        console.debug("call thisFunc = "+strResultFunc + '(strResponse,param1,param2);' )
                                                        console.debug("param1 = " + param1 + " param2 = " + param2);
                                                        eval(strResultFunc + '(strResponse,param1,param2);');
                                                        //return eval(thisFunc);
                                                        console.debug("after thisFunc")
                                                    }
                                            }
                                            break;
                            }
                        }catch(e){return;}
                }
            }
        xmlhttp.send(strSubmit);
    }
}

Here is the debug trace when my test page is run with 3 linked lists (Region > City > Village)

The first list Region links correctly to City and the correct values are populated but when City tries to link to Village the XMLHttpPost function is still using the values for param1,param2 that were set for the previous call so instead of village getting populated city gets re-populated with incorrect values. However as city has then been affected again it goes on to call Village again and this time the correct values for param1,param2 get passed in and the response function does affect village.

IN selectField = Region, test, true, false customObjFuncs.js (line 27)
selectField; childName for Region is City customObjFuncs.js (line 34)
selectField; Region has a child 'City' so call ajax to populate customObjFuncs.js (line 40)
selectField; qry is == /scripts/ajax/categories.asp, cat=7787%2C7785%2C7788, "populateLinkedList", City, test customObjFuncs.js (line 60)
IN xmlhttp post URL = /scripts/ajax/categories.asp submit = cat=7787%2C7785%2C7788 func = populateLinkedList param1 = City param2 = test param3 = undefined globalFuncs.js (line 266)
POST scripts/ajax/categories.asp (750ms) globalFuncs.js (line 333)
xmlhttp.readyState = 4 param1 = City, param2 = test globalFuncs.js (line 288)
xmlhttpPost; xmlhttpPost.status 200 globalFuncs.js (line 294)
xmlhttpPost; call function populateLinkedList ( 18 7797|Barnsley 7798|Doncaster 7800|Rotherham 7801|Sheffield 7799|Other - South Yorkshire 7802|Harrogate 7803|Malton 7804|Northallerton 7806|Ripon 7807|Scarborough 7808|Selby 7809|York 7805|Other - North Yorkshire 7810|Bradford 7811|Huddersfield 7812|Leeds 7814|Wakefield 7813|Other - West Yorkshire , City, test) globalFuncs.js (line 315)
onreadystatechange()globalFuncs.js (line 316)
call thisFunc = populateLinkedList(strResponse,param1,param2); globalFuncs.js (line 320)
param1 = City param2 = test globalFuncs.js (line 321)
IN populateLinkedList for = City page = test strIn=18 7797|Barnsley 7798|Doncaster 7800|Rotherham 7801|Sheffield 7799|Other - South Yorkshire 7802|Harrogate 7803|Malton 7804|Northallerton 7806|Ripon 7807|Scarborough 7808|Selby 7809|York 7805|Other - North Yorkshire 7810|Bradford 7811|Huddersfield 7812|Leeds 7814|Wakefield 7813|Other - West Yorkshire customObjFuncs.js (line 82)
populateLinkedList; object City is in chain so fire OnPopulate to populate its child which is Village customObjFuncs.js (line 131)
IN selectField = City, test, false, false customObjFuncs.js (line 27)
selectField; childName for City is Village customObjFuncs.js (line 34)
selectField; City has a child 'Village' so call ajax to populate customObjFuncs.js (line 40)
selectField; qry is == /scripts/ajax/categories.asp, cat=0, "populateLinkedList", Village, test customObjFuncs.js (line 60)
IN xmlhttp post URL = /scripts/ajax/categories.asp submit = cat=0 func = populateLinkedList param1 = Village param2 = test param3 = undefined globalFuncs.js (line 266)
POST scripts/ajax/categories.asp (547ms) globalFuncs.js (line 333)
after thisFunc globalFuncs.js (line 324)
xmlhttp.readyState = 4 param1 = City, param2 = test globalFuncs.js (line 288)
xmlhttpPost; xmlhttpPost.status 200 globalFuncs.js (line 294)
xmlhttpPost; call function populateLinkedList ( 0 , City, test) globalFuncs.js (line 315)
onreadystatechange() globalFuncs.js (line 316)
call thisFunc = populateLinkedList(strResponse,param1,param2); globalFuncs.js (line 320)
param1 = City param2 = testglobalFuncs.js (line 321)
IN populateLinkedList for = City page = test strIn=0 customObjFuncs.js (line 82)
populateLinkedList; object City is in chain so fire OnPopulate to populate its child which is Village customObjFuncs.js (line 131)
IN selectField = City, test, false, false customObjFuncs.js (line 27)
selectField; childName for City is Village customObjFuncs.js (line 34)
selectField; City has a child 'Village' so call ajax to populate customObjFuncs.js (line 40)
selectField; qry is == /scripts/ajax/categories.asp, cat=0, "populateLinkedList", Village, test customObjFuncs.js (line 60)
IN xmlhttp post URL = /scripts/ajax/categories.asp submit = cat=0 func = populateLinkedList param1 = Village param2 = test param3 = undefined globalFuncs.js (line 266)
POST scripts/ajax/categories.asp (547ms)globalFuncs.js (line 333)
after thisFuncglobalFuncs.js (line 324)
xmlhttp.readyState = 4 param1 = Village, param2 = test globalFuncs.js (line 288)
xmlhttpPost; xmlhttpPost.status 200 globalFuncs.js (line 294)
xmlhttpPost; call function populateLinkedList ( 0 , Village, test) globalFuncs.js (line 315)
onreadystatechange()globalFuncs.js (line 316)
call thisFunc = populateLinkedList(strResponse,param1,param2); globalFuncs.js (line 320)
param1 = Village param2 = testglobalFuncs.js (line 321)
IN populateLinkedList for = Village page = test strIn=0 customObjFuncs.js (line 82)
after thisFunc


The part of the trace that shows me passing in "Village" for param1 but when debugging param1 is actually "City" is here:

selectField; City has a child 'Village' so call ajax to populate customObjFuncs.js (line 40)
selectField; qry is == /scripts/ajax/categories.asp, cat=0, "populateLinkedList", Village, test customObjFuncs.js (line 60)
IN xmlhttp post URL = /scripts/ajax/categories.asp submit = cat=0 func = populateLinkedList param1 = Village param2 = test param3 = undefined globalFuncs.js (line 266)
POST scripts/ajax/categories.asp (547ms) globalFuncs.js (line 333)
after thisFunc globalFuncs.js (line 324)
xmlhttp.readyState = 4 param1 = City, param2 = test globalFuncs.js (line 288)
xmlhttpPost; xmlhttpPost.status 200 globalFuncs.js (line 294)
xmlhttpPost; call function populateLinkedList ( 0 , City, test) globalFuncs.js (line 315)

Can someone see what I am doing wrong or help me with a workaround. I am thinking of actually passing into the .asp that returns the categories the actual parameters so that the response contains them rather than trying to add these values into the function as literals.

For the main bit of code from a test page see below (some helper functions have been removed)

<html>
<head>
<script type="text/Javascript">
<!--
    // functions in globalFuncs handle the adding of events, xmlHTTP posting etc


    var arrLinkedLists = [];
    arrLinkedLists[0] = new LinkedList("test","Region","City",true,false,true, "","Any","No Records");
    arrLinkedLists[1] = new LinkedList("test","City","Village",false,false,fal se,"","Any","No Records");
    arrLinkedLists[2] = new LinkedList("test","Village","",false,false,false," ","Any","No Records");



function LinkedList(page,name,childName,isParent,isRequired ,popAllChild,selItems,AnyOption,NoRecords){
//console.debug("New LinkedList name = "+ name + " child = "+ childName);
    this.Page = page;
    this.Name = name;
    this.ChildName = childName;
    this.IsParent = isParent;
    this.Required = isRequired;
    this.SelItems = selItems;
    this.AnyOption = AnyOption;
    this.NoRecords = NoRecords;
    this.PopAllChild= popAllChild;
    if(this.ChildName!=""){
        this.InChain = true;
        //console.debug("InChain set onPopulate");
        var self = this;
        this.OnPopulate = function(){selectField(self.Name,self.Page,(self.P opAllChild&&self.IsParent)?true:false,self.Require d);}
    }else{
        this.InChain = false;
    }
}


function selectField(name,page,popAll,req)
{
    console.debug("IN selectField = " + name + ", " + page + ", " + popAll + ", " + req);
    if(bAllowAjax==undefined){bAllowAjax=AllowAjax();}
    if(!bAllowAjax){return;}
    //if this list has no child no need to collect values to pas to xmlHTTP to populate child with results
    var objList = getListObject(name,page,false);
    if(objList.InChain){
        var childName = objList.ChildName;
        console.debug("selectField; childName for " + name + " is " + objList.ChildName);
    }
    if(objList.ChildName==""){
        console.debug("selectField; " + objList.Name + " has no child so no need to call ajax to populate any other lists.")
        return;
    }else{
        console.debug("selectField; " + name + " has a child '" + childName + "' so call ajax to populate");
    }
    var catID="";
    //console.debug("get element for 'lst"+name+"'");
    var el = getEl("lst"+name);
    //console.debug("typeof = " + typeof(el));
    for(var x=0;x<el.options.length;x++){
        if((popAll) || el.options[x].selected){
            catID+=el.options[x].value+",";
        }
    }
    if(catID==""||catID==","){catID=0;}
    else{
        if(catID.substring(catID.length-1,catID.length)==",")
            catID=catID.substring(0,catID.length-1);
        if(catID.substring(0,1)==",")
            catID=catID.substring(1,catID.length);
    }
    var enc=encodeURIComponent||escape;
    var qry = 'cat=' + enc(catID);
    console.debug('selectField; qry is == \n' + '/ajax/categories.asp' + ', ' + qry + ', "populateLinkedList", ' + childName + ', ' + page)
    xmlhttpPost('/ajax/categories.asp',qry,'populateLinkedList',childName ,page);
// console.debug("return from select func for " + name);
}
// function to return a reference to the linked list object either for an item or that items child
function getListObject(name,page,getChild)
{
    var objList;
    if(arrLinkedLists.length>=0){
        for(var x=0;x<arrLinkedLists.length;x++){
            if(arrLinkedLists[x].Name==name && arrLinkedLists[x].Page==page){
                if(!getChild){
                    return arrLinkedLists[x];
                }else{
                    return getListObject(arrLinkedLists[x].ChildName,page,false);
                }
            }
        }
    }
    return objList;
}
function populateLinkedList(strIn,name,page) {
    console.debug('IN populateLinkedList for = ' + name + ' page = ' + page + ' strIn=' + strIn)
    var content = "";
    var rowCount = 0;
    var responseArray;
    var contentArray;
    var addNo = 0;
    var objList = getListObject(name,page,false); //get a reference to the object we need to populate by name
    if(typeof objList!="object"){return;}
    // Split row count from main results
    responseArray = strIn.split('\n\n');
    // Get row count
    rowCount = responseArray[0];
    //console.debug(rowCount + ' row(s) returned.');
    // Actual records are in second array item
    // Split them into the array of DB rows
    contentArray = responseArray[1].split('\n');
    var elTarget="lst"+objList.Name;
    //console.debug("populate child of "+ name + " which is " + objList.Name);
    if(getEl(elTarget)){
        var elT = getEl(elTarget);
        elT.options.length=0;
        if(contentArray.length-1>0){
            if(!objList.Required){
                elT.options[0]=new Option();
                elT.options[0].value="";
                elT.options[0].text=objList.AnyOption;
                addNo = 1;
            }
            var sel = objList.SelItems;
            for (var i = 0; i < contentArray.length-1; i++) {
                // Create new category object for each list item
                objCategory = new categoryListing(contentArray[i]);
                elT.options[i+addNo]=new Option();
                elT.options[i+addNo].value=objCategory.CategoryID;
                elT.options[i+addNo].text=objCategory.Category;
                if(sel.length>=0){
                    for(var s=0;s<sel.length;s++){
[s]                       if(objCategory.CategoryID==Trim(sel )){
                            elT.options[i+addNo].selected = true;
                        }
                    }
                }
            }
        }else{
            elT.options[0]=new Option();
            elT.options[0].value = "";
            elT.options[0].text = objList.NoRecords;
        }
        if(objList.InChain){
            console.debug("populateLinkedList; object " + objList.Name + " is in chain so fire OnPopulate to populate its child which is " + objList.ChildName);
            objList.OnPopulate();
        }
    }
}


function xmlhttpPost(strURL, strSubmit, strResultFunc, param1, param2, param3) {
    console.debug("IN xmlhttp post URL = " + strURL + " submit = " + strSubmit + " func = " + strResultFunc + " param1 = " + param1 + " param2 = " + param2 + " param3 = " + param3)
    if(bAllowAjax==undefined){
        bAllowAjax = AllowAjax();
    }
    if(!bAllowAjax || typeof(xmlhttp)!="object"){
        //redirect user to the browser compatibility test page as the site will not work for them
        //unless we are already on that page
        cl = window.location.href;
        //alert(cl)
        if(cl.indexOf('/userTest.asp')==-1){
            //alert("redirect to usertest")
            window.location.href = "/userTest.asp?er=1"
        }
        return;
    }else{
// alert("get data = "+ strURL + " , " + strSubmit)
        xmlhttp.open('POST', strURL, true);
        xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xmlhttp.onreadystatechange = function() {
                    var ListToPopulate = param1,PageName = param2;
                    if (xmlhttp.readyState == 4) {
                        strResponse = xmlhttp.responseText;
                        console.debug("xmlhttp.readyState = 4 param1 = " + param1 + ", param2 = " + param2);
                        //alert("response = " + strResponse + " for " + strURL + " qry = "+ strSubmit);
                        //alert("status = " + xmlhttp.status)
                        var statusCode = -1;
                        try{
                            statusCode = xmlhttp.status;
                            console.debug("xmlhttpPost; xmlhttpPost.status " + xmlhttp.status);
                            switch (xmlhttp.status) {
                                    // Page-not-found error
                                    case 404:
                                            alert('Error: Not Found. The requested URL ' +
                                                    strURL + ' could not be found.');
                                            break;
                                    // Display results in a full window for server-side errors
                                    case 500:
                                            handleErrFullPage(strResponse);
                                            break;
                                    default:
                                            //alert("full response = " + strResponse)
                                            // Call JS alert for custom error or debug messages
                                            if (strResponse.indexOf('Error:') > -1 ||
                                                    strResponse.indexOf('Debug:') > -1) {
                                                    alert(strResponse);
                                            }
                                            // Call the desired result function
                                            else {
                                                    if(strResultFunc!=''){
                                                        console.debug("xmlhttpPost; call function " + strResultFunc + " ( "+ strResponse + ", " + ListToPopulate + ", "+ param2 + ")");
                                                        console.trace();
                                                        //var thisFunc = strResultFunc+"(strResponse,'"+ param1+"','"+param2+"')";
                                                        //var thisFunc = strResultFunc+"(strResponse,'"+param1+"',"+param2+ ");}"
                                                        //console.debug("set thisFunc = " + thisFunc)
                                                        console.debug("call thisFunc = "+strResultFunc + '(strResponse,param1,param2);' )
                                                        console.debug("param1 = " + param1 + " param2 = " + param2);
                                                        eval(strResultFunc + '(strResponse,param1,param2);');
                                                        //return eval(thisFunc);
                                                        console.debug("after thisFunc")
                                                    }
                                            }
                                            break;
                            }
                        }catch(e){return;}
                }
            }
        //strSubmit
        xmlhttp.send(strSubmit);
        //alert(xmlhttp.responseText)
    }
}

    // this will loop through array of objects
    function run(){
        for(var x=0;x<arrLinkedLists.length;x++){
            alert("obj = " + arrLinkedLists[x].Name + " onPopulate = " + arrLinkedLists[x].OnPopulate);
        }
    }


//-->
</script>
</head>

<body>
<h1>Test</h1>
<form name="frmTest" id="frmTest">

    <label>Region</label>
    <select name="lstRegion" id="lstRegion">
        <option value="">Any</option>
        <option value="7787">Leeds</option>
        <option value="7785">Hull</option>
        <option value="7788">Sheffield</option>
    </select>
    <br /><br />

    <label>City</label>
    <select name="lstCity" id="lstCity">
        <option value="">Please select from above</option>
    </select>
    <br /><br />

    <label>Village</label>
    <select name="lstVillage" id="lstVillage">
        <option value="">Please select from above</option>
    </select>

    <input type="button" name="click" onclick="run();" />
</form>


<script type="text/javascript">
<!--
var myelem1 = getEl('lstRegion');
addEvent( myelem1, "change", function(){ selectField("Region","test",true,false); }) ;

var myelem2 = getEl('lstCity');
addEvent( myelem2, "change", function(){ selectField("City","test",false,false); }) ;
//-->
</script>


</body>
</html>

Thanks in advance for any help given.



Thanks in advance for any help.


Reply With Quote
  #2 (permalink)  
Old June 2nd, 2008, 07:14 PM
Friend of Wrox
 
Join Date: Jun 2008
Location: Snohomish, WA, USA
Posts: 1,649
Thanks: 3
Thanked 141 Times in 140 Posts
Default

Gee, that's funny.

This guy is having exactly the same problem:
http://www.aspmessageboard.com/forum...=896367#896338
Reply With Quote
Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Incorrect syntax near '.' meraj ADO.NET 6 February 27th, 2012 01:01 AM
Incorrect Date Value Stanny Access 1 January 17th, 2005 05:34 PM
Incorrect syntax near '!' sinapra Classic ASP Databases 8 August 25th, 2004 02:15 AM
Webrequest ?? Any equiv. for xmlhttppost in .net?? rajeevcv ASP.NET 1.0 and 1.1 Professional 0 May 3rd, 2004 01:00 PM



All times are GMT -4. The time now is 02:23 AM.


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