• Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.
  • The forums have been upgraded with support for dark mode. By default it will follow the setting on your system/browser. You may override it by scrolling to the end of the page and clicking the gears icon.

Undefined index

Rasputin

New Member
Joined
Feb 25, 2011
Messages
85 (0.02/day)
Location
Cumbria, United Kingdom
System Name My build
Processor AMD Llano A8-3850 APU
Motherboard Gigabyte GA-A75M-UD2H
Memory 8GB G.Skill Ripjaws 1600MHz
Storage Samsung Spinpoint 1TB
Display(s) HANNS-G HH221 1920x1080
Case Coolermaster Elite 331
Power Supply 500W
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.
Code:
<!--
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.
Code:
<?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!
 
Last edited:
HTML:
<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:

exploits_of_a_mom.png


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

I've already tried that..
 
Last edited:
Don't change it, *add* it. They're separate attributes.
 
Last edited:
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.
 
Thanks for yor help guys (:
 
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.
 
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

Code:
<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.
 
Back
Top