April 2009

Problem: When using AJax with PHP/MySQL, where you have a Form with a TextArea field 
which allows the user to enter hard carriage returns which do not Wrap, AJax will lose the 
carriage returns when the Form is submitted because instead of being submitted as a normal 
Post, the Form is submitted via AJax as a Get. 

For instance, given a Form myform and a TextArea field mytextbox, a call to AJax can be 
constructed in Javascript as follows:

var mtext = document.myform.mytextbox.value;
var mphp  = "myprog.php?mdata=" + mtext;

The var mphp is then fed to AJax where it is executed as a Get. Thus the carriage returns in 
mtext will be lost.

Solution: All that is needed to preserve the carriage returns is to convert them to 
%0D and %0A. A carriage return is Chr(13), which converts to %0D, while a line feed is Chr(10), 
which converts to %0A.

When the PHP program myprog.php Gets the variable mdata, it will automatically convert those 
characters back to what they were originally, without any further action from you.

Here is the Javascript code again with the added step of calling a function ConvCR() to convert 
the newline characters:

var mtext = document.myform.mytextbox.value;
var mconv = ConvCR(mtext);
var mphp  = "myprog.php?mdata=" + mconv;

And here is the old-school code for the Javascript function ConvCR():

function ConvCR( mstring )
{
  var i = 0;
  var n = 0;
  var c = "";
  var s = "";

  for (i = 0; i < mstring.length; i++)
  {
    c = mstring.charAt(i);
    n = mstring.charCodeAt(i);

    if (n == 13) {c = "%0D";}
    if (n == 10) {c = "%0A";}

    s = s + c;
  }

  return s;
}

End.

a_evangelista@netzero.com