Navigate
Home
ArticleWiki
Forum
Journal
Search
Newsletter
Links
Tech News
expertsrt.com
Welcome Guest.
Username:

Password:

Remember me

php code in asp
Welcome, Guest. Please login or register.
December 03, 2008, 11:48:35 PM
11306 Posts in 1249 Topics by 499 Members
Latest Member: haulaslemycle
Experts Round Table Network  |  Serverside Technology  |  ASP  |  php code in asp « previous next »
Pages: [1] 2
Author Topic: php code in asp  (Read 1311 times)
Johnny26652

Offline Offline

Posts: 61


« on: February 06, 2007, 06:43:21 PM »

Hello mentors,

i have 2 questions and i was wondering if someone can help me..

1)

<?php
if (isset($_POST['txtRow'])) {
  foreach($_POST['txtRow'] as $key => $rowTextbox) {
    echo "<p>".$key." : ".$rowTextbox."</p>";
  }
}
?>


can someone help me to convert this in to asp??

http://www.mredkj.com/tutorials/tablebasics5.html

i am trying to build a table dynamically and trying to retrieve the select values?



2) in my select box is it possible for me to use a do while loop in which the recorset is retrieved from database?


// select cell
  var cellRightSel = row.insertCell(2);
  var sel = document.createElement('select');
  sel.name = 'selRow' + iteration;
  sel.options[0] = new Option('<%= rs("books") %>', 'value0');


i am able to retrieve one book but i am not able to use a do while loop to get all the books here..



  cellRightSel.appendChild(sel);



thanks for youe help


Logged

Johnny
rdivilbiss
Moderator
*
Offline Offline

Posts: 414



WWW
« Reply #1 on: February 07, 2007, 09:31:09 AM »

1) ASP will receive the values of the text inputs as a comma delimited string, so you'll need to split that string to get an array.

<%
if request.form("txtRow[]")<>"" then
   'response.write(request.form("txtRow[]"))
   rowsArray = Split(request.form("txtRow[]"),",")
   for idx = 0 to UBound(rowsArray)
      response.write idx & " " & rowsArray(idx) & "<br>"
   next
end if
%>


2) Once you retrieve the records from the database then begin to render your page, your server side processing is no longer available. e.g. you can't loop through a ASP recordset in JavaScript.  You'll need to put your values into a JavaScript array, then use the JavaScript array client side.

http://www.rodsdot.com/ee/ASP2ClientSideArray.asp
Logged

Rod
Johnny26652

Offline Offline

Posts: 61


« Reply #2 on: February 07, 2007, 04:54:44 PM »

as always thanks for your response.. i tried something like this and it is working even though i am not using arrays..

this is the function which adds a row dynamically which has a checkbox and selectbox

 // right cell
  var cellRight = row.insertCell(1);
  var el = document.createElement('input');
  el.type = 'checkbox';
  el.name = 'txtRow[]' ;
  el.id = 'txtRow' + iteration;
  el.size = 40;
 
  el.onkeypress = keyPressTest;
  cellRight.appendChild(el);
 
  // select cell
  var cellRightSel = row.insertCell(2);
  var sel = document.createElement('select');
  sel.name = 'selRow[]' ;
do while not rs.eof
  sel.options[sel.options.length] = new Option('<%rs(authors)', '<%rs(authors)');

rs.movenext
loop
    cellRightSel.appendChild(sel);
}



and in my form i have

<form.....>
<table>

<td> <input type="checkbox" name = txtRow[]>
<td> <select name =selRow[]>
<option>
rs.movefirst

do while not rs.eof

Response.write <rs("")>

rs.movenext
loop
</option>
</select>




when i clcik addrow i get a checkbox (to see if he/she is primary author)and a selectbox with options (authors from database)..


in the next page how do i collect these values


right now when i say

response.write(request.form("txtRow[]"))
response.write(request.form("selRow[]"))

i get...

on, on, author1, author2, author3 author4 author5  for 5 rows in my previous page

i was wondering how to link them


primaryauthor   allauthors
on                     author1
off                     author2
on                     author3
off                     author4
off                     author5


thanks..




« Last Edit: February 08, 2007, 11:48:28 AM by Johnny26652 » Logged

Johnny
rdivilbiss
Moderator
*
Offline Offline

Posts: 414



WWW
« Reply #3 on: February 09, 2007, 03:52:27 PM »

You started off with a faulty premis from your original PHP code, which is: "A series of form fields with the same name will be retrieved by PHP as a comma delimited string, and if the field name is written as a PHP array variable, then you can manipulate those as a PHP array"

This does not work in ASP, and in both ASP and PHP a posted list of checkboxes is not going to coincide with a list od select elements.

When checkboxes are posted, they are either empty strings or checked/on/etc.

When a select is posted, there will be some value submitted so as you saw you got:

on, on  (The checkboxes)

author1, author2, author3 author4 author5 (The selects)

but you currently have no way to know which check boxes were checked, and will not unless they each have a unique name.

While I am not clear about what you are trying to accomplish, and I guess if I did know what you were up to I would suggest another approach, what follows is a page which does what you want so far.

I persist in passing the results of the database query to a JavaScript array, as the only way you can loop through recordset results client side is by using JScript which means you have an IE only result.  As you did not post all your code I can't figure out if you are building a  large set of results inside dynamically generated JavaScript functions.  But enough about that.

Note also I dropped the fieldName[] notation and uniquely name each checkbox and select, so I know exactly what was checked and selected when the form is posted back to ASP.

http://www.rodsdot.com/ee/dynamicRows.asp

Code
Language: asp (GeSHi-highlighted)
<!--METADATA TYPE="typelib" uuid="00000205-0000-0010-8000-00AA006D2EA4" -->
<%
Option Explicit
Session.CodePage=65001
Response.Charset="UTF-8"
 
' no browser caching of this page !! to be used on all pages
Response.Expires=-1
Response.ExpiresAbsolute = Now() - 1
 
'
do not allow proxy servers to cache this page !! to be used on all pages
Response.CacheControl="private"
Response.CacheControl="no-cache"
Response.CacheControl="no-store"
 
Dim cmd, conn, RS, cmdText, param, numAffected
 
Set cmd = Server.CreateObject("ADODB.Command")
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open Application("examples")
 
cmdText = "SELECT code, description FROM states"
cmd.commandText = cmdText
Set cmd.ActiveConnection = conn
 
Set rs = cmd.Execute(numAffected,,adCmdText)
if NOT (rs.bof AND rs.eof) then
 Dim tmpStr
 tmpStr = "<scr" & "ipt type=" & chr(34) & "text/javascr" & "ipt" & chr(34) & ">" & vbLF
 
 ' declare a client side array
 tmpStr = tmpStr & " var csArray=new Array();" & vbLF & vbLF
 
 Dim idx, item
 idx = 0 '
JavaSccript arrays are zero based.
 
 ' fill the array from our recordset
 While NOT rs.eof
   tmpStr = tmpStr & " csArray["& idx &"]=(['
"
   for each item in rs.fields
     tmpStr = tmpStr & item & "
','"
   next
 
   ' backoff the trailing ,' and terminate the line with ]);
   tmpStr = Left(tmpStr, Len(tmpStr)-2) & "
]);" & vbLF
 
   ' increment our array index
   idx = idx + 1
   rs.movenext
 Wend
 
 tmpStr = tmpStr & "
</scr" & "ipt>" & vbLF
end if
rs.close
Set rs = nothing
Set cmd=nothing
conn.close
Set conn=nothing
 
Dim posted, numRows
 
posted = "
"
' if we have a post - process it
if request.servervariables("
HTTP_METHOD")="POST" then
 if CInt(request.form("
numRows")) >= 0 then
   ' how many rows were posted?
   numRows = CInt(request.form("
numRows"))
 
   ' loop through the rows and associated the checkboxes
   ' to the selected values in the select lists
   for idx=0 to numRows
     if request.form("
cb"&idx) = "" then
       posted = posted & "
Row " & idx & " Not Checked "
     else
       posted = posted & "
Row " & idx & " Checked "
     end if
     if request.form("
sel"&idx) = "" then
       posted = posted & "
Value=Empty<br>"
     else
       posted = posted & "
Value=" & request.form("sel"&idx) & "<br>"
     end if
   next
 end if
end if
%>
Code
Language: javascript (GeSHi-highlighted)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="author" content="Roderick Divilbiss">
<meta name="copyright" content="© 2005, 2006 Roderick Divilbiss">
<title>Adding Dynamic Rows To Form</title>
<!--write our database results as an array-->
<% response.write tmpStr %>
<script type="text/javascript">
<!--
var numberOfRows = 0;
 
function insertRow(tblId) {
   var tbl = document.getElementById(tblId);
   var iteration = tbl.tBodies[0].rows.length;
   newRow = tbl.tBodies[0].insertRow(-1);
   var newCell = newRow.insertCell(0);
   var newCell1 = newRow.insertCell(1);
   var el = document.createElement('input');
   el.type = 'checkbox';
   el.name = 'cb' + iteration;
   el.id = 'cb' + iteration;
   newCell1.appendChild(el);
 
   var newCell2 = newRow.insertCell(1);
   var newCell1 = newRow.insertCell(1);
   var sel = document.createElement('select');
   sel.name = 'sel' + iteration;
   sel.id = 'sel' + iteration;
   // build the select from the retrieved database rows
   // we stored in a JS array.
   for (var idx=0;idx<csArray.length;idx++) {
       sel.options[idx] = new Option(csArray[idx][0], csArray[idx][1]);
   }
   newCell2.appendChild(sel);
   // update hidden rows count field
   document.getElementById('numRows').value=iteration;
}
 
 
function deleteAllRows(tblId) {
   var tbl = document.getElementById(tblId);
   for (var i=tbl.tBodies[0].rows.length-1; i>=0; i--) {
       tbl.tBodies[0].deleteRow(i);
   }
}
//-->
</script>
</head>
 
<body>
<!--posted results if any-->
<%=posted%>
 
<form action="dynamicRows.asp" method="post">
<p>
<input value="Add" onclick="insertRow('tblInsertRow');" type="button">
<input value="Reset" onclick="deleteAllRows('tblInsertRow');" type="button">
<input value="Submit" type="submit">
</p>
<table id="tblInsertRow" border="0" cellspacing="0">
 <thead>
   <tr>
     <th colspan="2">Header</th>
   </tr>
 </thead>
 <tbody></tbody>
</table>
<input id="numRows" name="numRows" type="hidden" value="0">
</form>
</body>
</html>
 
« Last Edit: February 10, 2007, 05:23:34 PM by rdivilbiss » Logged

Rod
VGR
Mentor

Offline Offline

Posts: 682



WWW
« Reply #4 on: February 10, 2007, 10:04:20 AM »

rod, I didn't check out your code and I'm pretty sure it works, but this remark :

Quote
When checkboxes are posted, they are either empty strings or checked/on/etc.
could be partly wrong and surely misleading.

***if*** checkboxes are posted, they are either empty string (greyed elements - not sure - ) or the value of the value attribute
The thing to know is that checkboxes are NOT posted if they aren't checked ! (or readonly and checked or greyed out - not sure again - )

for receving an HTML array of input type=text, you can use standard array examination (index from 0 or 1 to n-1 or n etc) but for arrays of checkboxes, you've to check with isset() or the like for each index possible. It's far more appropriate to use foreach() on the checkboxes "collection" (sparse array, in fact)
Logged

techie overlord, answers all kind of questions on http://www.europeanexperts.org
rdivilbiss
Moderator
*
Offline Offline

Posts: 414



WWW
« Reply #5 on: February 10, 2007, 12:01:14 PM »

rod, I didn't check out your code and I'm pretty sure it works, but this remark :
could be partly wrong and surely misleading.

***if*** checkboxes are posted, they are either empty string (greyed elements - not sure - ) or the value of the value attribute
The thing to know is that checkboxes are NOT posted if they aren't checked ! (or readonly and checked or greyed out - not sure again - )

I agree. It is more precise to say that it posts nothing if not checked, and the value in the VALUE attribute if checked.

Quote
for receving an HTML array of input type=text, you can use standard array examination (index from 0 or 1 to n-1 or n etc) but for arrays of checkboxes, you've to check with isset() or the like for each index possible. It's far more appropriate to use foreach() on the checkboxes "collection" (sparse array, in fact)

Not exactly when referring to an ASP receiver.  ASP\VBScript will not treat either as an array, unless you split the posted value on the comma.  Everything is a variant. See my first post to the thread as an example.

ASP\VBScript has no real equivalent to isset, althought you could use IsEmpty().

if IsEmpty(Request.Form("field-name"))

But you are correct that you must explicitly check each named checkbox field.

All of that aside, where I see some other issues which need to be addressed if using this dynamic row, form fields method.  e.g. there is a disconnect between the server side and client side.  For example, if we post five dynamic rows of fields and have a validation error, we should rebuild the form to show the five rows, the values submitted and the error.

So we need more code.

ALSO: I used no input filtering which is a big security no-no.
Logged

Rod
VGR
Mentor

Offline Offline

Posts: 682



WWW
« Reply #6 on: February 10, 2007, 12:45:48 PM »

haaa that's why everybody splits on the tilde upon receing data in ASP ;-)

the POST data is transmitted to ASP as a looong string of value-pairs delimited by ~ ?

LOL how convenient

it's fun to have variants (Pascal had them back in 69) but reading "everything is variant" makes me as nervous as when reading C code doing arithmetic operations on char data :D
Logged

techie overlord, answers all kind of questions on http://www.europeanexperts.org
rdivilbiss
Moderator
*
Offline Offline

Posts: 414



WWW
« Reply #7 on: February 10, 2007, 01:24:02 PM »

It gets a little messy tying the posted form fields back to the form...but it is doable.

http://www.rodsdot.com/ee/dynamicRows2.asp

Code
Language: asp (GeSHi-highlighted)
<!--METADATA TYPE="typelib" uuid="00000205-0000-0010-8000-00AA006D2EA4" -->
<%
Option Explicit
Session.CodePage=65001
Response.Charset="UTF-8"
 
 
' no browser caching of this page !! to be used on all pages
Response.Expires=-1
Response.ExpiresAbsolute = Now() - 1
 
'
do not allow proxy servers to cache this page !! to be used on all pages
Response.CacheControl="private"
Response.CacheControl="no-cache"
Response.CacheControl="no-store"
 
Dim cmd, conn, RS, cmdText, param, numAffected
 
Set cmd = Server.CreateObject("ADODB.Command")
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open Application("examples")
 
cmdText = "SELECT code, description FROM states"
cmd.commandText = cmdText
Set cmd.ActiveConnection = conn
 
Set rs = cmd.Execute(numAffected,,adCmdText)
 
function getSelect(id, selected)
Dim tmpStr
tmpStr = "<select id="& chr(34) & id & chr(34) &" name="& chr(34) & id & chr(34) &">"

Dim item

' fill the select from our recordset
rs.movefirst
While NOT rs.eof
if (rs("description")=selected) then
tmpStr = tmpStr & "<option selected value="&chr(34)&rs("description")&chr(34)&">"&rs("code")&"</option>"
else
tmpStr = tmpStr & "<option value="&chr(34)&rs("description")&chr(34)&">"&rs("code")&"</option>"
end if
rs.movenext
Wend
tmpStr = tmpStr & "</select>"
getSelect=tmpStr
end function
 
function getCheckBox(id, value)
Dim tmpStr
if value="" then
tmpStr = "<input id="& chr(34) & id & chr(34) &" name="& chr(34) & id & chr(34) &" type=""checkbox"">"
else
tmpStr = "<input id="& chr(34) & id & chr(34) &" name="& chr(34) & id & chr(34) &" type=""checkbox"" checked>"
end if
getCheckBox=tmpStr
end function
 
Dim theArray
theArray = "<scr" & "ipt type=" & chr(34) & "text/javascr" & "ipt" & chr(34) & ">" & vbLF

'
declare a client side array
theArray = theArray & "  var csArray=new Array();" & vbLF & vbLF

Dim idx, item
idx = 0 ' JavaSccript arrays are zero based.

'
fill the array from our recordset
While NOT rs.eof
theArray = theArray & "  csArray["& idx &"]=(['"
for each item in rs.fields
theArray = theArray & item & "','"
next

' backoff the trailing ,' and terminate the line with ]);
theArray = Left(theArray, Len(theArray)-2) & "]);" & vbLF

' increment our array index
idx = idx + 1
rs.movenext
Wend

theArray = theArray & "</scr" & "ipt>" & vbLF
 
 
 
Dim posted, numRows, cb(), sel()
 
posted = ""
numRows = 0
 
if request.servervariables("HTTP_METHOD")="POST" then
if CInt(request.form("numRows")) >= 0 then
numRows = CInt(request.form("numRows"))
redim cb(numRows)
redim sel(numRows)
posted = "<tbody>"
for idx=0 to numRows
posted = posted & "<tr><td></td><td></td><td>"
if request.form("sel"&idx) = "" then
sel(idx)=""
posted = posted & getSelect("sel"&idx, "") & "</td>"
else
sel(idx)=request.form("sel"&idx)
posted = posted & getSelect("sel"&idx, request.form("sel"&idx)) & "</td>"
end if
if request.form("cb"&idx) = "" then
cb(idx)=false
posted = posted & "<td>" & getCheckBox("cb"&idx, "") & "</td>"
else
cb(idx)=true
posted = posted & "<td>" & getCheckBox("cb"&idx, "checked") & "</td>"
end if
posted = posted & "</tr>"
next
posted = posted & "</tbody>"
end if
end if
 
if posted="" then
posted="<tbody></tbody>"
end if
 
rs.close
Set rs = nothing
Set cmd=nothing
conn.close
Set conn=nothing
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="author" content="Roderick Divilbiss">
<meta name="copyright" content="© 2005, 2006 Roderick Divilbiss">
<title>Whatever</title>
<%=theArray%>
<script type="text/javascript">
<!--
var numberOfRows = <%=numRows%>;
 
function insertRow(tblId) {
var tbl = document.getElementById(tblId);
var iteration = tbl.tBodies[0].rows.length;
newRow = tbl.tBodies[0].insertRow(-1);
var newCell = newRow.insertCell(0);
//newCell.innerHTML = iteration;
var newCell1 = newRow.insertCell(1);
var el = document.createElement('
input');
el.type = '
checkbox';
el.name = '
cb' + iteration;
el.id = '
cb' + iteration;
newCell1.appendChild(el);

var newCell2 = newRow.insertCell(1);
//newCell.innerHTML = '
right ' + iteration;
var newCell1 = newRow.insertCell(1);
var sel = document.createElement('
select');
sel.name = '
sel' + iteration;
sel.id = '
sel' + iteration;

for (var idx=0;idx<csArray.length;idx++) {
sel.options[idx] = new Option(csArray[idx][0], csArray[idx][1]);
}
newCell2.appendChild(sel);

document.getElementById('
numRows').value=iteration;
 
}
 
 
function deleteAllRows(tblId) {
var tbl = document.getElementById(tblId);
for (var i=tbl.tBodies[0].rows.length-1; i>=0; i--) {
tbl.tBodies[0].deleteRow(i);
}
}
//-->
</script>
</head>
 
<body>
<noscript><p>You need JavaScript to view this example.</p></noscript>
<h2>How can you dynamically add rows and fields to a table?</h2>
<p>
<%
if numRows<>"<tbody></tbody>" then
for idx=0 to numRows
response.write "Row "&idx&": Selected="&sel(idx)&" Checked="&cb(idx)&"<br>"  
next
end if
%>
</p>
<form action="dynamicRows2.asp" method="post">
<p>
<input value="Add" onclick="insertRow('
tblInsertRow');" type="button">
<input value="Reset" onclick="deleteAllRows('
tblInsertRow');" type="button">
<input value="Submit" type="submit">
</p>
<table id="tblInsertRow" border="0" cellspacing="0">
 <thead>
 <tr>
   <th colspan="4">Header</th>
 </tr>
 </thead>
 <%=posted%>
</table>
<input id="numRows" name="numRows" type="hidden" value="<%=numRows%>">
</form>
</body>
 
</html>
« Last Edit: February 10, 2007, 05:24:44 PM by rdivilbiss » Logged

Rod
Johnny26652

Offline Offline

Posts: 61


« Reply #8 on: February 10, 2007, 05:08:08 PM »

Hi Rod,
http://www.rodsdot.com/ee/dynamicRows.asp

Thank you so much. I didn't really try it in my code but i did go to your site and played with it..

I added one select box, checkbox  and clicked submit

no results are posted but when i do 2  the results shows up.. i thought may be it has to do something with intialization of array. but i see you are starting with zero..

if numRows>0 then   for idx=0 to numRows      response.write "Row "&idx&": Selected="&sel(idx)&" Checked="&cb(idx)&"<br>"     next
end if


any ideas?

thanks again.
John
Logged

Johnny
rdivilbiss
Moderator
*
Offline Offline

Posts: 414



WWW
« Reply #9 on: February 10, 2007, 05:20:35 PM »

Yes, a little bug....

Code
Language: asp (GeSHi-highlighted)
if CInt(request.form("numRows")) >= 0 then


and in http://www.rodsdot.com/ee/dynamicRows2.asp

Code
Language: asp (GeSHi-highlighted)
<%
if posted<>"<tbody></tbody>" then
for idx=0 to numRows
response.write "Row "&idx&": Selected="&sel(idx)&" Checked="&cb(idx)&"<br>"  
next
end if
%>
Logged

Rod
rdivilbiss
Moderator
*
Offline Offline

Posts: 414



WWW
« Reply #10 on: February 12, 2007, 10:07:51 AM »


how do i store this query in to an array ?


Did you remember to add

Code
Language: asp (GeSHi-highlighted)
<%=tmpStr%>

inside the JavaScript block?

e.g. viewsource should show you if the array wrote correctly.

Quote
all i get is chekboxes and it doesn't display select box?

You should probably be getting a JavaScript error which would help to determine why.  If you are using IE, and you are developing web pages, you need to go into Tools->Internet Options->Advanced Tab, and then make sure you have Display A Notification About Every Script Error checked, and Show friendly HTTP error messages unchecked.

« Last Edit: February 17, 2007, 02:29:51 PM by rdivilbiss » Logged

Rod
rdivilbiss
Moderator
*
Offline Offline

Posts: 414



WWW
« Reply #11 on: February 12, 2007, 11:30:16 AM »

Well got it working is a good thing, so I'm happy to hear that.  You're not bothering me.
Logged

Rod
rdivilbiss
Moderator
*
Offline Offline

Posts: 414



WWW
« Reply #12 on: February 14, 2007, 04:27:05 PM »

It should be, as far as getting the file names. You have to change to form to add ENCTYPE="multipart/form-data".

Assuming you are using something like the pure ASP upload or some other file component, It might actually prefer all the files having the same field name.

Frankly, I've never allowed more than one upload per form before.  If I have time later I might run a quick test.

 



Logged

Rod
Johnny26652

Offline Offline

Posts: 61


« Reply #13 on: February 28, 2007, 03:38:35 PM »

Rod,
I am trying to do the edit functionality. How can i bring the authors and checkboxes i added so user can edit them?

say for eg:
primaryauthor   allauthors
on                     author1
off                     author2
on                     author3
off                     author4
off                     author5

i added these 5 authors in to db. i should retrieve these 5 authors in to 5 selectboxes so users can edit them?

thanks
John

« Last Edit: February 28, 2007, 04:08:11 PM by Johnny26652 » Logged

Johnny
rdivilbiss
Moderator
*
Offline Offline

Posts: 414



WWW
« Reply #14 on: February 28, 2007, 06:37:57 PM »

I'm not sure I understand what you wish to do.

Can you post a link to an HTML only page which shows me what you want to do?
Logged

Rod
Pages: [1] 2
« previous next »
    Jump to: