-1

I am trying to get response from ASP page(inside which I'm creating dynamic javascript array). But after AJAX callback, I'm not able to access the javascript array.

I have gone through stackoverflow article Calling a JavaScript function returned from an Ajax response which addresses issues similar to mine.

Not sure what is wrong in this. I'm giving below brief idea of the code I've written.


Function ()
{
  var xmlhttp;
  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 == 1) {
      alert('connection');
    }
    if (xmlhttp.readyState == 3) {
      alert('processing');
    }
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      alert('back with the bang');
      document.getElementById('dvCallback').innerHTML = xmlhttp.responseText;
      eval(document.getElementsByID("runscript").innerHTML);
      split1 = arrJSCalT[i].split(":");
      alert(split1[1]);
    }
  }
  xmlhttp.open("POST", "Sys_Add.asp", true);
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlhttp.send();
  return false;
}

Sys_Add.asp is as below.

 <%
    response.Expires = -1
    dim strErrMsg

    recCntr = 0
    recCntr = rsCalT.RecordCount
    recCntr = recCntr - 1
    dim dicCalT
    set dicCalT = CreateObject("Scripting.Dictionary")
    if rsCalT.RecordCount <> 0 then
    rsCalT.MoveFirst
    do while not rsCalT.EOF
    dicCalT.Add cstr(rsCalT(0)), cstr(rsCalT(1))
    rsCalT.MoveNext
    loop
    end if
    Call FillJSArray(dicCalT,"arrJSCalT")

    Sub FillJSArray(dicVB, arrJS)
        dim itr
        a = dicVB.keys
        b = dicVB.items
        Response.write ("<script language=""javascript"" id=""runscript"" name =""runscript"">" & VbCrLf )
        Response.Write ("var " & arrJS & "= new Array(" )
        for i = 0 To dicVB.Count - 1
            If i > 0 then
                response.write (",")
            End If
            Response.Write ("""" & a(i) & ":" & b(i) & """")
        Next
        Response.Write (");" & vbCrLf )
        'Response.write "alert(""running from main"");"
        Response.write ("</script>" & VbCrLf)
        Response.write ("so this is printed as welll")
    End Sub
    'END creating javascript array from asp recordset

  response.Write ("Did you want this??")

%>

I get error at line split1 = arrJSCalT[i].split(":"); I would appreciate if I get assistance on this.

Thanks... Prashant....

Community
  • 1
  • 1
Prashant
  • 26
  • 5
  • 1
    What is the error that you receive? – xcopy Jun 18 '12 at 14:09
  • 1
    There is no `getElementsById()` function - it's "element" not "elements" – Pointy Jun 18 '12 at 14:13
  • Also where does arrJSCalT come from? – Pointy Jun 18 '12 at 14:14
  • Well, I corrected the syntax errors(variable i and getElement...) and I still get the error "'arrJSCalT' is undefined". I also tried to replace the code to get the local scope. responseDiv = document.getElementById('dvCallback'); responseDiv.innerHTML = xmlhttp.responseText; scripts = responseDiv.getElementsByTagName('script');eval(scripts[0]); But I still get the same error. Not sure why?? Thanks for your help. – Prashant Jun 19 '12 at 07:06
  • Hi Pointy, arrJSCalT is the name of javascript array that I'm passing while making call to subroutine FillJSArray(dicCalT,"arrJSCalT") in asp page Sys_Add.asp. – Prashant Jun 19 '12 at 07:12
  • Let me tell you this piece of code works absolutely fine without AJAX/when written in the same asp page. – Prashant Jun 19 '12 at 07:17
  • Also I'm able to get the response as "so this is printed as welllDid you want this??". What I don't see is the javascript that I am creating dynamically?? Any clue what could be wrong... – Prashant Jun 19 '12 at 07:26

2 Answers2

0

this is because

Response.write ("<script language=""javascript"" id=""runscript"" name =""runscript"">" & VbCrLf )
Response.Write ("var " & arrJS & "= new Array(" )

makes the array local to your new script, and unless the js function() {...} part is called within this same <script/> block you won't see it, because of the variable scope being local.

Additionnal informations: This :

  eval(document.getElementsByID("runscript").innerHTML);

creates a script with a local variable in it, which is your array. The array is totally invisible from outside this script.

But then you try to use it the next line:

  split1 = arrJSCalT[i].split(":");

But this line is outside your previously dynamically create block. I can't give you a solution because I don't know what you are attempting to realize in this operation, but I would strongly recommend the following:

  • get a XML document from your asp page, returning all the datas you need (and only the datas) for example the content of your array. Example of XML return:
<DATAS>
    <DATA>1</DATA>
    <DATA>2</DATA>
    <DATA>3</DATA>
    <DATA>4</DATA>
</DATAS>
var parser=new DOMParser();
var xmlDoc=parser.parseFromString(xmlhttp.responseText,"text/xml");
var sLocalData;
var oOpt;

for(var i=0; i< xmlDoc.getElementsByTagName("data").length; i++) {
    sLocalData = xmlDoc.getElementsByTagName("title")[i].textContent;
    //do your stuff here, for example:
    oOpt = document.createElement("option");
    oOpt.text = sLocalData;
    mycombobox.appendChild(oOpt);
}
  • don't use eval to addup scripts like this, you are doing something extremely risky, ugly and unclear

Here you go, have fun! Regards.

Sebas
  • 21,192
  • 9
  • 55
  • 109
  • So you mean to say I wouldn't be able access the javascript variable created dynamically on another page but captured in AJAX call back?? – Prashant Jun 19 '12 at 07:20
  • my whole effort is to fetch values from database and dynamically create javascript array so that I can load some dropdownlists based on onchange event of one master dropdown..I want to avoid postbacks/page loading and that is why AJAX approach.... – Prashant Jun 19 '12 at 13:29
  • then why do you need an array do fill up the drop down list? Why don't you load them directly in the ajax callback? – Sebas Jun 19 '12 at 13:31
  • as suggested by you to load data from XML file, I don't know how I am going to load the d/b values in XML and then read XML file upon AJAX callback....so there is more work for me understanding XML approach........ – Prashant Jun 19 '12 at 13:31
  • I understand, well I was in the same situation and I was really surprised that it took me only a few minutes to get it. This is pretty simple, let me edit my code to give an example – Sebas Jun 19 '12 at 13:33
0

You are trying to access arrJSCalT variable, but it don't exist. Exists only on ASP scope, but JS dont knows it.

So, you need tell to JS who is arrJSCalT. You can access AJAX return with xmlhttp's property responseText.

Before split1 var, place this:

arrJSCalT = xmlhttp.responseText;
Estevão Lucas
  • 4,440
  • 34
  • 37