Anant
Anant

Reputation: 167

jQuery $.post() doubt!

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"></script>
<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 ?

Upvotes: 1

Views: 186

Answers (4)

Chris Van Opstal
Chris Van Opstal

Reputation: 37537

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.

Upvotes: 2

Marco Ceppi
Marco Ceppi

Reputation: 7702

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"></script>
<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>

Upvotes: 1

zwippie
zwippie

Reputation: 15515

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

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

Upvotes: 0

Yuval Adam
Yuval Adam

Reputation: 165182

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

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

Upvotes: 0

Related Questions