# Undefined index



## Rasputin (Feb 7, 2012)

So i'm making a browser based instant messenger using javascript and PHP. 

There is a form on the page which sends the message to a MySQL database using the POST method.

Upon loading the page to write messages, the user is prompted to enter a username which is then held in a js variable. Now I figured out that you can't transfer the contents of a js var to a PHP var, so instead I have been trying to have the page write the value of the username var to a hidden textbox on the form.

I can make the js write the value of "nickname" to the textbox, but when I submit the form: "Undefined index: nickname in C:\wamp\www\new\insert.php on line 11".

I don't understand this though: the column is part of the mysql table it adds the data to, it was not doing before I worked out how to add the value of the variable to the text field on the form.

This is the "Chat.php" that the form is on.

```
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" href="style.css" type="text/css" />
        <title></title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
        <script type="text/javascript">
    
        // ask user for name with popup prompt   
        function setNick(){                 

        var nickname = prompt("Enter your chat name:", "Guest");       
        document.getElementById("nick").value = nickname;
        
        return false;
        
        }
    	</script>
    </head>
    <body onLoad="setNick();">
        <div id="chat-wrap">
        <div id="chat-area"></div>
            <form name="send" action="insert.php" method="POST">
                <input type="text" name="txtInput" value="Enter message..." size="50" />
                <input type="text" id="nick" readonly="readonly" />
                <input type="submit" value="Submit" name="btnSubmit" />

            </form>
        </div>
    </body>
</html>
```

This is the insert.php which adds the data to the table.

```
<?php

$con = mysql_connect("localhost","********","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("chat1", $con);

$sql="INSERT INTO msg (name, message)VALUES('$_POST[nick]','$_POST[txtInput]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";

mysql_close($con)

?>
```

If you need any more information, just ask.

Thank you for any help, fellow TPU members!


----------



## Disparia (Feb 7, 2012)

```
<input type="text" id="nick" readonly="readonly" />
```

GET/POST variable names come from the name attribute. Add name="nick" to the element.

Also, you might want to sanitize your input. Even if this is a learning exercise, get into the habit of doing it. The why:


----------



## Rasputin (Feb 7, 2012)

If I change id to name, the getElementById stops working.

I've already tried that..


----------



## Disparia (Feb 7, 2012)

Don't change it, *add* it. They're separate attributes.


----------



## digibucc (Feb 7, 2012)

just as you have id="nick" add name="nick"
love the comic jizzler 

you mostly, only need the id attribute when you need to apply styling to something outside of a class of similar objects. so if you have 11 textboxes, and all but one are styled one way, you could give the 11th an id to call it separately from the others in your css. it's not a bad habit to always have an id, but the more important tag is the name - every input has to have a name.


----------



## Rasputin (Feb 7, 2012)

Thanks for yor help guys


----------



## Rasputin (Feb 8, 2012)

Any tips on how to submit the form without leaving the page? E.g. press submit, and the PHP page is processed in the background while the user stays on the page with the form.

I've been trying AJAX but it just doesnt want to work.


----------



## xbonez (Feb 9, 2012)

If you don't want to leave the page, you will have to make an asynchronous request, i.e. AJAX. You can go the hard way and do it manually by not using any framework- this would require you to detect the user's browser and accordingly create an XHR object, or ActiveX object etc.

Or, do it the smart way - use Jquery.

Your front-end code should look like this


```
<head>
	<!-- your usual stuff here + Jquery -->
	 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>	 
	 <script type="text/javascript">
		$(document).ready(function(){
				$('#yourform').submit(function(){
					$.ajax({
						url : "insert.php",
						method : "post",
						data : {name : $('#nick').val(), txtInput : $('#txtInput').val()},
						success : function(data){
							console.log('Message has been posted');
						}
				});
			});
		});
	 </script>
</head>
```

However, rather than sending the nickname everytime a message is set, I would recommend that as soon as the user enters his name, you  send an AJAX request to a script that sets the nick as a SESSION variable, possibly even a cookie if you want to remember the user across sessions. Then, everytime the user posts a message, you look up the name from the session variable.

Also, get very comfortable with Jquery, because you cannot make a chat application without Ajax. Receiving messages will have to be implemented using an AJAX listener. The common way to do this is to use XHR Long Polling. This works by making sure there is always an outstanding Ajax request listening to the server for incoming messages.


----------

