Link to home
Start Free TrialLog in
Avatar of openujs
openujs

asked on

passing array from server to client in Javascript

i have a array in server side, i am trying to pass it to client, ,it is not working any clues?
server code

var arr = new Array();
arr[0] = "test";
arr[1] = "test1";
Response.write("<script>ClientFunc('"+ID+"',, '" + arr + "', 3 );</script>\r\n"  );

<script>
function ClienFunc( id, arr, num )
{
   var size = arr.length;
   var val = arr[0];
   alert( val );////returns undefined
}
</script>
      

ASKER CERTIFIED SOLUTION
Avatar of mcdown75
mcdown75
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of nurbek
nurbek

you can not pass it directly

try passing like this

<script>
function ClienFunc( id, arr, num )
{
var arr = new Array();
arr[0] = "<%=arr[0]%>";
arr[1] = "<%=arr[1]%>";

val = arr[0];
alert(val);
}
</script>


Avatar of openujs

ASKER

thank u so much..i decided to go with McDown75 method of converting into string. Nurbek's method is cool too but if the array is empty,,it gave error message saying arr.0 is undefined or not a object . i even put a if statement saying
if( arr != "undefined") but i kept getting that error message, i am sure there is a workaround.
Below is a server side function which will convert a server side (Vb) array to client side (JS) array 1 D Array. All you need to do is pass the VB Array and the name of the client side JS array

<%
Function ConvertToJSArray1D(VBArray , ArrayName)

Dim vb2jsRow, vb2jsCol , vb2jsStr, vb2jsi, vb2jsj
vb2jsRow = Ubound(VBArray,1)
'vb2jsCol = Ubound(VBArray,2)
%>

<SCRIPT LANGUAGE = 'JAVASCRIPT' >
var vb2jsi,vb2jsj
<%=ArrayName%> = new Array(<%=vb2jsRow%>);
</SCRIPT>
%>

Code for 2D array:
Converts the server side (Vb) 2D array to client side 2D (JS) array

Function ConvertToJSArray2D(VBArray , ArrayName)

Dim vb2jsRow, vb2jsCol , vb2jsStr, vb2jsi, vb2jsj
vb2jsRow = Ubound(VBArray,1)
vb2jsCol = Ubound(VBArray,2)
%>

<SCRIPT LANGUAGE = 'JAVASCRIPT' >
var vb2jsi,vb2jsj
<%=ArrayName%> = new Array(<%=vb2jsRow+1%>);
for (vb2jsi=0; vb2jsi < <%=vb2jsRow+1%>; vb2jsi++)
{  
     <%=ArrayName%>[vb2jsi] = new Array(<%=vb2jsCol+1%>)
   for (vb2jsj=0; vb2jsj < <%=vb2jsCol+1%>; vb2jsj++) <%=ArrayName%>[vb2jsi][vb2jsj] = " "
}
</SCRIPT>
<%
Response.Write("<SCR"&"IPT LANGUAGE = 'JAVASCRIPT' >"&chr(13))
for vb2jsi=0 to vb2jsRow
   for vb2jsj=0 to vb2jsCol
      vb2jsstr = "VBArray("&vb2jsi&","&vb2jsj&")"
%>      
     <%=ArrayName%>[<%=vb2jsi%>][<%=vb2jsj%>] = '<%=trim(eval(vb2jsstr))%>'
<%
   Next
Next
Response.Write("</SCR"&"IPT>")
End Function
<%
Response.Write("<SCR"&"IPT LANGUAGE = 'JAVASCRIPT' >"&chr(13))
for vb2jsi=0 to vb2jsRow
      vb2jsstr = "VBArray("&vb2jsi&")"
%>      
     <%=ArrayName%>[<%=vb2jsi%>]= '<%=trim(eval(vb2jsstr))%>'
<%
   Next
Response.Write("</SCR"&"IPT>")
End Function

%>

Mohit Raj