Ajax Talk - Asynchronous javascript and xml discussion board
 FAQ   Search    Usergroups      Register   Profile   Check your messages   Log in 
Signup now to enjoy a range of free membership advantages !!
Ajax Talk - Moderators Wanted
Ajax problem

 
Post new topic   Reply to topic    Ajaxtalk.com Forum Index -> AJAX Help
View previous topic :: View next topic  
Author Message
thebeast
New one
New one


Joined: 23 Jul 2006
Posts: 3

PostPosted: Sun Jul 23, 2006 10:15 am    Post subject: Ajax problem Reply with quote

Hi there,

I am trying to create a form, that when the user clicks on the 'Save' button, AJAX takes the form data and delivers it to a script behind the scenes, without the original form page reloading... i then have information that is sent back from the server (once processing of the form is complete) display a message in the originating form window.

The problem I am having is that wierdly, when I have the various form elements in a table, the AJAX doesnt work.. it doesnt send any of the form values at all. If i remove all of the table structure, everything really works well. Now, I need to keep it in tabular form, because i am dealing with dynamic stuff coming from a database, and for me, tabular layout is my best (and easiest) solution.

I have simplified the code down to the bare minimum, just to show what works and what doesnt.

Can anyone help with fixing the issue why having form elements in tabular format causes the AJAX processing not to function properly?

Code for index.html
Code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
   
<link rel="stylesheet" href="../css/list_tracks.css" type="text/css" />
<script type="text/javascript" language="javascript">
   var http_request = false;
   function makeRequest(url, parameters) {
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
            // set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
      http_request.onreadystatechange = alertContents;
      http_request.open('GET', url + parameters, true);
      http_request.send(null);
   }

   function alertContents() {
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
            //alert(http_request.responseText);
            result = http_request.responseText;
            document.getElementById('myspan').innerHTML = result;           
         } else {
            alert('There was a problem with the request.');
         }
      }
   }
   
   function get(obj) {
      var getstr = "?";
      for (i=0; i<obj.childNodes.length; i++) {
         if (obj.childNodes[i].tagName == "INPUT") {
            if (obj.childNodes[i].type == "text") {
               getstr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&";
            }
         }   
       
      }
      makeRequest('get.php', getstr);
   }
</script>
</head>
<body>

Version 1:
</p>

<br><br>

<form action="javascript:get(document.getElementById('myform'));" name="myform" id="myform" method="get">
<table>
   <tr>
      <td>
            <input type="text" name="myfield" value="this is field 1">
      </td>
   </tr>
   <tr>
      <td>
         <input type="text" name="another field" value="a lovely field">
      </td>
   </tr>
</table>
<br>
<input type="button" name="button" value="Submit"
   onclick="javascript:get(this.parentNode);">
</form>

<hr  />

<p>
Version 2:
</p>

<br><br>

<form action="javascript:get(document.getElementById('myform'));" name="myform" id="myform">
<input type="text" name="myfield" value="version 2, field 1"><br>
<input type="text" name="another field" value="some useless info"><br>

<br>
<input type="button" name="button" value="Submit"
   onclick="javascript:get(this.parentNode);">
</form>

<br><br>
Server-Response:<br>
<span name="myspan" id="myspan"></span>

</body>
</html>


Code for the processing script, get.php (i simply am calling $_GET, which will print all of the elements... a simple method to see if any data is in fact coming through to the server):
Code:

<?php
print_r($_GET);
?>


It is very weird and confusing lol... I am still quite new to JS and all that it entails!

Thanks in advance Very Happy
Back to top
View user's profile Send private message
deejay
Forum Assistant
Forum Assistant


Joined: 17 May 2006
Posts: 78
Location: Netherlands

PostPosted: Mon Jul 24, 2006 12:04 pm    Post subject: hi beast Reply with quote

Hi beast,

I played around with your example and couln'dt get it to work quickly. (Also both versions generated errors in ie.)

However i can help you by giving you the following script, this is doing exactly the same.

Got this from dynamicdrive.com and enhanced it (also this contains tabular design).

Don't know about cross browser issues, maybe somebody else can solve that;

live demo:
http://www.terrababy.nl/web2.0/

contents from index.php:

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>De rijke gebruikerservaring van Web 2.0 Ajax demo - scripts formulieren e4x web 2.0 web2.0 interaction usability</title>
<link rel="stylesheet" href="style.css" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta name="ROBOTS" content="ALL" />
<meta name="revisit-after" content="1 days" />
<meta name="Keywords" content="Ajax demo scripts formulieren e4x web2.0" />
<meta name="Description" content="Terrababy: Ajax demo scripts formulieren e4x web2.0 !" />

<script type="text/javascript" src="ajaxroutine.js"></script>
<script type="text/javascript" src="process.js"></script>
</head>

<body>
<div align="center">

<table width="90%" class="tab2" border="0">
<tr bgcolor="#E9E9E9"><td height="18" colspan="2" align="center">
<table width="100%"><tr><td width="67">&nbsp;</td><td>
<br/>
<br/>
<font class="head0">De rijke gebruikerservaring van Web 2.0</font>
<br/>
<br/>
<font class="mail">Wilt u dat uw site ook tot de nieuwe generatie sites behoort ? Lees dan verder ...</font><br />
<br />
</td><td width="67">
<img src="pic.jpg" alt="Auteur: D.J. de Groot" width="67" height="84" />
</td></tr></table>

</td></tr>
<tr><td valign="top" colspan="2" align="center">

<br/>
<font class="head1">AJAX en E4X demonstratie scripts</font>
<br/>
<br/>

<table width="95%"><tr><td class="left">
Dit is een demonstratie van de nieuwe technieken die sinds kort beschikbaar zijn op het web en worden gebruikt om een rijke gebruikerservaring neer te zetten voor internetgebruikers.
<br/>
<br/>
Deze technieken worden al lang gebruikt in conventionele software maar op het web is het relatief nieuw.
<br/>
<br/>
De techniek heet AJAX en staat voor A-synchroon Javascript and XML. Een moeilijke term die aangeeft dat er updates op de pagina kunnen plaatsvinden aan de gebruikers kant met informatie van de server kant, zonder dat de pagina daarvoor opnieuw behoeft te worden ingeladen. E4x is een nieuwe extensie op Javascript die interactie kan hebben met XML.
<br/>
<br/>
Voorbeelden van toepassingen zijn o.a.; automatisch aanvullen van gegevens op basis van input (zgn auto-complete functie), directe validatie en verwerking van formulieren, sorteren van tabellen etc.
<br/>
<br/>
Een groot voordeel van deze techniek is dat alleen de noodzakelijke code wordt ingeladen, dit kan forse besparingen in bandbreedte opleveren bij druk-bezochte sites.
<br/>
<br/>
<br />


<center><font class="head1">Een demonstratie AJAX formulier</font></center>

<br/>
<br/>
Probeer een van de volgende mail adressen in te voeren; <a href="#" onclick="javascript:myform.mail.value='test@test.nl'; myform.nick.value='test'">'test@test.nl'</a>,<a href="#" onclick="javascript:myform.mail.value='test@worldcom.com'; myform.nick.value='test'">'test@worldcom.com'</a>, <a href="#" onclick="javascript:myform.mail.value='jouw@email.nl'; myform.nick.value='jouw'">'jouw@email.nl'</a>, probeer html in te voeren, een e-mail adres dat niet correct is, een bijnaam van minder dan 3 karakters. Bijvoorbeeld dit adres is gewoon beschikbaar:  <a href="#" onclick="javascript:myform.mail.value='beschikbaar@test.nl'; myform.nick.value='beschikbaar'">'beschikbaar@test.nl'</a>
<br/><br/>


<table width="80%" class="tab" align="center"><tr><td align="center">

<br /><font class="mail">Wil je lid worden van de nieuwsbrief ? Vul hieronder je mail adres in.<br /></font>
<br/>


<span id="Messmail" class="center" style="font-size:14px;font-weight:bold;font-family:verdana;color:red;"></span>

<form id="myform" name="myform" action="">
<? print '
<input type="text" size="18" value="jouw bijnaam" class="inputfront" onfocus="value=\'\';this.className=\'inputback\';" onblur="this.className=\'inputfront\';"  name="nick" />&nbsp;&nbsp;

<input type="text" size="18" value="jouw@email.nl" class="inputfront" onfocus="value=\'\';this.className=\'inputback\';" onblur="this.className=\'inputfront\'; " name="mail" />&nbsp;&nbsp;

<input type="button" value="Verstuur" onclick="var poststr=createpoststring(); ajaxpack.postAjaxRequest(\'profile_submit.php\', poststr, processGetPost, \'txt\'); return false" class="inputfront" onmouseover="this.className=\'inputback\';" onmouseout="this.className=\'inputfront\';" /></form>
'; ?>
</td></tr></table>
<br/>
<br/>

In dit voorbeeld worden er validatieregels aan de server kant doorgevoerd die in de database kijken of het mail adres al in het bestand staat. Deze gegevens worden vervolgens teruggestuurd naar deze file zonder een refresh van de pagina. Uw testgegevens worden overigens niet opgenomen in de database. Met een aanpassing is dit operationeel te maken.
<br/>
<br/>
De taal aan de server kant is php, maar dit voorbeeld is servercode onafhankelijk. U kunt dus ook asp, coldfusion of andere talen gebruiken. Wij kunnen de servercode voor u opstellen in php, coldfusion en asp.
<br/>
<br/>

Voor informatie over wat dit voor uw site kan betekenen kunt u contact opnemen met <a href="mailto:info@terrababy.nl">info@terrababy.nl</a>. Kijk ook op <a href="http://www.terrababy.nl" target="_blank">terrababy.nl</a>. <br/>
<br/>
Wij kunnen uw site of intranet voorzien van AJAX technologie zodat ook uw bezoekers een Web 2.0 ervaring kunnen hebben.
<br/>
<br/>
<br/><br/><!-- Search Google -->
<center>
<form method="get" action="http://www.google.nl/search">
<table bgcolor="#FFFFFF"><tr><td>
<a href="http://www.google.nl/">
<img src="http://www.google.com/logos/Logo_40wht.gif"
border="0" alt="Google" /></a></td><td>
<input type="text" name="q" size="31" maxlength="255" value="" class="inputfront" onfocus="this.className='inputback';" onblur="this.className='inputfront';" />
<input type="hidden" name="hl" value="nl" />
<input type="submit" name="btnG" value="Google Zoeken" class="inputfront"  onmouseover="this.className='inputback';" onmouseout="this.className='inputfront';" />
</td></tr></table>
</form>
</center>
<!-- Search Google -->

</td></tr></table>
</td></tr>

<tr bgcolor="#E9E9E9"><td height="18" class="left" colspan="2">
<a href="http://validator.w3.org/check?uri=referer" target="_blank"><img src="valid-xhtml10.gif"  alt="Valid XHTML 1.0 Transitional" border="0"/></a>

</td></tr>

<tr bgcolor="#E9E9E9"><td height="18" class="left">&nbsp;
Design en ontwikkeling: <a href="http://www.terrababy.nl" target="_blank" class="design2" style="a.hover: #e9e9e9;">terrababy.nl</a> | Hosting: <a href="http://www.ipxl.nl " target="_blank" class="design2" style="a.hover: #e9e9e9;">ipxl.nl</a>
</td><td class="right">Dit artikel is geschreven door D.J. de Groot. Met dank aan <a href="http://www.dynamicdrive.com" target="_blank" class="design2" style="a.hover: #e9e9e9;">dynamicdrive.com</a>&nbsp;</td></tr></table>
</div>

</body></html>


contents from ajaxroutine.js (thx to dd):

Code:
//Basic Ajax Routine- Author: Dynamic Drive (http://www.dynamicdrive.com)
//Last updated: Jan 15th, 06'

function createAjaxObj(){
var httprequest=false
if (window.XMLHttpRequest){ // if Mozilla, Safari etc
httprequest=new XMLHttpRequest()
if (httprequest.overrideMimeType)
httprequest.overrideMimeType('text/xml')
}
else if (window.ActiveXObject){ // if IE
try {
httprequest=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
try{
httprequest=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){}
}
}
return httprequest
}

var ajaxpack=new Object()
ajaxpack.basedomain="http://"+window.location.hostname
ajaxpack.ajaxobj=createAjaxObj()
ajaxpack.filetype="txt"
ajaxpack.addrandomnumber=0 //Set to 1 or 0. See documentation.

ajaxpack.getAjaxRequest=function(url, parameters, callbackfunc, filetype){
ajaxpack.ajaxobj=createAjaxObj() //recreate ajax object to defeat cache problem in IE
if (ajaxpack.addrandomnumber==1) //Further defeat caching problem in IE?
var parameters=parameters+"&ajaxcachebust="+new Date().getTime()
if (this.ajaxobj){
this.filetype=filetype
this.ajaxobj.onreadystatechange=callbackfunc
this.ajaxobj.open('GET', url+"?"+parameters, true)
this.ajaxobj.send(null)
}
}

ajaxpack.postAjaxRequest=function(url, parameters, callbackfunc, filetype){
ajaxpack.ajaxobj=createAjaxObj() //recreate ajax object to defeat cache problem in IE
if (this.ajaxobj){
this.filetype=filetype
this.ajaxobj.onreadystatechange = callbackfunc;
this.ajaxobj.open('POST', url, true);
this.ajaxobj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
this.ajaxobj.setRequestHeader("Content-length", parameters.length);
this.ajaxobj.setRequestHeader("Connection", "close");
this.ajaxobj.send(parameters);
}
}

//ACCESSIBLE VARIABLES (for use within your callback functions):
//1) ajaxpack.ajaxobj //points to the current ajax object
//2) ajaxpack.filetype //The expected file type of the external file ("txt" or "xml")
//3) ajaxpack.basedomain //The root domain executing this ajax script, taking into account the possible "www" prefix.
//4) ajaxpack.addrandomnumber //Set to 0 or 1. When set to 1, a random number will be added to the end of the query string of GET requests to bust file caching of the external file in IE. See docs for more info.

//ACCESSIBLE FUNCTIONS:
//1) ajaxpack.getAjaxRequest(url, parameters, callbackfunc, filetype)
//2) ajaxpack.postAjaxRequest(url, parameters, callbackfunc, filetype)

///////////END OF ROUTINE HERE////////////////////////


//////EXAMPLE USAGE ////////////////////////////////////////////
/* Comment begins here

//Define call back function to process returned data
function processGetPost(){
var myajax=ajaxpack.ajaxobj
var myfiletype=ajaxpack.filetype
if (myajax.readyState == 4){ //if request of file completed
if (myajax.status==200 || window.location.href.indexOf("http")==-1){ if request was successful or running script locally
if (myfiletype=="txt")
alert(myajax.responseText)
else
alert(myajax.responseXML)
}
}
}

/////1) GET Example- alert contents of any file (regular text or xml file):

ajaxpack.getAjaxRequest("example.php", "", processGetPost, "txt")
ajaxpack.getAjaxRequest("example.php", "name=George&age=27", processGetPost, "txt")
ajaxpack.getAjaxRequest("examplexml.php", "name=George&age=27", processGetPost, "xml")
ajaxpack.getAjaxRequest(ajaxpack.basedomain+"/mydir/mylist.txt", "", processGetPost, "txt")

/////2) Post Example- Post some data to a PHP script for processing, then alert posted data:

//Define function to construct the desired parameters and their values to post via Ajax
function getPostParameters(){
var namevalue=document.getElementById("namediv").innerHTML //get name value from a DIV
var agevalue=document.getElementById("myform").agefield.value //get age value from a form field
var poststr = "name=" + encodeURI(namevalue) + "&age=" + encodeURI(agevalue)
return poststr
}

var poststr=getPostParameters()

ajaxpack.postAjaxRequest("example.php", poststr, processGetPost, "txt")
ajaxpack.postAjaxRequest("examplexml.php", poststr, processGetPost, "xml")

Comment Ends here */



contents of process.js

Code:
// JavaScript Document
function processGetPost(){
var myajax=ajaxpack.ajaxobj
var myfiletype=ajaxpack.filetype
if (myajax.readyState == 4){ //if request of file completed
if (myajax.status==200 || window.location.href.indexOf("http")==-1){ //if request was successful or running script locally
if (myfiletype=="txt")
Messmail.innerHTML = myajax.responseText;
else
alert(myajax.responseXML)
}}}

function createpoststring(){
var mailvalue   =document.getElementById("myform").mail.value //get value to post from a form field
var nickvalue   =document.getElementById("myform").nick.value //get value to post from a form field

var poststr = "mail=" + encodeURI(mailvalue) + "&nick=" + encodeURI(nickvalue);
return poststr
}


contents of profile_submit.php:
Code:

<?

if ( is_array($_POST) )
    {
        // Loop through POST array
        foreach( $_POST as $key => $value )
        {
         $_POST[$key] = ereg_replace( "['\"\<>#{}]", "", trim($value) );
        }
    }

foreach ($HTTP_POST_VARS as $postvar) {
   if (preg_match("/([\<])([^\>]{1,})*([\>])/i", $postvar)) {
    $problem = TRUE;
   $error_array[] = "Een van de velden bevat html tags !";
   }
   }

$mail=$_POST['mail'];
$url=$_POST['url'];
$ext=$_POST['ext'];
$nickname=$_POST['nick'];


$string = $mail;

   if (!eregi ("^([a-z0-9_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,4}$", $string) ) {
      $problem = TRUE;
      $error_array[]= '<br><br>Dit is geen geldig e-mail adres. ';}


   if($nickname == 'jouw bijnaam' || !trim($nickname) || strlen(trim($nickname)) < 3) {
   $problem = TRUE;
   $error_array[]= '<br><br>Deze bijnaam kan niet worden gebruikt of dit veld is leeg of een te kleine bijnaam.'; }
   


$mail_array = array('test@test.nl','test@worldcom.com', 'jouw@email.nl');

if (in_array($mail, $mail_array)) {

   $problem = TRUE;
   $error_array[]= '<br><br>Dit e-mail adres is al in gebruik, kies een andere';
   }




if ($problem) {
   print '<p> Er zijn de volgende fouten aangetroffen : </p>';
   
   foreach ($error_array as $error) {
   print $error;
   }
   
   } else {
   
   $mail_array[] = $mail;


   print "<font color=\"green\">Je bent nu ge-abonneerd, $nickname</font>";
   
   }
   

?>

_________________
please correct me if i am wrong
seo-expertglobalwarming
Back to top
View user's profile Send private message Visit poster's website MSN Messenger
Snyke
Forum Assistant
Forum Assistant


Joined: 20 Jun 2006
Posts: 87
Location: Zurich

PostPosted: Mon Jul 24, 2006 1:10 pm    Post subject: Reply with quote

Hey deejay, in Firefox your code produces some errors, but the good news is that the request is actually sent:
Quote:
POST http://www.terrababy.nl/web2.0/profile_submit.php
PostResponseHeaders

mail=jouw@email.nl&nick=jouw%20bijnaam

<p> Er zijn de volgende fouten aangetroffen : </p><br><br>Deze bijnaam kan niet worden gebruikt of dit veld is leeg of een te kleine bijnaam.<br><br>Dit e-mail adres is al in gebruik, kies een andere

Content-Type: text/html
Server: Microsoft-IIS/6.0
X-Powered-By: PHP/4.4.3RC3-dev, ASP.NET
Date: Mon, 24 Jul 2006 13:07:35 GMT
Connection: close

ajaxroutine.js (line 52)
junk after document element
profile_submit.ph... (line 1)
<p> Er zijn de volgende fouten aangetroffen : </p><br><br>Deze bijnaam kan niet worden gebruikt of dit veld is leeg of een te kleine bijnaam.<br><br>Dit e-mail adres is al in gebruik, kies een andere --------------------------------------------------^
Messmail is not defined
process.js (line Cool
processGetPostprocess.js (line Cool
anonymousfirebug.js (line 951)
anonymousfirebug.js (line 2049)
Messmail is not defined
process.js (line Cool

_________________
[::[ Snyke.net ]::]
Back to top
View user's profile Send private message Visit poster's website MSN Messenger
thebeast
New one
New one


Joined: 23 Jul 2006
Posts: 3

PostPosted: Tue Jul 25, 2006 11:12 pm    Post subject: Reply with quote

Thanks for the responses Very Happy

I have not yet been able to look at the code that you have supplied, but I appreciate your efforts in helping me out, and I will certainly play around with the code to see if I can use it for my site.

Thanks again Very Happy

--
theBeast
Back to top
View user's profile Send private message
thebeast
New one
New one


Joined: 23 Jul 2006
Posts: 3

PostPosted: Thu Jul 27, 2006 12:36 am    Post subject: Reply with quote

I also posted this question on another forum, a little while back, and recently got a response. This has solved the problem, and works great for me.

I thought, i would share the code that fixed the problem;

Code:
function get(frm) {
      var getstr = "?";
      for (i=0; i<frm.elements.length; i++) {
         if (frm.elements[i].type == "text") {
               getstr += frm.elements[i].name + "=" + frm.elements[i].value + "&";
         }
      }
      makeRequest('get.php', getstr);
   }
...
<input type="button" name="button" value="Submit"
   onclick="javascript:get(this.form);" />
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    Ajaxtalk.com Forum Index -> AJAX Help All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
 Advertisements
 XML & Copyright Notice 
    


Powered by phpBB © 2001, 2005 phpBB Group

What is according to Wikipedia: Ajax Web2.0 XML E4X


Link to our site:

  


del.icio.us digg spurl wists simpy newsvine blinklist furl blogmarks yahoo! myweb smarking ma.gnolia segnalo reddit fark technorati cosmos


Normal Bookmark


Partner Button Links:
Codecrunch.com: Webmaster Tutorials    One Ajax


Partner Text Links:
quomon | web20log | ajaxmatters | tableless | 456bereastreet | music charts | gift ideas | competitions | free xbox 360 | link trade ?


Credits:
it consultancy & project management lead generation zoekmachine optimalisatie steal these buttons seo expert