Edit multiple rows of records inline with Ajax and Classic ASP
 


Classic ASP Active Server Pages Examples, code, tutorials, scriptsYvo Schaap's inline edit Ajax script for editing multiple rows of records in a table display

This really is as easy as he says it is.

The example that is shown on Schaap's page is like for editing a single record, and his processing script is in PHP. I am more familiar with Classic ASP, so I wrote up a little example of how it might be used for inline editing of multiple records in a table grid.

Save this as instantedit.js

<!--
//script by http://www.yvoschaap.com

//XMLHttpRequest class function
function datosServidor() {
};
datosServidor.prototype.iniciar = function() {
try {
// Mozilla / Safari
this._xh = new XMLHttpRequest();
} catch (e) {
// Explorer
var _ieModelos = new Array(
'MSXML2.XMLHTTP.5.0',
'MSXML2.XMLHTTP.4.0',
'MSXML2.XMLHTTP.3.0',
'MSXML2.XMLHTTP',
'Microsoft.XMLHTTP'
);
var success = false;
for (var i=0;i < _ieModelos.length && !success; i++) {
try {
this._xh = new ActiveXObject(_ieModelos[i]);
success = true;
} catch (e) {
}
}
if ( !success ) {
return false;
}
return true;
}
}

datosServidor.prototype.ocupado = function() {
estadoActual = this._xh.readyState;
return (estadoActual && (estadoActual < 4));
}

datosServidor.prototype.procesa = function() {
if (this._xh.readyState == 4 && this._xh.status == 200) {
this.procesado = true;
}
}

datosServidor.prototype.enviar = function(urlget,datos) {
if (!this._xh) {
this.iniciar();
}
if (!this.ocupado()) {
this._xh.open("GET",urlget,false);
this._xh.send(datos);
if (this._xh.readyState == 4 && this._xh.status == 200) {
return this._xh.responseText;
}

}
return false;
}


var urlBase = "updatembr.asp";
var formVars = "";
var changing = false;


function fieldEnter(campo,evt,idfld) {
evt = (evt) ? evt : window.event;
if (evt.keyCode == 13 && campo.value!="") {
elem = document.getElementById( idfld );
remotos = new datosServidor;
nt = remotos.enviar(urlBase + "?fieldname=" +encodeURI(elem.id)+ "&content="+encodeURI(campo.value)+"&"+formVars,"");
//remove glow
noLight(elem);
elem.innerHTML = nt;
changing = false;
return false;
} else {
return true;
}


}

function fieldBlur(campo,idfld) {
if (campo.value!="") {
elem = document.getElementById( idfld );
remotos = new datosServidor;
nt = remotos.enviar(urlBase + "?fieldname=" +escape(elem.id)+ "&content="+escape(campo.value)+"&"+formVars,"");
elem.innerHTML = nt;
changing = false;
return false;
}
}

//edit field created
function editBox(actual) {
//alert(actual.nodeName+' '+changing);
if(!changing){
width = widthEl(actual.id) + 20;
height =heightEl(actual.id) + 2;

if(height < 40){
if(width < 100) width = 150;
actual.innerHTML = "<input id=\""+ actual.id +"_field\" style=\"width: "+width+"px; height: "+height+"px;\" maxlength=\"254\" type=\"text\" value=\"" + actual.innerHTML + "\" onkeypress=\"return fieldEnter(this,event,'" + actual.id + "')\" onfocus=\"highLight(this);\" onblur=\"noLight(this); return fieldBlur(this,'" + actual.id + "');\" />";
}else{
if(width < 70) width = 90;
if(height < 50) height = 50;
actual.innerHTML = "<textarea name=\"textarea\" id=\""+ actual.id +"_field\" style=\"width: "+width+"px; height: "+height+"px;\" onfocus=\"highLight(this);\" onblur=\"noLight(this); return fieldBlur(this,'" + actual.id + "');\">" + actual.innerHTML + "</textarea>";
}
changing = true;
}

actual.firstChild.focus();
}



//find all span tags with class editText and id as fieldname parsed to update script. add onclick function
function editbox_init(){
if (!document.getElementsByTagName){ return; }
var spans = document.getElementsByTagName("span");

// loop through all span tags
for (var i=0; i<spans.length; i++){
var spn = spans[i];

if (((' '+spn.className+' ').indexOf("editText") != -1) && (spn.id)) {
spn.onclick = function () { editBox(this); }
spn.style.cursor = "pointer";
spn.title = "Click to edit!";
}

}


}

//crossbrowser load function
function addEvent(elm, evType, fn, useCapture)
{
if (elm.addEventListener){
elm.addEventListener(evType, fn, useCapture);
return true;
} else if (elm.attachEvent){
var r = elm.attachEvent("on"+evType, fn);
return r;
} else {
alert("Please upgrade your browser to use full functionality on this page");
}
}

//get width of text element
function widthEl(span){

if (document.layers){
w=document.layers[span].clip.width;
} else if (document.all && !document.getElementById){
w=document.all[span].offsetWidth;
} else if(document.getElementById){
w=document.getElementById(span).offsetWidth;
}
return w;
}

//get height of text element
function heightEl(span){

if (document.layers){
h=document.layers[span].clip.height;
} else if (document.all && !document.getElementById){
h=document.all[span].offsetHeight;
} else if(document.getElementById){
h=document.getElementById(span).offsetHeight;
}
return h;
}

function highLight(span){
//span.parentNode.style.border = "2px solid #D1FDCD";
//span.parentNode.style.padding = "0";
span.style.border = "1px solid #54CE43";
}

function noLight(span){
//span.parentNode.style.border = "0px";
//span.parentNode.style.padding = "2px";
span.style.border = "0px";


}

//sets post/get vars for update
function setVarsForm(vars){
formVars = vars;
}

addEvent(window, "load", editbox_init);
-->


 
Put these into your datalist.asp table page

In the header of your data list page, put this:
<script type="text/javascript" src="instantedit.js"></script>
 

In the body of your data list page, put this:
<script type="text/javascript"> setVarsForm("pageID=profileEdit&userID=11"); </script>
Edit the variables as desired.The inline edit script seems to work fine without it, but you can put additional variables into it to be retrieved from querystring if you like.

Your rows of records are presumably in a table like this

First Last Job
Janine Turner actress
Jerry Wells horse trainer
Jerzy Kosinski writer

This tutorial assumes you already know how to get an ASP script to spit out rows of records into a html table.

Because I wanted to use Yvo Schaap's Ajax script for inline editing of multiple rows of records, I needed to be able to designate the primary key of the specific record being edited.

To do that, I put a pipe delimiter character in the span id name, followed by the value of the primary key:
<span id="FirstName|<%=rs("DKEY")%>" class="editText"><% response.write rs("FirstName") %></span>

The html the script renders looks something like this:
<td width="98"><span id="FirstName|100" class="editText">Janine</span></td>
<td width="99">Turner</td>
<td width="99">actress</td>
</tr>
<tr>
<td width="98">
<span id="FirstName|102" class="editText">Jerry</span></td>
<td width="99">Wells</td>
<td width="99">horse trainer</td>
</tr>
<tr>
<td width="98">
<span id="FirstName|103" class="editText">Jerzy</span></td>
<td width="99">Kosinski</td>
<td width="99">writer</td>

Then in the script below that processes the data input, the span id name is split at the pipe delimiter and the primary key fished out for use in the sql statement.


 

Save this as update.asp

<%

'this is just an example! You will need to put in some security code to prevent malicious use

xDb_Conn_Str = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & server.mappath("../YourPath/YOURDB.mdb") & ";"

' Open Connection to the database
set conn = Server.CreateObject("ADODB.Connection")
conn.Open xDb_Conn_Str

'How to get the primary key for the record being edited? I decided to add the primary key to the span id with the character | as a separator. Then split the span id/fieldname to get the primary key:
strKarray = Split(Request.querystring("fieldname"), "|")
strField = (strKarray(0)) 'here is my field name
strKey = clng(strKarray(1))   'my primary key is an autonumber, make sure strKey is cint or clng


strsql = "SELECT * FROM [MEMBERS] WHERE [ID]=" & strKey

set rs = Server.CreateObject("ADODB.Recordset")
rs.Open strsql, conn, 1, 2

rs("FirstName") = Trim(request.querystring("content")) 'use Trim to remove any accidental spaces before or after the string


if strField = "FirstName" then
rs("FirstName") = Trim(request.querystring("content")) 'use Trim to remove any accidental spaces before or after the string
strData = rs("FirstName") 'here we get the updated field for sending back to viewer
end if

if strField = "LastName" then
rs("LastName") = Trim(request.querystring("content")) 'use Trim to remove any accidental spaces before or after the string
strData = rs("LastName")  'here we get the updated field for sending back to viewer
end if

'here is an example of handling a numeric field
if strField = "Price" then
If IsNumeric(Trim(request.querystring("content"))) Then
rs("Price") = Trim(request.querystring("content")) 'use Trim to remove any accidental spaces before or after the string
end if
strData = rs("Price) 'here we get the updated field for sending back to viewer
end if

rs.Update

response.write strData 'here the updated field is shown back to you and can be edited again if needed
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing

%>

Test thoroughly before use and back up your database.
Please rate below:

Codango PHP, ASP .NET, JSP Scripts, Resources, Reviews
Click to Read Reviews
User
Rated
What do you think?

 

ASP Examples Menu of Active Server Pages scripts code Classic ASP

Classic ASP Active Server Pages Examples, code, tutorials, scriptsASP Examples Menu (below*)



Active Server Pages | ASP | Scripts | Tutorials | Code | Web Programming | Examples
Active Server Pages ASP code examples, tutorials, and snippets for use in Programming interactive websites.

If you find omissions or errors let me know. I have moved these code samples to their own domain; if you find pieces missing, please let me know.
My favorite scripts site is CODANGO.

*

If any the information I've posted here has been useful to you, please donate.

Quick 'n  easy  dirty PHP script code wizard-generator

Zenphoto RSS XML feed used as data source for javascript slide show with PHP

Classic ASP to archive emails into database and save attached files to folder

PHP Image GD for thumbnails and image resizing with pathing for Windows servers

ODBC database connections for Microsoft Access MDB files with Windows 7: solution posted on this forum.

HTML5 embedded video player "Projekktor" completely skinnable with hyperlinked watermark

Edit web.config to allow Windows iis7 server to handle mp4 files or other mime types as needed

URL rewrite or make friendly URLs for iis7 Windows Server 2008 by editing your web.config file

FACEBOOK API GEEWHIZ - INTEGRATE FACEBOOK WITH YOUR WEBSITE

Use PHP to zip folders for backing up a website

Use PHP to archive emails in database and save attached files to folder

Use PHP with json to check how many hits left on Twitter API

PHP get single record from Access database without catchable fatal error message

PHP to make a bot to send automatic Twitter status updates with Abraham Williams' PHP Oauth Twitter Library

A way to use the PHP Oauth Twitter Library with your Classic ASP scripts for sending status updates

Get user's IP address location for your form results

Tutorial for registering an application with Twitter

Update your Twitter status with Classic ASP and Oauth seamlessly and invisibly without having to login to Twitter. Send status updates programmatically from a web page. PHP example too.

CLASSIC ASP: Cache your Twitter tweets in a database to keep your Twitter xml requests within the rate limit of 350 per hour / PHP VERSION

PHP: Use json to fetch Twitter followers' profiles

Index files content and insert into database for faster searches

Classic ASP with Ajax: secure URL check

Classic ASP with Ajax: referer check

Classic ASP with Ajax: a solution to the ampersand problem in querystrings

Very Simple Star Rating System for Classic ASP

Star Rating System uses CSS and JS adapated for Classic ASP from Yvo Schaap PHP script

XMLhttp with ASP to fetch and save photos from Photobucket account through RSS XML. Can be adapted for Youtube videos to import data to database.

NET image resize can be used to make thumbnails for Classic ASP

Track site visitors, get their ip address geographical data, count page views with Classic ASP

Javascript slideshow with Classic ASP to load image details dynamically from database photos table

Classic ASP with Ajax for rotating banners without page refresh and XML file converted to recordset as banner database
--Variation of the above but fetching a REMOTE XML file as the database
--Variation checks for secure URL and builds absolute URL and makes offsite banner links open in new window

True inline edit Classic ASP datagrid table database edit updating with Ajax SIMPLE EASY without page refresh!

Use Ajax with Classic ASP to preview data then update form with javascript url write

Yvo Schaap's easy inline edit Ajax: an example of using it to inline edit multiple rows of records in Classic ASP

Use Classic ASP to send text messages SMS from your website (Also shows how to use xmlhttp to post form data)

Ajax with Classic ASP for seamless, no page reload database record insertion

Nested SQL Statements to make temporary column names

Multiple records per row with paging

Display multiple records per row

Get ID of newly inserted record, Classic ASP, Access Database

Javascript timer with ASP to keep track of time expired until login expires / timeout session is up

Multiple Javascript event functions triggered from single form onsubmit

Get Querystring key names along with querystring variables

These are out of date but may still be of interest:

ASP Youtube Downloader  Version FOUR
All ASP code. Allows user client side downloads of Youtube videos. You have the option to allow files to be saved directly to your site also.
ASP/PHP video downloader (Works better than ASP for large files)

Use ASP to dynamically parse a Youtube XML playlist to render to html.

Zip up an archive file of your site for backup if you need to restore website with ASP and free Zip Component.

Zip all files in a folder into an archive or backup file dynamically by specific file extension.

Sanitize or clean price cost field for database insertion or display.

Javascript image dimensions and image file size preview.

Put recordset into array, assign keys to the records then use record associated with specific array key as a variable elsewhere.

Access Database Interface Generator Wizard to read your table and field names and to create a table display.

Combining dropdown selection box menu with dynamic ASP database page.

How to redirect user to original page they tried to view before logging, after they are logged in.

Previous/Current/Next Records, or Buddy Ring Script

Custom ASP 404 page not found error script: can also be used for URL rewriting

ASP Example: Combine ASP with Javascript for popup windows
dynamically sized to image dimensions.

ASP Example: How to use ASPJPEG to create thumbnails
Click for free Highly recommended thumbnailer for which you don't need Server access (doesn't seem to work on Windows Server 2008)

ASPjpeg: How to re-scale aspect ratio of thumbnails by height instead of width.

ASP Example: What if your host has an older version of ASPJPEG that doesn't support gifs?

Select Count Distinct Records for Access Database

Upload Image to folder and insert filename into database

Get date in such a way that it can be made part of a file name

Isolate a file name away from its path or extension or strip a path from a file name or strip characters from database field

User-customized on-the-fly stylesheet css files

Enhanced Page Hits Counter (also counts downloads and menu link hits)

Loop through array and compare to string with select case

Aphabetical Paging for your ASP scripts

Web Wiz Guide's Site Searcher Script modified as a file content indexer

Let Users Select How Many Records to View

Access Database for your PayPal IPN scripts

Miscellaneous collected code

From Classic ASP to PHP

You don't have to be a genius, just persistent, to write original Active Server Pages scripts

BuildApp - great old Classic ASP script generator!

Software Recommendation: bare_bones_no_bells_and_whistles_asp_code_generator_database_interface_maker (For PHP I recommend EasyGen.)

If any of this information is helpful to you, please consider donating with the button below. Thanks! ~~Lil