tags:

views:

47

answers:

5

I'm trying to use POST to pass variables to chat.php from try.htm

The code for try.htm is :

<head>
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
<script type = "text/javascript">
     function yo() {
       var text = $("#msg").val();
       $.post("chat.php",msg:text);
     }
</script>
</head>
<body>

<input type="text" id="msg" onkeyup="yo()">
<div id="display">Change</div>            
</body>

The code for chat.php is :

<?php
$msg=$_POST['msg'];
mysql_connect("localhost","root");
mysql_select_db("user");
mysql_query("INSERT INTO user (name,pwd,status) VALUES ('$msg','work','0')") or die(mysql_error());
?> 

The problem is that the 'msg' variable doesn't seem to be getting passed onto chat.php! What's wrong ?

+2  A: 

Change it to:

$.post("chat.php", { msg:text } );

jQuery expects the data to be passed as an object and { ... } will essentially create an anonymous object for us. msg:text -- without the curly braces -- unfortunately doesn't do much and will throw and error at runtime.

So putting the two together: { msg:text } creates an anonymous object with a property of msg populated with the value of your text variable.

Chris Pebble
A: 

You're doing it wrong, use a proper JSON object:

$.post("chat.php",  { msg:text });
Yuval A
It is not a JSON object. It is a plain old literal JavaScript object ;)
Felix Kling
Well, guess you're right :)
Yuval A
A: 

You forgot the curly braces round the data parameter of $.post

$.post("chat.php",{msg:text});
zwip
+1  A: 

Parameters are passed as an array:

<head>
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
<script type = "text/javascript">
     function yo() {
       var text = $("#msg").val();
       $.post("chat.php", {msg:text});
     }
</script>
</head>
<body>

<input type="text" id="msg" onkeyup="yo()">
<div id="display">Change</div>            
</body>
Marco Ceppi
A: 

thanks :) a lot!!

Anant