Jump to content

Problem with accessing data from server and outputting it into a textbox


abitlikehomer

Recommended Posts

Hi all

 

I am currently trying to do a page where I can edit a story that has been published to my website and stored in the database. Currently I can select the news story that I want to edit and then it outputs the returned data to a div element. The problem is when I try to do the same but display the returned data into a text box rather than a div it won't let me? Any help please guys....

 

editStory2.php

<?php
session_start();
?>
<!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");
				//$result = mysql_query($query);
			?>
				<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",
				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 method="post" name="retrieveddetails" action="alterNews.php">
                	<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" onchange="showNews()"></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>

 

alterNews.php

<?php
include "connection.php";
$NewsID=$_GET['NewsID'];
?>
<?php 

// (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()); 

?>
<?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);     
?>

 

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.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;
}

 

I am aware that at the moment I am open to SQL Injections but I shall do the security part of it after once I can actually get it to work. Thanks people :)

Link to comment
Share on other sites

There was too much information there, i couldnt read though it all and find the things i would of needed.

 

Having you tryed useing jQuery?

 

Its really simple to use and theres lots of plugins to help with things like rss feeds and such.

 

Google it.

 

it helped me so might help you.

 

Sorry i didnt answer your querstion to the full extent but an answer non-of-the-less

Paul

Link to comment
Share on other sites

Thanks for the answer anyway Paul :) it's appreciated. Erm i've had a look a jQuery but not got too far with it to be honest.

 

The main issue at the moment appears to be the line of code below:

 

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.txtContent.value=xmlhttp.responseText;
      }

 

The first bit will display the data using a div tag but the second part - using a textbox won't work. I don't know why and what I am doing wrong.

 

Thanks anyway though for the advice :)

Link to comment
Share on other sites

with textarea's you don't use .value you use .innerHTML

 

<textarea value="This doesn't exist" />
<textarea>This does exist</textarea>

 

Unfortunately that still doesn't work. I have changed it to .innerHTML but no look :( - still works using the div but not textbox or textarea. Thank you for the help anyway though :)

Link to comment
Share on other sites

I got it to work but I don't know how.

 

I do however now have a problem when it comes to actually editting the content. When I try to edit it and click save I get the following error message:

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

 

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

 

I know what the error message is - it is telling me that for some reason the NewsID variable isn't being passed to the alterNews.php page - but my question is why not? What am I doing thats wrong because as far as I can tell it should be picking it up and passing it through.

 

Thanks guys once again for any help I receive. Code is above, not altered.

Link to comment
Share on other sites

take a look at this line

 

header("Location: newsReceipt.php?"."NewsID=".$NewsID);   

 

$NewsID has not be declared yet.

 

I thought it was. Is the line below not declaring it?

$NewsID=$_GET['NewsID'];

 

Sorry you need to do something like this at the beginning of the document instead of that

 

if(isset($_GET['NewsID'])) {
   $NewsID = $_GET['NewsID'];
}
else {
   $NewsID = '1' // Put a default number here
}

 

You need to do that so that if NewsID isn't pass you wont throw errors up, and are you sure that NewsID is getting passed to the page?

Link to comment
Share on other sites

Im not sure that NewsID is getting passed to the page, but I can't work out why it wouldn't do because as far as I know I have done everything that I can think of correctly. I'm using the POST command for it but I don't know what's going wrong with it.

 

I'm selecting the option from a table so I can't just put an else if statement because that would throw out the ability to edit my news story, unfortunately.

 

Any other ideas?

Link to comment
Share on other sites

Sorry I have created another topic http://www.phpfreaks.com/forums/index.php/topic,283363.0.html - as I thought that as my original solution was sorted I should keep the two seperate.

 

However in answer to your question although it should look like that, it doesn't. It still pulls all the necessary data but the URL doesn't change at all. Maybe because of the AJAX that I am also using.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.