AJAX聊天问题

The problem is this.I want to save every message in MySQL DB and I try to do this making this javascript function:

function doWork(str)
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// Използваните браузъри
  xmlhttp=new XMLHttpRequest();
  }
else
  {// Кой ли ползва тези версии..
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
    xmlhttp.open("GET","newmsg.php?q="+str,true);
    xmlhttp.send();
}

Then the text field :

  <div id="sender">
     Your message: <input type="text" name="msg" size="30" id="msg" />
     <button onclick="doWork(this.msg);">Send</button>
  </div>

And finally the php file:

$q=$_GET["q"];
  (str)$q;
    $db_connect = mysql_connect('localhost', 'root', 'diamond');
    if(!$db_connect)
        {
         die('Не може да се осъществи връзка с базата данни' . mysql_error());
        }
mysql_select_db("chat", $db_connect);
$sql = "INSERT INTO messages (user_id, time, text) VALUES ('1','1234','$q')";
mysql_query($sql);
mysql_close($db_connect);

And what actually happen is that the user_id and time fields are filled properly, but the 'text' filed says "undefined". What does it mean and how can I fix the problem(s)? Thanks Leron

Typecast (str) doesn't exist, it's (string). And you have to do this by assignment:

$q = (string) $q;

Actually it's pretty pointless since URL's are strings. So leave that line out.

Also, as the other repliers mentioned, that's not the right way to get the value. If you do it the following way, the button will be accessible with the return key too. With onclick the user is forced to click on the button. Add return false so that the form doesn't get submitted. this points to <form>.

<form onsubmit="alert(this.msg.value); return false">
    <p>
        <input type="text" name="msg" />
        <button type="submit">Send</button>
    </p>
</form>

I believe the issue is in your reference to the input text field. Try this instead:

<div id="sender">
   Your message: <input type="text" name="msg" size="30" id="msg" />
   <button onclick="doWork(document.getElementById('msg').value);">Send</button>
</div>

When you use the following, 'this' refers to the button element, so don't do the following.

<button onclick="doWork(this.msg);">Send</button>

doWork(document.getElementById('msg'));

this there is a button element. It has no msg property i.e. undefined, within string conversion.

Replace
<button onclick="doWork(this.msg);">Send</button> with
<button onclick="doWork(msg);">Send</button>

this.msg is the same as button.msg, which does not make sense.