Updating form with AJAX

5 views
Skip to first unread message

Jamen

unread,
Apr 24, 2009, 1:36:17 PM4/24/09
to Webmasters Helping Webmasters, jamen.mc...@vanderbilt.edu
I'm fairly new to trying to use AJAX, so please forgive my ignorance.
I know it is possible to update a form with new content with AJAX, and
I've actually been able to do that - but just on one form element. The
problem I have is trying to update another form element on that same
page.

Here is my js code (update.js):
----------------------------------------------
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!

try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var priority = document.getElementById('priority').value;
var id = document.getElementById('id').value;
var express = document.getElementById('express').value;
var queryString = "?priority=" + priority + "&id=" + id + "&express="
+ express;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}

-----------------------------------
Here is my ajax-example.php code:

<?php

//Database connection
include ('db.php');

// Set Table Variable
$table = purchase_os;

// Retrieve data from Query String
$listitem=array(1 =>
'priority','express','expressdate','location','bibname','fundnum','lowuse','received','userid','addcomments','notify','name','idnum','depart','telnum','email','mat','access','lic','neg','fileloc','url','col','numtit','recs','funds','author','title','pubplace','publisher','edition','price','quantity','series','standorder','isnnum','source','catnum','itemnum','comments','acornnum','vendor','verifier','verifydate','status','ccemail');

$listvars=array(1 =>
'$priority','$express','$expressdate','$location','$bibname','$fundnum','$lowuse','$received','$userid','$addcomments','$notify','$name','$idnum','$depart','$telnum','$email','$mat','$access','$lic','$neg','$fileloc','$url','$col','$numtit','$recs','$funds','$author','$title','$pubplace','$publisher','$edition','$price','$quantity','$series','$standorder','$isnnum','$source','$catnum','$itemnum','$comments','$acornnum','$vendor','$verifier','$verifydate','$status','$ccemail');

$numitems = count($listitem);

$i = 1;
while ($i <= $numitems) {
$x = $listitem[$i];
if (isset($_GET[$x]) && !is_null($_GET[$x])) {
$listvars[$i] = $_GET[$x];
$z = $listvars[$i];
$listvars[$i] = mysql_real_escape_string($z);
} else {
$listvars[$i] = null;
}
$i++;
}

// Build update query
$query_1 = "UPDATE $table SET ";
$query_3 = "' WHERE id = '$id'";

$k = 1;
while ($k <= $numitems) {
if (isset($listvars[$k]) && !is_null($listvars[$k])) {
$query[$k] = $query_1 . $listitem[$k] . "='" . $listvars[$k] .
$query_3;
}
$k++;
}

// Build results query
$query2 = "SELECT * FROM $table WHERE id = '$id'";

// Execute update query
$m = 1;
while ($m <= $numitems) {
if (isset($query[$m]) && !is_null($query[$m])) {
$qry_result = mysql_query($query[$m]) or die(mysql_error());
}
$m++;
}

$qry_result2 = mysql_query($query2) or die(mysql_error());

//Build Result String
$display_string = "<table>";

// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result2)){
$display_string .= "<tr>";
$display_string .= "<td>This has been updated to<br />$row[priority]</
td>";
$display_string .= "</tr>";

}
$display_string .= "</table>";
echo $display_string;

?>

---------------------

And here is my form (modify-backup.php):

<?php
// Start session to save session data
session_start();

//Header/footer
include('headfoot.php');

//Database connection
include ('db.php');

$id = $_GET["i1"];

$query = "SELECT * FROM purchase_os WHERE id=$id";
$result = mysql_query($query);

$num_rows = mysql_num_rows($result);

echo "$header";

while ($myrow = mysql_fetch_array($result)) {
echo "<table width='100%' border='1'>";
echo "<tr><td colspan='3' align='center'>Record Number: " . $myrow
['id'] . "</td></tr>";
echo "<tr><td width='33%'>&nbsp;</td><td width='33%'>Current Value</
td><td width='33%'>Update Value With:</td></tr>";
echo "<tr><td> Priority:</td><td>" . $myrow['priority'] . "<br /
><div id='ajaxDiv'></div></td>";
echo "<td><form name='myform'>Priority: <select id='priority'>";
echo "<option> </option><option>Level 1 - Patron Request</option>
<option>Level 1 - Rush</option>
<option>Level 1 - SuperRush (Leisure Reading Collection Only)</option>
<option>Level 1 - Reserve</option>
<option>Level 2 - Reference</option>
<option>Level 2 - Leisure Reading</option>
<option>Level 2 - Other</option>
<option>Level 3</option>";
echo "</select>";
echo "<br />";
echo "<input type='button' value='Update data' onclick='ajaxFunction
();' />";
echo "</td></tr>";
echo "<tr><td>Date Sensitive Order: </td><td>" . $myrow['express'] .
"<br /><div id='ajaxDiv'></div></td>";
echo "<td>Date Sensitive?<br />";
echo "<input type='radio' name='express' id='express' value='yes' /
>Yes";
echo "<input type='radio' name='express' id='express' value='no' /
>No";
echo "<br />";
echo "<input type='hidden' id='id' value='" . $myrow['id'] . "' />";
echo "<input type='button' value='Update data' onclick='ajaxFunction
();' />";
echo "</form>";
echo "</td></tr>";
echo "</table>";
}

echo "$footer";
?>

Vision Jinx (Guru)

unread,
Apr 24, 2009, 10:03:42 PM4/24/09
to Webmasters Helping Webmasters
Hi,

I am not entirely clear on exactly what your asking/needing so if you
can please provide a bit more information that would be great.

Best I can tell what your looking for is you need to separate your
AJAX function in to a more versatile and independent wrapper function
then use another javascript function call on your form to get the
values and create the URL then pass that to your ajax function.


eg. function myajax(queryUrl,resultID){Do Ajax Stuff}

Then this way you can just attach a handler on your form submit
onsubmit="processForm(this);return false;" to grab the data from your
form and create your query string for your ajax function to process.

You can then use that same ajax function to initially create the form
also either on a window.onload=function(){Make AJAX Form....}; or
using an onclick event too after the page loads.

I just love AJAX, there are so many ways to play with it. If you need
I can post some code for a more "independent" ajax wrapper so you can
take your "ajax-example.php" + queryString and ajaxDisplay.innerHTML
out of that function. This will give your ajax apps a lot more
versatility.

Also, http://paste-it.net/ or http://pastebin.com/ works much better
for posting large chunks of code where groups does a lot of
reformatting (and line breaks) making code debugging a problem in
groups.


Cheers!
Vision Jinx

Jamen McGranahan

unread,
Apr 25, 2009, 10:37:46 PM4/25/09
to Webmaste...@googlegroups.com
To answer your first question: What I want to do is bring up the full record (which contains 46 fields from a MySQL table) with 3 columns:

column 1 = field name
column 2 = current setting
column 3 = forms available for changing the setting

This is one reason why I tried to use arrays in my PHP script. Ideally, what I want it to do is allow a user to bring up the full record, find the field they want to update, change the setting and click the Update Field button. This button should activate a function that updates this field and displays in the Current Field with "This field has been updated with $v" (where $v is the new value). Does this make sense?

And thanks for the tip about the how to submit codes to groups like this.

Jamen

Vision Jinx (Guru)

unread,
Apr 27, 2009, 11:22:45 PM4/27/09
to Webmasters Helping Webmasters
Hi,

I made a sample script here >> http://paste-it.net/public/m06ca65/

This should help get you going with what you need. It's the basic AJAX
GET request wrappers and a sample form handler and looking at the code
you provided it should help do what your trying to do in a more
versatile way (meaning your form/query parameters are not hard coded
in your AJAX handler).

I did not go too overboard on it and tried to keep it as simple and
self explanatory as possible. You should be able to add an updated/
custom version of that form handler to suit your needs (the only thing
that really needs editing) and I included a javascript wrapper if you
prefer using document.getElementById over the names for form elements
as I used in my sample (or you can easily use both).

Hope this helps :)

Cheers!
Vision Jinx
> > Also,http://paste-it.net/orhttp://pastebin.com/works much better

Vision Jinx (Guru)

unread,
Apr 27, 2009, 11:32:08 PM4/27/09
to Webmasters Helping Webmasters
Oops, small syntax error in the window.onload it should not have a
comma (,) but a dot (.) Strange it did not throw an error o.O

Anyways, not a big part of the scripts functionality, just a small
typo :D

Cheers!
Vision Jinx
> > > Also,http://paste-it.net/orhttp://pastebin.com/worksmuch better
> ...
>
> read more »
Reply all
Reply to author
Forward
0 new messages