Jump to content

Archived

This topic is now archived and is closed to further replies.

abitlikehomer

Undefined index error: Trying to pass variable to another page

Recommended Posts

The problem I have is having two seperate forms (which is necessary) that get directed to two seperate pages. I want the variable from the first form, after I have made my selection, to then be passed to the action page of the second form. If that makes sense?

 

Currently whatever I am doing isn't allowing me to correctly pass that variable through.

 

This form allows me to select which record I want to update

<form action="getNews.php" method="POST">
                    <select name="News" onchange="showNews(this.value)"><option value="" "selected">Select News article to edit</option>
					<?php
						// loop through the records
						while ($row = mysql_fetch_array($query))
						{
							echo "<option value=\"{$row['NewsID']}\">{$row['Title']}</option>";
						}							
					?>
				</select>
				</form>

 

This form allows me to then edit the content that I have selected

<form action="alterNews.php" method="POST" name="retrieveddetails">
                	<p>
                    	Title: 
                        <input name="txtTitle" type="text" id="txtTitle">
                    </p>
                	<p>
                    	Date: 
                        <input name="txtDate" type="text" id="txtDate" value="" class="calendarSelectDate" />
                  </p>
                    <p>	
                    Content: <br />    
                        <textarea name="txtContent" cols="50" rows="15" id="txtContent" ></textarea>
               	    HTML Content: <br />
                        <textarea name="txtHTMLContent" cols="50" rows="15" id="txtHTMLContent" ></textarea>
                        <input type="submit" value="Save" />
                	</p>
                </form>

 

This is the action page that the second form uses when the save button is clicked:

<?php
include "connection.php";
?>

<?php 
// (1) Declare the $NewsID variable - taken from the editStory.php page 
$NewsID = $_GET['NewsID'];

// (2) gather all details from form
$newTitle= $_POST['txtTitle'];
$newDay = substr($_POST['txtDate'],0,2);
$newMonth = substr($_POST['txtDate'],3,2);
$newYear = substr($_POST['txtDate'],6,4);
$newContent = $_POST['txtContent'];

// (3) Create an UPDATE query of the form  
$query = "UPDATE News SET Title = '$newTitle', Date = '$newYear''$newMonth''$newDay', Content = '$newContent' WHERE NewsID = '$NewsID'";

// (4) Run query through connection
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error()); 

$title = 'Title';
$date = 'Date';
$content = 'Content';

?>
<?php
	// set server access variables 
	include ("connection.php");

	// create query 
	$query = "SELECT * FROM News ORDER BY NewsID DESC"; 

	// execute query 
	$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error()); 

		// see if any rows were returned 
		if (mysql_num_rows($result) > 0) { 
			// yes 
			//Top of xml file
			$_xml = "";
				$_xml = '<?xml version="1.0"?>';
				$_xml .= '<rss version="2.0">';
				$_xml .= '<channel>';
				   $_xml .= '<title>'.'Kingfisher Trust'.'</title>';
				   $_xml .= '<description>'.'The latest news about the charity'.'</description>';
				   $_xml .= '<link>'.'http://www.2asmooth.com/Kingfisher_Trust/news/updatedNewsFeed.xml'.'</link>';
					  while($row = mysql_fetch_array($result)) {
						 $_xml .= '<item>';
							$_xml .= '<title>'.$row['Title'].'</title>';
							$_xml .= '<description>'.$row['Date'].'</description>';
							$_xml .= '<link>'.$row['Link'].'</link>';
						 $_xml .= '</item>';    
					  }
				$_xml .= '</channel>';
				$_xml .= '</rss>';

			//Output the xml string
			//print $_xml; 

			// Could also write to a file at this point	
			file_put_contents("news/updatedNewsFeed.xml", $_xml);
			// Need to give 'somedir' write permissions

		} 
		else {  // no 
			// print status message 
			echo "No rows found!"; 
		} 		

// (7) print message with ID of inserted record    
header("Location: newsReceipt.php?"."NewsID=".$NewsID);   

// ( close connection 
    mysql_close($connection);     
?>

 

Sorry to be a constaint pain. I tried keeping it to one thread but realised they were seperate topics.

Share this post


Link to post
Share on other sites

Your form uses the post method.

 

$NewsID = $_POST['NewsID'];

Share this post


Link to post
Share on other sites

Your form uses the post method.

 

$NewsID = $_POST['NewsID'];

 

Even changing it to $_POST doesn't make any difference I am afraid. I still get the same error. I really have not got a clue what I am doing wrong here.

Share this post


Link to post
Share on other sites

Your second form doesn't contain anything to pass the necessary ID along.  You've got 2 options:

 

Either append the necessary variable to the end of the form action like so:    <form action="alterNews.php?NewsId=<?php echo $_POST['News']; ?>

 

OR

 

Have a hidden field in your second form containing the news ID like so: <input type="hidden" name="NewsId" value="<?php echo $_POST['News']; ?>" />

 

 

You'd need to use $_GET to grab the first method's variable, and $_POST for the second method - the choice is yours :)

Share this post


Link to post
Share on other sites

The first method you suggested unfortunately didn't work. The second one appears to be halfway there but I still get the following error message:

 

Warning: Cannot modify header information - headers already sent by (output started at /customers/2asmooth.com/2asmooth.com/httpd.www/Kingfisher_Trust/alterNews.php:5) in /customers/2asmooth.com/2asmooth.com/httpd.www/Kingfisher_Trust/alterNews.php on line 72

 

and it still won't update the database with the updated information.

 

We're are getting somewhere though, thanks for your help so far.

Share this post


Link to post
Share on other sites

You have whitespace included within your file. Change...

 

<?php
include "connection.php";
?>

<?php

 

to....

 

<?php
include "connection.php";

 

header cannot be called after any output is sent to the client, this includes all whitespace.

Share this post


Link to post
Share on other sites

You have whitespace included within your file. Change...

 

<?php
include "connection.php";
?>

<?php

 

to....

 

<?php
include "connection.php";

 

header cannot be called after any output is sent to the client, this includes all whitespace.

 

I tried what you suggested but then I got yet another error message :'(

Warning: Header may not contain more than a single header, new line detected. in /customers/2asmooth.com/2asmooth.com/httpd.www/Kingfisher_Trust/alterNews.php on line 67

 

Now where is there a small room where I can just scream and shout lol. This is soo frustrating! Once again though, i sincerely appreciate it all.

Share this post


Link to post
Share on other sites

var_dump $NewsID and see if it contains a newline, as the header() function will not be pleased if it does!

Share this post


Link to post
Share on other sites

var_dump $NewsID and see if it contains a newline, as the header() function will not be pleased if it does!

Sorry to sound simple but can you explain what that means please? I don't really understand. Thanks. :)

Share this post


Link to post
Share on other sites
string(162) "

Notice: Undefined index: NewsID in /customers/2asmooth.com/2asmooth.com/httpd.www/Kingfisher_Trust/editStory2.php on line 98

"

Warning: Cannot modify header information - headers already sent by (output started at /customers/2asmooth.com/2asmooth.com/httpd.www/Kingfisher_Trust/alterNews.php:6) in /customers/2asmooth.com/2asmooth.com/httpd.www/Kingfisher_Trust/alterNews.php on line 71

 

That's the reply I get from the var_dump($NewsID);

Looks like it is not correctly picking up my variable that I want from my first form.

Share this post


Link to post
Share on other sites

I did an echo command on the $NewsID to see whether it was being passed from one form to another but it appears it isn't. I get the following error message:

 

NewsID :

Notice: Undefined index: NewsID in /customers/2asmooth.com/2asmooth.com/httpd.www/Kingfisher_Trust/editStory2.php on line 98

 

Looks like I am back to where I was before.

 

Anybody know if there is an easy way to select data on one form, take some of that data into another form and then pass it across? It appears like it's impossible to do :(

 

Thanks in advance.

Share this post


Link to post
Share on other sites

Post your current code.

Share this post


Link to post
Share on other sites

alterNews.php

<?php
include "connection.php";
$NewsID = $_POST['NewsID'];
echo "NewsID : ".$NewsID;

// (2) gather all details from form
$newTitle= $_POST['txtTitle'];
$newDay = substr($_POST['txtDate'],0,2);
$newMonth = substr($_POST['txtDate'],3,2);
$newYear = substr($_POST['txtDate'],6,4);
$newContent = $_POST['txtContent'];

// (3) Create an UPDATE query of the form  
$query = "UPDATE News SET Title = '$newTitle', Date = '$newYear''$newMonth''$newDay', Content = '$newContent' WHERE NewsID = '$NewsID'";

// (4) Run query through connection
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error()); 

$title = 'Title';
$date = 'Date';
$content = 'Content';

?>
<?php
      // set server access variables 
      include ("connection.php");
               
      // create query 
      $query = "SELECT * FROM News ORDER BY NewsID DESC"; 
               
      // execute query 
      $result = mysql_query($query) or die ("Error in query: $query. ".mysql_error()); 
               
         // see if any rows were returned 
         if (mysql_num_rows($result) > 0) { 
            // yes 
            //Top of xml file
            $_xml = "";
               $_xml = '<?xml version="1.0"?>';
               $_xml .= '<rss version="2.0">';
               $_xml .= '<channel>';
                  $_xml .= '<title>'.'Kingfisher Trust'.'</title>';
                  $_xml .= '<description>'.'The latest news about the charity'.'</description>';
                  $_xml .= '<link>'.'http://www.2asmooth.com/Kingfisher_Trust/news/updatedNewsFeed.xml'.'</link>';
                    while($row = mysql_fetch_array($result)) {
                      $_xml .= '<item>';
                        $_xml .= '<title>'.$row['Title'].'</title>';
                        $_xml .= '<description>'.$row['Date'].'</description>';
                        $_xml .= '<link>'.$row['Link'].'</link>';
                      $_xml .= '</item>';   
                    }
               $_xml .= '</channel>';
               $_xml .= '</rss>';
            
            //Output the xml string
            //print $_xml;
                  
            // Could also write to a file at this point   
            file_put_contents("news/updatedNewsFeed.xml", $_xml);
            // Need to give 'somedir' write permissions
                  
         }
         else {  // no
            // print status message
            echo "No rows found!";
         }       

   // (7) print message with ID of inserted record      
   header("Location: newsReceipt.php?"."NewsID=".$NewsID);

   // ( close connection
    mysql_close($connection);     
?>

 

editStory2.php

<?php
session_start();
?>
<!--
Design by 2A Smooth Ltd
http://www.2asmooth.com
-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="generator" content="HTML Tidy for Linux (vers 1 September 2005), see www.w3.org" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>The Kingfisher Trust</title>
<meta name="keywords" content="Homeless, People, Bridlington, Kingfisher, Trust" />
<meta name="description" content="The Kingfisher Trust - Helping the Homeless" />
<link href="default.css" rel="stylesheet" type="text/css"/>
<script src="calendar.js" type="text/javascript" language="javascript"></script>
<style type="text/css" media="screen,projection">
@import url(calendar.css);
</style>
<script type="text/javascript" src="selectNews.js"></script>
</head>
<body>
<!--Header Start-->
<div id="header">
<div id="menu">
	<ul>
            <li class="active"><a href="index.php" title="">Homepage</a></li>
            <li><a href="news.php" title="">News</a></li>
            <li><a href="about_us.php" title="">About Us</a></li>
            <li><a href="login.php" title="">Login</a></li>
            <li><a href="contact us.php" title="">Contact Us</a></li>
        </ul>
</div>
</div>
<!--Header End-->
<!--Content Start-->
<div id="content">
<div id="sidebarleft">
    	<div id="linksleft" class="boxed">
        	<div class="title">
            	<h2>Latest News</h2>
            </div>
            	<!--I will use this part of the page to do a dynamic link up to the database where it will display the latest news.-->
                <p> </p>
                <p>You can now register an account with us and also log in. To do so please <a href="login.php">login here</a> or 
                <a href="registration.php">register here.</a></p>
        </div>
    </div>
    <div id="main">
    	<div class="post">
        	<h2 class="title"><span>Edit News Story</span></h2>
        	<div class="intro"><img src="images/logo.jpg" alt="" width="120" height="120" class="left" />
            <p>Please select which news story you wish to edit using the drop-down box below:
			<?php
					include "connection.php"
			?>

			<?php
				//database connection				
				$query = mysql_query("SELECT * FROM News ORDER BY NewsID DESC");
			?>
				<form action="getNews.php" method="POST">
                    <select name="News" onchange="showNews(this.value)"><option value="" "selected">Select News article to edit</option>
					<?php
						// loop through the records
						while ($row = mysql_fetch_array($query))
						{
							echo "<option value=\"{$row['NewsID']}\">{$row['Title']}</option>";
						}							
					?>
				</select>
				</form>
		</p>
            	<div id="txtHint"><b>News story will appear here</b></div>
              	<br /> <br />
                <!-- OF COURSE YOU NEED TO ADAPT NEXT LINE TO YOUR tiny_mce.js PATH -->
			<script type="text/javascript" src="tinymce_3_2_7/tinymce/jscripts/tiny_mce/tiny_mce.js"></script>                
                <script type="text/javascript">
				tinyMCE.init({
				theme : "advanced",
				//mode : "textareas",
				mode : "exact",
				elements : "txtHTMLContent",
				plugins : "fullpage",
				// Theme options
				theme_advanced_buttons1 :
"save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
				theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,forecolor,backcolor",
				theme_advanced_buttons3 : "hr,removeformat,visualaid,|,sub,sup,|,charmap,",
				theme_advanced_toolbar_align : "left",
				});
			</script>

                <!-- OF COURSE YOU NEED TO ADAPT ACTION TO WHAT PAGE YOU WANT TO LOAD WHEN HITTING "SAVE" -->
	  		<form action="alterNews.php" method="POST" name="retrieveddetails">
                	<input type="hidden" name="NewsID" value="<?php $NewsID =$_POST['NewsID']; ?>" />
                    <?php echo $NewsID; ?>
                    <p>
                    	Title: 
                        <input name="txtTitle" type="text" id="txtTitle">
                    </p>
                	<p>
                    	Date: 
                        <input name="txtDate" type="text" id="txtDate" value="" class="calendarSelectDate" />
                  </p>
                    <p>	
                    Content: <br />    
                        <textarea name="txtContent" cols="50" rows="15" id="txtContent" ></textarea>
               	    HTML Content: <br />
                        <textarea name="txtHTMLContent" cols="50" rows="15" id="txtHTMLContent" ></textarea>
                        <input type="submit" value="Save" />
                	</p>
                </form>
    		</div>
    	</div>
    </div>
    <div id="calendarDiv"></div>
<div id="sidebarright">
    	<div id="linksright" class="boxed">
            <div class="title">
            <h2>Useful Links</h2>
            </div>
                <ul>
                    <li><a href="http://www.shelter.org.uk">Shelter</a><br />
                    The UK's biggest homeless charity</li>
                    <li><a href="http://www.eastriding.gov.uk/az/az_details_new?az_selected=599">Homeless form</a><br />
                    Complete this form for help and assistance from East Riding Council</li>
                    <li><a href="http://homelessuk.org/">HomelessUK</a></li>
                </ul>
            <div id="sponsorlogo"><!--<img src="images/United logo.jpg" alt="united coop logo" />--></div>
    	</div>
    </div>
</div>
<!--Content End-->
<!--Footer Start-->
<div id="footer">
    <p id="legal">Copyright © 2009 Kingfisher Trust. All Rights Reserved. Designed by <a href="http://www.2asmooth.com/">2A Smooth Ltd</a>.</p>
    <p><a href="http://validator.w3.org/check?uri=referer"><img src= "http://www.w3.org/Icons/valid-xhtml10" alt="Valid XHTML 1.0 Strict" height="31" width="88" /></a></p>
</div>
<!--Footer End-->
<div style="font-size: 0.8em; text-align: center; margin-top: 1.0em; margin-bottom: 1.0em;"><a href="http://www.2asmooth.com/">2A Smooth Ltd</a>
</div>
</body>
</html>

 

selectNews.js

var xmlhttp;

function showNews(str)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
  {
	  alert ("Browser does not support HTTP Request");
	  return;
  }
//the next couple of lines will add the information to the URL to be passed through so that the data can be retrieved.
var url="getNews.php";
url=url+"?NewsID="+str;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}

function stateChanged()
{
if (xmlhttp.readyState==4)
	{
		//this will display the data that has been returned using the div element
		document.getElementById("txtHint").innerHTML=xmlhttp.responseText;

		//this will display the data that has been returned into the textbox 
		document.retrieveddetails.txtTitle.value=xmlhttp.responseText;
		document.retrieveddetails.txtDate.value=xmlhttp.responseText;
		document.retrieveddetails.txtContent.value=xmlhttp.responseText;
	}
}

function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
  {
	  // code for IE7+, Firefox, Chrome, Opera, Safari
	  return new XMLHttpRequest();
  }
if (window.ActiveXObject)
  {
	  // code for IE6, IE5
	  return new ActiveXObject("Microsoft.XMLHTTP");
  }
return null;
}

 

Don't know what else I can do. Thanks for all your help everyone. I owe the person who solves this issue many pints or other such tipple lol.

Share this post


Link to post
Share on other sites

Which form posts to editStory2.php ?

Share this post


Link to post
Share on other sites

Which form posts to editStory2.php ?

neither - there are two form that are in editStory2.php but each form has an action that directs them to different pages but i cant use the second form until the first has been completed.

Share this post


Link to post
Share on other sites

Then this line....

 

<input type="hidden" name="NewsID" value="<?php $NewsID = $_POST['NewsID']; ?>" />

 

means nothing.

Share this post


Link to post
Share on other sites

Then this line....

 

<input type="hidden" name="NewsID" value="<?php $NewsID = $_POST['NewsID']; ?>" />

 

means nothing.

so how can i get the data from one form passed to another on the same page so i can then pass it to another page? if that makes sense...

Share this post


Link to post
Share on other sites
so how can i get the data from one form passed to another on the same page so i can then pass it to another page? if that makes sense...

 

The first form will need to submit back to itself.

Share this post


Link to post
Share on other sites

so how can i get the data from one form passed to another on the same page so i can then pass it to another page? if that makes sense...

 

The first form will need to submit back to itself.

it cant because i need to it submit to the page that it is already submitting to. Is there anyway in which i can get it to submit to two different locations at the same time?

Share this post


Link to post
Share on other sites
it cant because i need to it submit to the page that it is already submitting to. Is there anyway in which i can get it to submit to two different locations at the same time?

 

Why would the first page need to submit to the final processing page? When in reality you want to display another form in between.

 

The process is simple.

 

Form1 submits to Form2

Form2 submits to the final processing page.

Share this post


Link to post
Share on other sites

it cant because i need to it submit to the page that it is already submitting to. Is there anyway in which i can get it to submit to two different locations at the same time?

 

Why would the first page need to submit to the final processing page? When in reality you want to display another form in between.

 

The process is simple.

 

Form1 submits to Form2

Form2 submits to the final processing page.

 

Because the first form needs to first select the record from the database using a drop down menu which gets the specific record to edit. It will then display that data in the second form but at the same time it needs to pass the variable of the specific record number to the second form which can then edit the data that has been pulled from the database and update it.

 

Thats why I need two forms with two seperate locations, the first form can't just call itself because it needs to get all the record from the database and display it.

 

Does that explanation make any more sense to you at all? Sorry if it sounds confusing.

 

I have actually managed to pass the variable from the first form into the selectNews.js page which works fine but then I don't know how to retrieve that back onto the second php form in the editStory2.php page to then send across as part of the second action.

Share this post


Link to post
Share on other sites
Thats why I need two forms with two seperate locations, the first form can't just call itself because it needs to get all the record from the database and display it.

 

But you are doing that via ajax.

Share this post


Link to post
Share on other sites

Thats why I need two forms with two seperate locations, the first form can't just call itself because it needs to get all the record from the database and display it.

 

But you are doing that via ajax.

yes but in order for me to do that via ajax i need to first send it to that page therefore I can't call the page itself because I am already telling it to do the AJAX stuff. I can either use the action to do the AJAX stuff by sending it to the selectNews.js page or I can call the page itself using the action. I can't do both.

 

The only thing i can think of is to try and pass the variable into the ajax page, which i have already done and then somehow pass that back to the second form.

Share this post


Link to post
Share on other sites

I think your over complicating things. You don't really even need two forms.

 

Your form page should have a drop-down to select the news item to edit.

Once a news item has been selected an ajax call is used to get the news item and place it in a form.

The user can then edit the news and submit it.

Share this post


Link to post
Share on other sites

I think your over complicating things. You don't really even need two forms.

 

Your form page should have a drop-down to select the news item to edit.

Once a news item has been selected an ajax call is used to get the news item and place it in a form.

The user can then edit the news and submit it.

I may well be overcomplicating things and for that im sorry - im new to all this. I just don't know how I can fix it.

 

I've done the first two steps its the final step I can't get to work properly. I can edit the news but when it comes to submit it, it doesn't seem to be able to find which record it is supposed to be editting so it doesn't update the specific database record.

Share this post


Link to post
Share on other sites

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.