By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,254 Members | 1,713 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,254 IT Pros & Developers. It's quick & easy.

Why is a variable sometimes sent and other times not?

Claus Mygind
100+
P: 571
On the web page I have two forms. The first created statically, the 2nd created dynamically (upon request)

Both forms make the same ajax call to the server.
Both use the same javaScript routines to make the call.
Both call the same server side app.

I store the data in a variable/array "appData" which I JSON encode.

On the server side app, I look for the JSON element "appData" and decode it.

appData is not present when the dynamic form makes the request.

Here is my code and screen shots of where the code was halted to show the content of the variables.

This is my ajax routine
Expand|Select|Wrap|Line Numbers
  1. function myAjax (form, dataObj ) {
  2.  
  3.     var    aCallBack = new Array();
  4.  
  5.     this.makeCall = function (form, dataObj) {
  6.  
  7.         var queryString  = "appData="+JSON.stringify(dataObj);
  8.  
  9.         var request = window.ActiveXObject ?
  10.             new ActiveXObject('Microsoft.XMLHTTP') :
  11.             new XMLHttpRequest;
  12.  
  13.             var url = form.action+'?timeStamp=' + new Date().getTime();
  14.  
  15.             request.open("POST", url, true);
  16.             request.onreadystatechange = function chkStateChange(){
  17.                                             if (request.readyState == 4) {
  18.                                                 if (request.status == 200) {
  19.                                                     processResponse(request.responseText, form);
  20.                                                 }
  21.                                             }
  22.                                          };
  23.             request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  24.  
  25.             request.send( queryString );
  26.     };
  27.  
  28.     var processResponse = function (response, form) {
  29.  
  30.         aCallBack = response.split(';');
  31.  
  32.         if ( aCallBack[0].indexOf("An error occured") > -1 ||
  33.              aCallBack[0] == "Record Saved"    ||
  34.              aCallBack[0].indexOf("deleted") > 1     ||
  35.              aCallBack[0] == "The data you saved was the same as found in the database!"
  36.            ) { 
  37.  
  38.             eAlert  = aCallBack[0]+"\n";
  39.             for (var i = 1; i < aCallBack.length; i++ )
  40.             {
  41.                 eAlert += aCallBack[i]+"\n";
  42.             }
  43.             alert( eAlert );
  44.             clearForm( document.getElementById(form.id) );
  45.             AddMode();
  46.         }else{
  47.             aCallBack = JSON.parse(response);        
  48.             updatePage(form, aCallBack);
  49.         }
  50.     };
  51. }
  52.  
  53. var ajax = new myAjax();
  54.  
The ajax routine is called from the "saveData" routine which receives one parameter "form".
Expand|Select|Wrap|Line Numbers
  1. function saveData(form)
  2. {
  3.     var dataObj = new Object();
  4.  
  5.     var encode = function (strVal)
  6.     {
  7.         if (strVal.indexOf('&') > -1)
  8.         {
  9.             var searchStr = "&";
  10.             var replaceStr = "%26";
  11.             var re = new RegExp(searchStr, "g");
  12.             var result = strVal.replace(re, replaceStr);
  13.         }else{
  14.             var result = strVal;
  15.         }
  16.             return result;
  17.     };
  18.  
  19.     for (var i = 0; i < form.elements.length; i++)
  20.     {
  21.         var element = form.elements[i];
  22.         var type = element.type;
  23.  
  24.         if (type == "checkbox")
  25.         {
  26.             if (element.checked)
  27.             {
  28.                 dataObj[element.id] ="T";
  29.             }else{
  30.                 dataObj[element.id] ="F";
  31.             }
  32.         }
  33.         else if (type == "radio")
  34.         {
  35.             if (element.checked)
  36.             {
  37.                 dataObj[element.id] = element.value;
  38.             }
  39.         }
  40.         else if (type == "hidden" || type == "password" || type == "text" ||
  41.                  type == "textarea")
  42.         {
  43.                 dataObj[element.id] = encode(element.value);
  44.         }
  45.         else if (type == "select-one" || type == "select-multiple")
  46.         {
  47.             for (var j = 0; j < element.options.length; j++)
  48.             {
  49.                 if (element.options[j].selected )
  50.                 {
  51.                     dataObj[element.id] = encode(element.options[j].value);
  52.                 }
  53.             }
  54.         }
  55.     }
  56.  
  57.     ajax.makeCall(form, dataObj);
  58. }
  59.  
  60. function escapeQuote(strVal)
  61. {
  62.     if (strVal != null)
  63.     {
  64.         if (strVal.indexOf("'") > -1 )
  65.         {
  66.             var searchStr = "'";
  67.             var replaceStr = "\'";
  68.             var re = new RegExp(searchStr, "g");
  69.             var result = strVal.replace(re, replaceStr);
  70.         }else{
  71.             var result = strVal;
  72.         }
  73.     }else{
  74.         var result = strVal;
  75.     }
  76.         return result;
  77. }
  78.  
This routine scans the form's control elements and stores the data in an associative array "dataObj" by control id, then makes the ajax call.

As you can see by the photos below the variable "queryString" contains the array "appData" (created on line 7 of the ajax routine above). This screen shots are from line 25 of the ajax code posted above. Move cursor over photo to reveal.

From the static form
[IMG]http://i1097.photobucket.com/albums/g345/ClausTSC/OkCall.jpg[/IMG]

From the dynamic form
[IMG]http://i1097.photobucket.com/albums/g345/ClausTSC/NotOkCall.jpg[/IMG]

both call the same exact server side program.
[IMGNOTHUMB]http://i1097.photobucket.com/albums/g345/ClausTSC/serverSideAppCode.gif[/IMGNOTHUMB]

Here is the result of each call. Note that from the dynamic form "appData" is missing.

This is from the static form (OK)
[IMGNOTHUMB]http://i1097.photobucket.com/albums/g345/ClausTSC/ServerSideOkCall.jpg[/IMGNOTHUMB]

This if from the dynamic form (Not OK)
[IMGNOTHUMB]http://i1097.photobucket.com/albums/g345/ClausTSC/ServerSideNotOkCall.jpg[/IMGNOTHUMB]

At this point I am not even sure whether it is the sending or the receiving that is messed up.

I use:
xP Professional
Apache v 2.2
php v 5.3
Mar 3 '11 #1

✓ answered by Claus Mygind

I finally solved the mystery and here is the explanation.

As was correctly pointed out by Dormilich
"the server canít even differentiate if the request came from a reload, form submit or AJAX, let alone if the form elements are static or not."

My problem here stemmed from 2 key errors in my code. And perhaps I still don't understand them fully.
1) I have not used the "submit" button control on my forms for years. I use a standard button so I can execute other functions as part of the form submittal process. In this case I used the <input type="submit"/>

2) This is were I really got into trouble and was the root of my looping problem. Again I normally disable the enter key from submitting the form as I want more control over the process. To prevent that, I set the forms "onsubmit" event handler like this: onSubmit="return false". In the code I have submitted in this thread I failed to include this statement.

The combination of these two errors, resulted in the form re-submitting a 2nd, 3rd time etc. until the app crashed.

Here then is the corrected code, which solved the ajax problem.

Expand|Select|Wrap|Line Numbers
  1.         td.innerHTML =    
  2.         '<form  method="POST"  action="startSmallSearch(this);" id="smallSearch" ENCTYPE="application/x-www-form-urlencoded" onSubmit="return false">'+
  3.         '<div align="center">Testing ajax on a dynamic form<br>'+
  4.         '<input type="text" id="sSearch"'+
  5.         'onkeypress="return submitViaEnter(event)"/><br>'+
  6.         'There are 3 hidden input paramters.'+
  7.         '<input type="hidden" id="p1" value="param1"/>'+
  8.         '<input type="hidden" id="p2" value="param2"/>'+
  9.         '<input type="hidden" id="p3" value="param3"/>'+
  10.         '<table><tbody id="searchBody"></tbody></table></div></form>';
  11.  
  12.         td.innerHTML =    '<input type="button" value="Test Dynamic Form" '+
  13.                             'onClick="startSmallSearch();">'+
  14.                         '<input type="button" value="Close Form" onClick="showHideScratchPad();">';
  15.  
  16.  
And since this is a simple form with one user input control, I included a method for the enter key to be activated when the user had finished keying in their request so they don't have to tab off the field or use the mouse to continue.

Notice this code in the code block above
Expand|Select|Wrap|Line Numbers
  1. <input type="text" id="sSearch"'+
  2.         'onkeypress="return submitViaEnter(event)"/>
Here is that method
Expand|Select|Wrap|Line Numbers
  1.     function submitViaEnter(evt) {
  2.         evt = (evt) ? evt : event;
  3.         var target = (evt.target) ? evt.target : evt.srcElement;
  4.         var form = target.form;
  5.         var charCode = (evt.charCode) ? evt.charCode :
  6.             ((evt.which) ? evt.which : evt.keyCode);
  7.         if (charCode == 13) {
  8.             if (validateForm(form)) {
  9.                 startSmallSearch(form);
  10.                 return false;
  11.             }
  12.         }
  13.         return true;
  14.     }
  15.  
Dormilich suggested a little dressup code on the use of style: "and another PS: instead of using .style repeatedly, you can use (for instance)"

which then looks like this:
Expand|Select|Wrap|Line Numbers
  1.     function showHideScratchPad() 
  2.     {
  3.         if (  document.getElementById("scratchPad").style.visibility == "hidden" ) {
  4.             document.getElementById("scratchPad").style.cssText = "background-color:#E4BF87;border-width:5px;border-style:ridge;border-color:orange;z-Index = '101';visibility:visible;overflow:auto;left:312px;top:167px;height:200px;width:400px";
  5.         }else{ 
  6.             document.getElementById("scratchPad").style.cssText = 
  7.             "visibility:hidden;"+
  8.             "left:0px;top:0px;height:0px;width:0px";
  9.             while (document.getElementById("sPadData").rows.length > 0) 
  10.             {
  11.                 document.getElementById("sPadData").deleteRow(0);
  12.             }
  13.         }
  14.     }
  15.  

Share this Question
Share on Google+
13 Replies


Dormilich
Expert Mod 5K+
P: 8,639
there seems to be a problem with you PHP script. did you manually check its output?

it looks like your second output is your deserialised appData object.

PS. encodeURIComponent()
Mar 3 '11 #2

Claus Mygind
100+
P: 571
well that is the crux of my problem. I was trying to deserialised the data when I ran into the problem.

As you can see from the test app I wrote with just the two lines of code, I still got two different responses on the same call.

I use firePHP to check the output. Not sure what else I can do there.
Mar 3 '11 #3

Claus Mygind
100+
P: 571
I just ran a quick dump in the php app. It simply confirms what I see with the firePHP.

array(6) { ["SEARCH"]=> string(4) "clau" ["TABLE"]=> string(13) "contactCLIENT" ["INDEX"]=> string(2) "ID" ["FieldName"]=> string(6) "Client" ["SETMODE"]=> string(3) "Yes" ["SearchMethod"]=> string(9) "StartWith" }
Mar 3 '11 #4

Claus Mygind
100+
P: 571
It appears I either have a timing issue on some other kind of looping problem.

I have attached a zip file with a calling form and a receiving app that demonstrate the problem.

You can run the static form ok. But the Dynamic form only works when you put stops in the code on the ajax call. And even then it will continue to loop.

Perhaps someone can explain this behavior to me.

test using these steps
1) enter a value in first and last and click "static Test"
2) then click open dynamic form, enter a value there then click "test dynamic"

if you have phpfire you can check it further.
Attached Files
File Type: zip testDynamicForm.zip (3.0 KB, 31 views)
Mar 3 '11 #5

Claus Mygind
100+
P: 571
Upon further testing (using the files I posted), I see the problem is in the "request.status".

A standard code should be returned 200, 400 or one of the other error codes. In fact it returns the correct data the first time but not the 200 code. Instead the code is 0 therefore it keeps looping 3 times.

I put in a counter and alert into the code and got this response readyState = 4 status = 0 loop count = 3

I am having trouble figuring out where to look next.
Mar 3 '11 #6

Dormilich
Expert Mod 5K+
P: 8,639
you could manually send the status header Ö
Mar 3 '11 #7

Claus Mygind
100+
P: 571
Hmm! Ok I will give that a shot, if I can figure out how to separate it out.

Meanwhile, I realize people may not want to open up a zip file. So I will simply post the code here to be copy and pasted instead. There must be a reason why a dynamically created form cannot get a proper response on this call.

By the way I am running this in FireFox and I need a FireFox solution:

The calling form here
Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  2.  
  3. <html>
  4.  
  5. <head>
  6.  
  7. <title>TEST</title>
  8. <script type="text/javascript">
  9. <!--
  10.     function addScratchPad(obj)
  11.     {
  12.         document.getElementById( obj.document.body.id ).innerHTML += 
  13.             '<div '+
  14.             '  id="scratchPad" '+
  15.             '  align="center" '+
  16.             '  style="position:absolute; '+
  17.             '  visibility:hidden; '+
  18.             '  z-index:99;" '+
  19.             '> '+
  20.             '    <table style="padding:0px; margin:0px;" width="100%"> '+
  21.             '        <tr><td> '+
  22.             '            <table name = "sPadTable" id = "sPadTable" align="center"> '+
  23.             '                <tbody id="sPadData" ></tbody>'+
  24.             '            </table>'+
  25.             '        </td></tr> '+
  26.             '    </table>'+
  27.             '</div>';
  28.     }
  29.  
  30.     function showHideScratchPad(cLeft,cTop,cHeight,cWidth,cBgColor,cBstyle,cBwidth,cBcolor) 
  31.     {
  32.         if (  document.getElementById("scratchPad").style.visibility == "hidden" ) {
  33.             document.getElementById("scratchPad").style.backgroundColor = ( !cBgColor ) ? "#E4BF87" : cBgColor ;
  34.             document.getElementById("scratchPad").style.borderStyle = ( !cBstyle ) ? "ridge" :cBstyle ;
  35.             document.getElementById("scratchPad").style.borderWidth = ( !cBwidth ) ? "5px" : cBwidth ;
  36.             document.getElementById("scratchPad").style.borderColor = ( !cBcolor ) ? "orange" : cBcolor;
  37.             document.getElementById("scratchPad").style.zIndex = "101";
  38.             document.getElementById("scratchPad").style.visibility = "visible";
  39.             document.getElementById("scratchPad").style.overflow = "auto";
  40.             document.getElementById("scratchPad").style.left =  cLeft;
  41.             document.getElementById("scratchPad").style.top = cTop;
  42.             document.getElementById("scratchPad").style.height = cHeight;
  43.             document.getElementById("scratchPad").style.width =  cWidth;
  44.         }else{ 
  45.             document.getElementById("scratchPad").style.visibility = "hidden";
  46.             document.getElementById("scratchPad").style.left =  "0px";
  47.             document.getElementById("scratchPad").style.top = "0px";
  48.             document.getElementById("scratchPad").style.height = "0px";
  49.             document.getElementById("scratchPad").style.width =  "0px";
  50.             while (document.getElementById("sPadData").rows.length > 0) 
  51.             {
  52.                 document.getElementById("sPadData").deleteRow(0);
  53.             }
  54.         }
  55.     }
  56.  
  57.     function displaySearchRequest(cDescriptor, cLineLength, cMaxLength, cTable, cIndex, cFieldName, cSetMode)
  58.     {
  59.  
  60.         var tr, td, th, object, cRowColor;
  61.         var tbody = document.getElementById("sPadData");
  62.         cRowColor = "#E2E2E2";
  63.  
  64.         tr = tbody.insertRow(tbody.rows.length);
  65.         td = tr.insertCell(tr.cells.length);
  66.         td.innerHTML =    '<form  method="POST"  action="startSmallSearch(this);" id="smallSearch" ENCTYPE="application/x-www-form-urlencoded">'+'<div align="center"><b>Enter '+cDescriptor+'</b><br>'+'<input type="text" maxLength='+cMaxLength+' size='+cLineLength+' id="sSearch" name="SEARCH" onkeypress="return submitViaEnter(event)"/>'+'<br>'+'<input type="hidden" id="p1" value="param1">'+'<input type="hidden" id="p2" value="param2">'+'<input type="hidden" id="p3" value="param3">'+'<table><tbody id="searchBody"></tbody></table></div></form>';
  67.  
  68.         var stbody = document.getElementById("searchBody");
  69.  
  70.         tr = stbody.insertRow(stbody.rows.length);
  71.         td = tr.insertCell(tr.cells.length);
  72.         td.setAttribute("colspan", "2");
  73.         td.setAttribute("style", "text-align:center");
  74.         td.innerHTML =    '<input type="submit" value="Test Dynamic Form" '+
  75.                             'onClick="startSmallSearch();">'+
  76.                         '<input type="button" value="Close Form" onClick="showHideScratchPad();">';
  77.  
  78.        var t=setTimeout("document.getElementById('sSearch').focus()",30);
  79.     }
  80.  
  81.     function startSmallSearch()
  82.     {
  83.         var fNode = document.getElementById("smallSearch");
  84.             fNode.action="receivingForm.php";
  85.             saveData(fNode);
  86.     }
  87.  
  88.     function smallSearch(Title, cLength, cMax, cP1, cP2, cP3){
  89.         displaySearchRequest(Title, cLength, cMax, cP1, cP2, cP3)
  90.         var _width    = 400;
  91.         var _height = 200;
  92.         var _left   = parseInt((screen.availWidth/2) - (_width/2));
  93.         var _top    = parseInt((screen.availHeight/2) - (_height/2));
  94.         showHideScratchPad(_left,(_top-100), _height, _width,'#95E3E3');    
  95.  
  96.     }
  97.  
  98.     function myAjax (form, dataObj ) {
  99.  
  100.     var    aCallBack = new Array();
  101.     var counter = 0
  102.     this.makeCall = function (form, dataObj) {
  103.  
  104.         var queryString  = "appData="+JSON.stringify(dataObj);
  105.  
  106.         var request = window.ActiveXObject ?
  107.             new ActiveXObject('Microsoft.XMLHTTP') :
  108.             new XMLHttpRequest;
  109.  
  110.             var url = form.action+'?timeStamp=' + new Date().getTime();
  111.  
  112.             request.open("POST", url, true);
  113.             request.onreadystatechange = function chkStateChange(){
  114.  
  115.         counter += 1
  116.     //alert(request.status);
  117.                                             if (request.readyState == 4) {
  118.     alert('readyState = '+request.readyState+' status = '+request.status+' loop count = '+counter);
  119.                                                 if (request.status == 200) {
  120.     //alert(request.status);
  121.                                                     processResponse(request.responseText, form);
  122. //                                                }else{
  123. //    alert('status = '+request.status);
  124.                                                 }
  125.                                             }
  126.                                          };
  127. alert(counter);
  128.             request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  129.  
  130.             request.send( queryString );
  131.     };
  132.  
  133.     var processResponse = function (form,response ) {
  134.         counter += 1
  135.         updatePage(response, counter);
  136.  
  137.     };
  138. }
  139.  
  140. function updatePage(r,cnt){
  141.     alert(r+" "+cnt);
  142. }
  143. var ajax = new myAjax();
  144.  
  145.     function saveData(form)
  146.     {
  147.         var dataObj = new Object();
  148.  
  149.         var encode = function (strVal)
  150.         {
  151.             if (strVal.indexOf('&') > -1)
  152.             {
  153.                 var searchStr = "&";
  154.                 var replaceStr = "%26";
  155.                 var re = new RegExp(searchStr, "g");
  156.                 var result = strVal.replace(re, replaceStr);
  157.             }else{
  158.                 var result = strVal;
  159.             }
  160.                 return result;
  161.         };
  162.  
  163.         for (var i = 0; i < form.elements.length; i++)
  164.         {
  165.             var element = form.elements[i];
  166.             var type = element.type;
  167.  
  168.             if (type == "checkbox")
  169.             {
  170.                 if (element.checked)
  171.                 {
  172.                     dataObj[element.id] ="T";
  173.                 }else{
  174.                     dataObj[element.id] ="F";
  175.                 }
  176.             }
  177.             else if (type == "radio")
  178.             {
  179.                 if (element.checked)
  180.                 {
  181.                     dataObj[element.id] = element.value;
  182.                 }
  183.             }
  184.             else if (type == "hidden" || type == "password" || type == "text" ||
  185.                      type == "textarea")
  186.             {
  187.                     dataObj[element.id] = encode(element.value);
  188.             }
  189.             else if (type == "select-one" || type == "select-multiple")
  190.             {
  191.                 for (var j = 0; j < element.options.length; j++)
  192.                 {
  193.                     if (element.options[j].selected )
  194.                     {
  195.                         dataObj[element.id] = encode(element.options[j].value);
  196.                     }
  197.                 }
  198.             }
  199.         }
  200.         ajax.makeCall(form, dataObj);
  201.     }
  202.     function submitViaEnter(evt) {
  203.         evt = (evt) ? evt : event;
  204.         var target = (evt.target) ? evt.target : evt.srcElement;
  205.         var form = target.form;
  206.         var charCode = (evt.charCode) ? evt.charCode :
  207.             ((evt.which) ? evt.which : evt.keyCode);
  208.         if (charCode == 13) {
  209.             if (validateForm(form)) {
  210.                 form.submit();
  211.                 return false;
  212.             }
  213.         }
  214.         return true;
  215.     }
  216.  
  217. //-->
  218. </script>
  219. </head>
  220.  
  221. <body
  222.     id = "testThis"
  223.     onload="addScratchPad(this)"
  224. >
  225.     <form 
  226.         id="testAjax"
  227.         action="receivingForm.php"
  228.         onSubmit="return false"
  229.     >
  230.         <table>
  231.             <tbody>
  232.                 <tr>
  233.                     <td colspan="4">
  234.                         <input 
  235.                             type="button" 
  236.                             onClick="saveData(this.form);"
  237.                             id="staticForm" 
  238.                             value="Test Static Form" 
  239.                         />
  240.                         <input 
  241.                             type ="button" 
  242.                             id  ="sb" 
  243.                             value="Open Dynamic form" 
  244.                             onmousedown="smallSearch('Title','10','8','param10','param11','param12');"
  245.                         />
  246.                     </td>
  247.                 </tr><tr>
  248.                     <td>First</td>
  249.                     <td>Last</td>
  250.                 </tr><tr id="contactInfo">
  251.                     <td>
  252.                         <input 
  253.                             type ="text"
  254.                             maxLength=15
  255.                             size="15"
  256.                             id  ="FIRST"
  257.                         />
  258.                     </td><td colspan="2">
  259.                         <input 
  260.                             type ="text"
  261.                             maxLength=25
  262.                             size="25"
  263.                             id  ="LAST"
  264.                         />
  265.                     </td>
  266.                 </tr>
  267.             </tbody>
  268.         </table>
  269.   </form>
  270.  </body>
  271. </html>
  272.  
And here is the receiving form NOTE make sure you call it "receivingForm.php" that is the reference that is made in the calling form.
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. /*
  3. //if you have php fire installed uncomment this section and add path to firePHP
  4.     require_once('<your path to php/FirePHP.class.php');
  5.  
  6.     // Start output buffering
  7.     ob_start();
  8.  
  9.     $firephp = FirePHP::getInstance(true);
  10.  
  11.     $firephp->log($_REQUEST, 'request =');
  12. */
  13.     echo $_REQUEST;
  14.  
  15.     foreach ( $_REQUEST as $key => $value )
  16.     {
  17.         echo $key.' = '.$value.', ';    
  18.     }
  19. ?>
Mar 4 '11 #8

Dormilich
Expert Mod 5K+
P: 8,639
There must be a reason why a dynamically created form cannot get a proper response on this call.
technically that's not true. the server can’t even differentiate if the request came from a reload, form submit or AJAX, let alone if the form elements are static or not. there must be some difference in the data being processed.

PS. if you want to see a variable’s content rather use var_dump() than echo
Mar 4 '11 #9

Claus Mygind
100+
P: 571
In theory I would agree with you, that is why I set out to create an all purpose "scratch pad", which I could manipulate to request input and display multiple results when the database query generated more than one row set.

The idea was to include the dynamic code in my javaScript library, so I could add it in without hard coding it into every page I created. So far it is not working.

Actually instead of your suggestion
"PS. if you want to see a variableís content rather use var_dump() than echo" firePHP does a much better job of displaying intermediate results (as shown in my screen shots above). Of course I do use echo to return the results to the page.

Have you tested the sample code I posted? If you do not have php installed you could respond with any other server side script you would like.

The question is still why does the server not generate the "request.status" code?

When the program is stepped through one line at the time you can clearly see the data is processed correctly the first time through. However the repeated request generated because the "if (request.status == 200)" condition is never met. In fact it stays at 0 all the time. Causes the initial data to be wiped out.

Well here is an alternative coding of the same layout, where I hard code the <div> tag and the <form> and it will properly process the data.

Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  2.  
  3. <html>
  4.  
  5. <head>
  6.  
  7. <title>TEST</title>
  8. <script type="text/javascript">
  9. <!--
  10.     function addScratchPad(obj)
  11.     {
  12. /*        document.getElementById( obj.document.body.id ).innerHTML += 
  13.              '<div '+
  14.             '  id="scratchPad" '+
  15.             '  align="center" '+
  16.             '  style="position:absolute; '+
  17.             '  visibility:hidden; '+
  18.             '  z-index:99;" '+
  19.             '> '+
  20.             '    <table style="padding:0px; margin:0px;" width="100%"> '+
  21.             '        <tr><td> '+
  22.             '            <table name = "sPadTable" id = "sPadTable" align="center"> '+
  23.             '                <tbody id="sPadData" ></tbody>'+
  24.             '            </table>'+
  25.             '        </td></tr> '+
  26.             '    </table>'+
  27.             '</div>';
  28. */    }
  29.  
  30.     function showHideScratchPad(cLeft,cTop,cHeight,cWidth,cBgColor,cBstyle,cBwidth,cBcolor) 
  31.     {
  32.         if (  document.getElementById("scratchPad").style.visibility == "hidden" ) {
  33.             document.getElementById("scratchPad").style.backgroundColor = ( !cBgColor ) ? "#E4BF87" : cBgColor ;
  34.             document.getElementById("scratchPad").style.borderStyle = ( !cBstyle ) ? "ridge" :cBstyle ;
  35.             document.getElementById("scratchPad").style.borderWidth = ( !cBwidth ) ? "5px" : cBwidth ;
  36.             document.getElementById("scratchPad").style.borderColor = ( !cBcolor ) ? "orange" : cBcolor;
  37.             document.getElementById("scratchPad").style.zIndex = "101";
  38.             document.getElementById("scratchPad").style.visibility = "visible";
  39.             document.getElementById("scratchPad").style.overflow = "auto";
  40.             document.getElementById("scratchPad").style.left =  cLeft;
  41.             document.getElementById("scratchPad").style.top = cTop;
  42.             document.getElementById("scratchPad").style.height = cHeight;
  43.             document.getElementById("scratchPad").style.width =  cWidth;
  44.         }else{ 
  45.             document.getElementById("scratchPad").style.visibility = "hidden";
  46.             document.getElementById("scratchPad").style.left =  "0px";
  47.             document.getElementById("scratchPad").style.top = "0px";
  48.             document.getElementById("scratchPad").style.height = "0px";
  49.             document.getElementById("scratchPad").style.width =  "0px";
  50.             while (document.getElementById("sPadData").rows.length > 0) 
  51.             {
  52.                 document.getElementById("sPadData").deleteRow(0);
  53.             }
  54.         }
  55.     }
  56.  
  57.     function displaySearchRequest(cDescriptor, cLineLength, cMaxLength, cTable, cIndex, cFieldName, cSetMode)
  58.     {
  59.  
  60. /*        var tr, td, th, object, cRowColor;
  61.         var tbody = document.getElementById("sPadData");
  62.         cRowColor = "#E2E2E2";
  63.  
  64.         tr = tbody.insertRow(tbody.rows.length);
  65.         td = tr.insertCell(tr.cells.length);
  66.         td.innerHTML =    '<form  method="POST"  action="startSmallSearch(this);" id="smallSearch" ENCTYPE="application/x-www-form-urlencoded">'+'<div align="center"><b>Enter '+cDescriptor+'</b><br>'+'<input type="text" maxLength='+cMaxLength+' size='+cLineLength+' id="sSearch" name="SEARCH" onkeypress="return submitViaEnter(event)"/>'+'<br>'+'<input type="hidden" id="p1" value="param1">'+'<input type="hidden" id="p2" value="param2">'+'<input type="hidden" id="p3" value="param3">'+'<table><tbody id="searchBody"></tbody></table></div></form>';
  67. */
  68.  
  69.         var stbody = document.getElementById("searchBody");
  70.  
  71.         tr = stbody.insertRow(stbody.rows.length);
  72.         td = tr.insertCell(tr.cells.length);
  73.         td.setAttribute("colspan", "2");
  74.         td.setAttribute("style", "text-align:center");
  75.         td.innerHTML =    '<input type="submit" value="Test Dynamic Form" '+
  76.                             'onClick="startSmallSearch();">'+
  77.                         '<input type="button" value="Close Form" onClick="showHideScratchPad();">';
  78.  
  79.        var t=setTimeout("document.getElementById('sSearch').focus()",30);
  80.     }
  81.  
  82.     function startSmallSearch()
  83.     {
  84.         var fNode = document.getElementById("smallSearch");
  85.             fNode.action="receivingForm.php";
  86.             saveData(fNode);
  87.     }
  88.  
  89.     function smallSearch(Title, cLength, cMax, cP1, cP2, cP3){
  90.         displaySearchRequest(Title, cLength, cMax, cP1, cP2, cP3)
  91.         var _width    = 400;
  92.         var _height = 200;
  93.         var _left   = parseInt((screen.availWidth/2) - (_width/2));
  94.         var _top    = parseInt((screen.availHeight/2) - (_height/2));
  95.         showHideScratchPad(_left,(_top-100), _height, _width,'#95E3E3');    
  96.  
  97.     }
  98.  
  99.     function myAjax (form, dataObj ) {
  100.  
  101.     var    aCallBack = new Array();
  102.     var counter = 0
  103.     this.makeCall = function (form, dataObj) {
  104.  
  105.         var queryString  = "appData="+JSON.stringify(dataObj);
  106.  
  107.         var request = window.ActiveXObject ?
  108.             new ActiveXObject('Microsoft.XMLHTTP') :
  109.             new XMLHttpRequest;
  110.  
  111.             var url = form.action+'?timeStamp=' + new Date().getTime();
  112.  
  113.             request.open("POST", url, true);
  114.             request.onreadystatechange = function chkStateChange(){
  115.  
  116.         counter += 1
  117.     //alert(request.status);
  118.                                             if (request.readyState == 4) {
  119.     alert('readyState = '+request.readyState+' status = '+request.status+' loop count = '+counter);
  120.                                                 if (request.status == 200) {
  121.     //alert(request.status);
  122.                                                     processResponse(request.responseText, form);
  123. //                                                }else{
  124. //    alert('status = '+request.status);
  125.                                                 }
  126.                                             }
  127.                                          };
  128. alert(counter);
  129.             request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  130.  
  131.             request.send( queryString );
  132.     };
  133.  
  134.     var processResponse = function (form,response ) {
  135.         counter += 1
  136.         updatePage(response, counter);
  137.  
  138.     };
  139. }
  140.  
  141. function updatePage(r,cnt){
  142.     alert(r+" "+cnt);
  143. }
  144. var ajax = new myAjax();
  145.  
  146.     function saveData(form)
  147.     {
  148.         var dataObj = new Object();
  149.  
  150.         var encode = function (strVal)
  151.         {
  152.             if (strVal.indexOf('&') > -1)
  153.             {
  154.                 var searchStr = "&";
  155.                 var replaceStr = "%26";
  156.                 var re = new RegExp(searchStr, "g");
  157.                 var result = strVal.replace(re, replaceStr);
  158.             }else{
  159.                 var result = strVal;
  160.             }
  161.                 return result;
  162.         };
  163.  
  164.         for (var i = 0; i < form.elements.length; i++)
  165.         {
  166.             var element = form.elements[i];
  167.             var type = element.type;
  168.  
  169.             if (type == "checkbox")
  170.             {
  171.                 if (element.checked)
  172.                 {
  173.                     dataObj[element.id] ="T";
  174.                 }else{
  175.                     dataObj[element.id] ="F";
  176.                 }
  177.             }
  178.             else if (type == "radio")
  179.             {
  180.                 if (element.checked)
  181.                 {
  182.                     dataObj[element.id] = element.value;
  183.                 }
  184.             }
  185.             else if (type == "hidden" || type == "password" || type == "text" ||
  186.                      type == "textarea")
  187.             {
  188.                     dataObj[element.id] = encode(element.value);
  189.             }
  190.             else if (type == "select-one" || type == "select-multiple")
  191.             {
  192.                 for (var j = 0; j < element.options.length; j++)
  193.                 {
  194.                     if (element.options[j].selected )
  195.                     {
  196.                         dataObj[element.id] = encode(element.options[j].value);
  197.                     }
  198.                 }
  199.             }
  200.         }
  201.         ajax.makeCall(form, dataObj);
  202.     }
  203.     function submitViaEnter(evt) {
  204.         evt = (evt) ? evt : event;
  205.         var target = (evt.target) ? evt.target : evt.srcElement;
  206.         var form = target.form;
  207.         var charCode = (evt.charCode) ? evt.charCode :
  208.             ((evt.which) ? evt.which : evt.keyCode);
  209.         if (charCode == 13) {
  210.             if (validateForm(form)) {
  211.                 form.submit();
  212.                 return false;
  213.             }
  214.         }
  215.         return true;
  216.     }
  217.  
  218. //-->
  219. </script>
  220. </head>
  221.  
  222. <body
  223.     id = "testThis"
  224.     onload="addScratchPad(this)"
  225. >
  226.     <form 
  227.         id="testAjax"
  228.         action="receivingForm.php"
  229.         onSubmit="return false"
  230.     >
  231.         <table>
  232.             <tbody>
  233.                 <tr>
  234.                     <td colspan="4">
  235.                         <input 
  236.                             type="button" 
  237.                             onClick="saveData(this.form);"
  238.                             id="staticForm" 
  239.                             value="Test Static Form" 
  240.                         />
  241.                         <input 
  242.                             type ="button" 
  243.                             id  ="sb" 
  244.                             value="Open Dynamic form" 
  245.                             onmousedown="smallSearch('Title','10','8','param10','param11','param12');"
  246.                         />
  247.                     </td>
  248.                 </tr><tr>
  249.                     <td>First</td>
  250.                     <td>Last</td>
  251.                 </tr><tr id="contactInfo">
  252.                     <td>
  253.                         <input 
  254.                             type ="text"
  255.                             maxLength=15
  256.                             size="15"
  257.                             id  ="FIRST"
  258.                         />
  259.                     </td><td colspan="2">
  260.                         <input 
  261.                             type ="text"
  262.                             maxLength=25
  263.                             size="25"
  264.                             id  ="LAST"
  265.                         />
  266.                     </td>
  267.                 </tr>
  268.             </tbody>
  269.         </table>
  270.   </form>
  271.     <form 
  272.         id="form2"
  273.         action="receivingForm.php"
  274.         onSubmit="return false"
  275.     >
  276.         <table>
  277.             <tbody>
  278.                 <tr>
  279.                     <td colspan="4">
  280.                         <input 
  281.                             type="button" 
  282.                             onClick="saveData(this.form);"
  283.                             id="staticForm" 
  284.                             value="Test Static Form" 
  285.                         />
  286.                         <input 
  287.                             type ="button" 
  288.                             id  ="sb" 
  289.                             value="Open Dynamic form" 
  290.                             onmousedown="smallSearch('Title','10','8','param10','param11','param12');"
  291.                         />
  292.                     </td>
  293.                 </tr><tr id="contactInfo">
  294.                     <td>
  295.                         <input 
  296.                             type ="text"
  297.                             maxLength=15
  298.                             size="15"
  299.                             id  ="FIRST"
  300.                         />
  301.                     </td>
  302.                 </tr>
  303.             </tbody>
  304.         </table>
  305.   </form>
  306. <div 
  307.       id="scratchPad" 
  308.       align="center" 
  309.       style="position:absolute; visibility:hidden; z-index:99;" 
  310.     > 
  311.         <table style="padding:0px; margin:0px;" width="100%"> 
  312.             <tr><td> 
  313.                 <table name = "sPadTable" id = "sPadTable" align="center"> 
  314.                     <tbody id="sPadData" >
  315.     <form  
  316.         method="POST"  
  317.         action="startSmallSearch(this);" 
  318.         id="smallSearch" 
  319.         ENCTYPE="application/x-www-form-urlencoded">
  320.  
  321.         <div align="center">
  322.             <span id="sTitle"></span>
  323.  
  324.             <input type="text" maxLength='+cMaxLength+' size='+cLineLength+' id="sSearch" name="SEARCH" onkeypress="return submitViaEnter(event)"/><br>
  325.  
  326.             <input type="hidden" id="p1" value="param1">
  327.             <input type="hidden" id="p2" value="param2">
  328.             <input type="hidden" id="p3" value="param3">
  329.  
  330.             <table>
  331.                 <tbody id="searchBody">
  332.                 </tbody>
  333.             </table>
  334.         </div>
  335.     </form>
  336.  
  337.  
  338.                     </tbody>
  339.                 </table>
  340.             </td></tr> 
  341.         </table>
  342. </div>
  343.   </body>
  344. </html>
  345.  
  346.  
I invite you to run both sets of code to see if you can help me further.

Thanks in advance for all your help so far.
Mar 4 '11 #10

Dormilich
Expert Mod 5K+
P: 8,639
do you have a live page where I can look at?

Actually instead of your suggestion
"PS. if you want to see a variable’s content rather use var_dump() than echo" firePHP does a much better job of displaying intermediate results (as shown in my screen shots above). Of course I do use echo to return the results to the page.
I said that mainly because of echo $_REQUEST;

and another PS: instead of using .style repeatedly, you can use (for instance)
Expand|Select|Wrap|Line Numbers
  1. elem.style.cssText = "width: 10px; height: 10px; color: navy;";
Mar 4 '11 #11

Claus Mygind
100+
P: 571
Sorry, this is just an in house (intranet) setup. We have no outside access. But if you have a server like apache setup on your computer, it is just a matter of cut and paste.

On the style comment, yes you have taught that one to me before and I do use it when writing new code. This is old code, I've had sitting around for years.

I think I will file a bug report with Mozilla and post the code there. I know exactly what is happening now, but I just don't understand why?
Mar 4 '11 #12

Claus Mygind
100+
P: 571
I finally solved the mystery and here is the explanation.

As was correctly pointed out by Dormilich
"the server canít even differentiate if the request came from a reload, form submit or AJAX, let alone if the form elements are static or not."

My problem here stemmed from 2 key errors in my code. And perhaps I still don't understand them fully.
1) I have not used the "submit" button control on my forms for years. I use a standard button so I can execute other functions as part of the form submittal process. In this case I used the <input type="submit"/>

2) This is were I really got into trouble and was the root of my looping problem. Again I normally disable the enter key from submitting the form as I want more control over the process. To prevent that, I set the forms "onsubmit" event handler like this: onSubmit="return false". In the code I have submitted in this thread I failed to include this statement.

The combination of these two errors, resulted in the form re-submitting a 2nd, 3rd time etc. until the app crashed.

Here then is the corrected code, which solved the ajax problem.

Expand|Select|Wrap|Line Numbers
  1.         td.innerHTML =    
  2.         '<form  method="POST"  action="startSmallSearch(this);" id="smallSearch" ENCTYPE="application/x-www-form-urlencoded" onSubmit="return false">'+
  3.         '<div align="center">Testing ajax on a dynamic form<br>'+
  4.         '<input type="text" id="sSearch"'+
  5.         'onkeypress="return submitViaEnter(event)"/><br>'+
  6.         'There are 3 hidden input paramters.'+
  7.         '<input type="hidden" id="p1" value="param1"/>'+
  8.         '<input type="hidden" id="p2" value="param2"/>'+
  9.         '<input type="hidden" id="p3" value="param3"/>'+
  10.         '<table><tbody id="searchBody"></tbody></table></div></form>';
  11.  
  12.         td.innerHTML =    '<input type="button" value="Test Dynamic Form" '+
  13.                             'onClick="startSmallSearch();">'+
  14.                         '<input type="button" value="Close Form" onClick="showHideScratchPad();">';
  15.  
  16.  
And since this is a simple form with one user input control, I included a method for the enter key to be activated when the user had finished keying in their request so they don't have to tab off the field or use the mouse to continue.

Notice this code in the code block above
Expand|Select|Wrap|Line Numbers
  1. <input type="text" id="sSearch"'+
  2.         'onkeypress="return submitViaEnter(event)"/>
Here is that method
Expand|Select|Wrap|Line Numbers
  1.     function submitViaEnter(evt) {
  2.         evt = (evt) ? evt : event;
  3.         var target = (evt.target) ? evt.target : evt.srcElement;
  4.         var form = target.form;
  5.         var charCode = (evt.charCode) ? evt.charCode :
  6.             ((evt.which) ? evt.which : evt.keyCode);
  7.         if (charCode == 13) {
  8.             if (validateForm(form)) {
  9.                 startSmallSearch(form);
  10.                 return false;
  11.             }
  12.         }
  13.         return true;
  14.     }
  15.  
Dormilich suggested a little dressup code on the use of style: "and another PS: instead of using .style repeatedly, you can use (for instance)"

which then looks like this:
Expand|Select|Wrap|Line Numbers
  1.     function showHideScratchPad() 
  2.     {
  3.         if (  document.getElementById("scratchPad").style.visibility == "hidden" ) {
  4.             document.getElementById("scratchPad").style.cssText = "background-color:#E4BF87;border-width:5px;border-style:ridge;border-color:orange;z-Index = '101';visibility:visible;overflow:auto;left:312px;top:167px;height:200px;width:400px";
  5.         }else{ 
  6.             document.getElementById("scratchPad").style.cssText = 
  7.             "visibility:hidden;"+
  8.             "left:0px;top:0px;height:0px;width:0px";
  9.             while (document.getElementById("sPadData").rows.length > 0) 
  10.             {
  11.                 document.getElementById("sPadData").deleteRow(0);
  12.             }
  13.         }
  14.     }
  15.  
Mar 4 '11 #13

Dormilich
Expert Mod 5K+
P: 8,639
1) I have not used the "submit" button control on my forms for years. I use a standard button so I can execute other functions as part of the form submittal process. In this case I used the <input type="submit"/>
sometimes I find it useful to use <button type="button">some text or an image</button> as it allows for more flexibility in the HTML coding


2) This is were I really got into trouble and was the root of my looping problem. Again I normally disable the enter key from submitting the form as I want more control over the process. To prevent that, I set the forms "onsubmit" event handler like this: onSubmit="return false". In the code I have submitted in this thread I failed to include this statement.
you might want to look into JavaScript event handling (that part where you donít use event attributes). it has the advantage that you canít "forget" to include an attribute (like onsubmit="return false") as all code is placed in the JavaScript directly. you also have all event code in one spot (plus you can use DOM events). the obvious disadvantage is IE, where you have non-standard implementations, but you can write a Facade to overcome this.
Mar 5 '11 #14

Post your reply

Sign in to post your reply or Sign up for a free account.