Jump to content

Recommended Posts

  • Replies 58
  • Created
  • Last Reply

Top Posters In This Topic

Top Posters In This Topic

Your getNews.php script which is called via ajax could (and should) send this data back with the rest of the news.

It does but not in the right format - it sends everything back all in one line. So the NewsID, Title, Date and Content all do get pulled from the server but its like it is in one string rather than separately. I can't separate it so I cant then edit the news story.

 

If I knew how to separate each section into its own and then display them individually into each text box I would have accomplished it.

 

Does that make sense? Is there a way I could upload a screen shot of what I mean?

 

[attachment deleted by admin]

Ah, ok now I see where your stuck. Post your getNews.php script.

:D I think I need to work on my explanation skills lol. I've added a picture for help so I can show you what I mean.

 

getNews.php

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

$query = "SELECT * FROM News WHERE NewsID = $NewsID"; 
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error()); 
	while ($row = @ mysql_fetch_array($result)) 
	{	 
		$NewsID = $row['NewsID'];
		$Title = $row['Title'];
		$Date = $row['Date'];
		$Content = $row['Content'];
		$Link = $row['Link'];
	}

echo "News ID :". $NewsID;
echo "Title :". $Title;
echo "Date :". $Date;
echo "Content :". $Content;

// close connection 
mysql_close($connection); 


?> 

 

So I can successfully retrieve all the data but I don't know then how to separate that data into different sections to put onto the different text boxes on the form - it merges into one long string.

I'm not sure exactly how AJAX works, but I read that you have trouble because the data is all in one string, so couldn't you add some characters between each piece of the news data and then explode on those characters to seperate each part of the news data?

I'm not sure exactly how AJAX works, but I read that you have trouble because the data is all in one string, so couldn't you add some characters between each piece of the news data and then explode on those characters to seperate each part of the news data?

I don't know. It is all in one string but I wouldn't know where to start in separating it. I'm hoping thats where thorpe can help lol. Im completely stuck :(

This is a javascript question.

 

if you want to have Form 1 "submit" to Form2 then you're not submitting at all.  When you submit something... the page changes, unless you alter the onSubmit function.  But you're not pushing submit after the dropdown selection, you're pushing it after the data has been retrieved (by a dropdown selection) and has been edited (if at all).  Which is why having two forms kind of cancels itself out.  Though having two forms isn't exactly necessary you can still get the job done with it.  I guess it would ...keep it organized or something.

 

something like

document.forms.getForm.mySelectionbox.onChange = function() {
     //AJAX call to getNews.php?id=mySelectedbox.value
     //Then update the HTML elements in the form (or other form)\

     //Something like
     document.forms.editForm.title = myajaxdata.title;
}

This is a javascript question.

 

if you want to have Form 1 "submit" to Form2 then you're not submitting at all.  When you submit something... the page changes, unless you alter the onSubmit function.  But you're not pushing submit after the dropdown selection, you're pushing it after the data has been retrieved (by a dropdown selection) and has been edited (if at all).  Which is why having two forms kind of cancels itself out.  Though having two forms isn't exactly necessary you can still get the job done with it.  I guess it would ...keep it organized or something.

 

something like

document.forms.getForm.mySelectionbox.onChange = function() {
     //AJAX call to getNews.php?id=mySelectedbox.value
     //Then update the HTML elements in the form (or other form)\

     //Something like
     document.forms.editForm.title = myajaxdata.title;
}

 

If I can get it done with one form then that is fine, I'm just not sure how to. I have tried looking through the tutorials on the W3Schools website and some work for me others don't. I can't get things to display using XML - just the Textproperty. I don't know enough on either AJAX or Javascript really but I am trying.

 

Anybody know of any other good tutorials out there? Basically what I am trying to do is to select an option from a drop down menu - populate the other appropriate fields which can then be editted and finally saving off the editted version of the form. It seems near impossible to do.

 

So far I can select the data and populate the form areas, but it populates the entire string rather than parts of it - this is where returning the data as xml would help but for some reason I can't get that to work either.

 

Any help please....

As Catfish mentioned, all you really need do is delimit your data (in php) by some character that you can then use to separate it (in javascript).

 

So, in getNews.php you could return your data by.....

 

echo $NewsID . '||' . $Title . '||' . $Date . '||' . $Content;

 

You can now split this data within javascript and populate your form. Something like.....

 

function stateChanged()
{
   if (xmlhttp.readyState==4)
      {
         var data = xmlhttp.responseText.split('||');
         document.forms.editForm.newsID = data[0];
         document.forms.editForm.title = data[1];
         document.forms.editForm.date = data[2];
         document.forms.editForm.content = data[3];
      }
}

As Catfish mentioned, all you really need do is delimit your data (in php) by some character that you can then use to separate it (in javascript).

 

So, in getNews.php you could return your data by.....

 

echo $NewsID . '||' . $Title . '||' . $Date . '||' . $Content;

 

You can now split this data within javascript and populate your form. Something like.....

 

function stateChanged()
{
   if (xmlhttp.readyState==4)
      {
         var data = xmlhttp.responseText.split('||');
         document.forms.editForm.newsID = data[0];
         document.forms.editForm.title = data[1];
         document.forms.editForm.date = data[2];
         document.forms.editForm.content = data[3];
      }
}

Tried that but it comes up with a response of "undefined".

What is undefined?

That is the response that I get when I click on one of the values from the drop down box and the returned data is just coming back with "undefined". I've attached a screenshot which should hopefully explain it.

 

 

 

[attachment deleted by admin]

Have you got firefug installed? What is the console output of.....

 

function stateChanged()
{
   if (xmlhttp.readyState==4)
      {
         console.log(xmlhttp.responseText);
         var data = xmlhttp.responseText.split('||');
         console.log(data);
         document.forms.editForm.newsID = data[0];
         document.forms.editForm.title = data[1];
         document.forms.editForm.date = data[2];
         document.forms.editForm.content = data[3];
      }
}

 

?

Have you got firefug installed? What is the console output of.....

 

function stateChanged()
{
   if (xmlhttp.readyState==4)
      {
         console.log(xmlhttp.responseText);
         var data = xmlhttp.responseText.split('||');
         console.log(data);
         document.forms.editForm.newsID = data[0];
         document.forms.editForm.title = data[1];
         document.forms.editForm.date = data[2];
         document.forms.editForm.content = data[3];
      }
}

 

?

The response is:

News ID :3 Title :Trust seeks a new home Date :2009-12-03 Content :<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Untitled document</title> </head> <body> <p>The Kingfisher Trust is actively seeking a new home in which it can better help support those unfortunate enough to be homeless in Bridlington. We are in the early stages of securing a new building with funding from various different sources. This will allow us to have a permanent place in which we can provide a shelter for those in most need of our help.<br /><br />We aim to be able to have regular soup kitchens and set up a new computer centre with internet access in order to help those who have no regular home a place where they can research and apply for jobs. It will also allow them to have an address that they can provide for any correspondance that is sent.<br /><br />We would like to place on record our sincere thanks for the continued help and support from the churches in Bridlington and look forward to continuing our relationship.</p> <p>Thank you,<br /><strong>The Kingfisher Trust board</strong></p> </body> </html>

["News ID :3 Title :Trust seeks a new home Date :2009-12-03 Content :<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\r\n<html>\r\n<head>\r\n<title>Untitled document</title>\r\n</head>\r\n<body>\r\n<p>The Kingfisher Trust is actively seeking a new home in which it can better help support those unfortunate enough to be homeless in Bridlington. We are in the early stages of securing a new building with funding from various different sources. This will allow us to have a permanent place in which we can provide a shelter for those in most need of our help.<br /><br />We aim to be able to have regular soup kitchens and set up a new computer centre with internet access in order to help those who have no regular home a place where they can research and apply for jobs. It will also allow them to have an address that they can provide for any correspondance that is sent.<br /><br />We would like to place on record our sincere thanks for the continued help and support from the churches in Bridlington and look forward to continuing our relationship.</p>\r\n<p>Thank you,<br /><strong>The Kingfisher Trust board</strong></p>\r\n</body>\r\n</html> "]

Seems you didn't change your php as per my example.

 

You also seem to have complete html pages within your content, this will break your form page.

I changed my php like how you suggested, the code currently looks like:

echo $NewsID.'||'.$Title.'||'.$Date.'||'. $Content;

 

and then:

	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.NewsID.value=xmlhttp.responseText;
   		    console.log(xmlhttp.responseText);
            var data = xmlhttp.responseText.split('||');
            console.log(data);
            document.retrieveddetails.NewsID.value = data[0];
            document.retrieveddetails.txtTitle.value = data[1];
            document.retrieveddetails.txtDate.value = data[2];
            document.retrieveddetails.txtContent.value = data[3];
	    //document.retrieveddetails.txtContent.value= data[3];			
	}

 

Yes there is HTML content within the content page.

The output of....

 

console.log(xmlhttp.responseText);

 

Does not reflect the changes int the php I'm afraid.

 

Can you post your current getNews.php? Also, you'll need to use htmlentities on this data or your data will break the form anyway.

 

echo $NewsID . '||' . $Title . '||' . $Date . '||' . htmlentities($Content);

The output of....

 

console.log(xmlhttp.responseText);

 

Does not reflect the changes int the php I'm afraid.

 

Can you post your current getNews.php? Also, you'll need to use htmlentities on this data or your data will break the form anyway.

 

echo $NewsID . '||' . $Title . '||' . $Date . '||' . htmlentities($Content);

 

as requested - my current getNewsTest.php

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

$query = "SELECT * FROM News WHERE NewsID = $NewsID"; 
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error()); 
	while ($row = @ mysql_fetch_array($result)) 
	{	 
		$NewsID = $row['NewsID'];
		$Title = $row['Title'];
		$Date = $row['Date'];
		$Content = $row['Content'];
		$Link = $row['Link'];
	}

echo $NewsID.'||'.htmlentities($Title).'||'.htmlentities($Date).'||'. htmlentities($Content);

// close connection 
mysql_close($connection); 


?> 

 

Thing I have done what you mean there :) Is the below code what you meant about the html entities?

echo $NewsID.'||'.htmlentities($Title).'||'.htmlentities($Date).'||'. htmlentities($Content);

I'm just going to clean that code up a little, you don't need any loop.

 

<?php
include "connection.php";
if (isset($_GET['NewsID'])) {
  $NewsID = mysql_real_escape_string($_GET['NewsID']);
  $query = "SELECT Title, `Date`, Content FROM News WHERE NewsID = $NewsID LIMIT 1"; 
  if ($result = mysql_query($query)) { 
    if (mysql_num_rows($result)) {
      $row = mysql_fetch_array($result); 
      echo $row['NewsID'] . '||' . htmlentities($row['Title']) . '||' . htmlentities($row['Date']) . '||' . htmlentities($row['Content']);
    }
  }
}
?>

 

That code (and yours actually) should be returning a || delimited string.

I'm just going to clean that code up a little, you don't need any loop.

 

<?php
include "connection.php";
if (isset($_GET['NewsID'])) {
  $NewsID = mysql_real_escape_string($_GET['NewsID']);
  $query = "SELECT Title, `Date`, Content FROM News WHERE NewsID = $NewsID LIMIT 1"; 
  if ($result = mysql_query($query)) { 
    if (mysql_num_rows($result)) {
      $row = mysql_fetch_array($result); 
      echo $row['NewsID'] . '||' . htmlentities($row['Title']) . '||' . htmlentities($row['Date']) . '||' . htmlentities($row['Content']);
    }
  }
}
?>

 

That code (and yours actually) should be returning a || delimited string.

 

I've tidied it up but still no luck. It is still coming up with the undefined error. Sorry to be a pain - I really do appreciate all the help you are giving me. You may not believe it but I am also learning quite a bit at the same time. Thanks again.

 

Any other ideas?

I'm sorry but that php code cannot produce the console output you posted. Your old.....

 

echo "News ID :". $NewsID;
echo "Title :". $Title;
echo "Date :". $Date;
echo "Content :". $Content;

 

will. Are you sure your editing the correct file?

I'm sorry but that php code cannot produce the console output you posted. Your old.....

 

echo "News ID :". $NewsID;
echo "Title :". $Title;
echo "Date :". $Date;
echo "Content :". $Content;

 

will. Are you sure your editing the correct file?

I agree with you - that does appear to be the case but I am sure I am editting the correct pages. I shall post the code below:

 

editStory3.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="selectNewsTest.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>
			<?php 
			$i = 0;
                $rssdoc = simplexml_load_file('news/updatedNewsFeed.xml');
                	foreach ($rssdoc->channel->item as $item) {
					$i++;
					  print "<b>". $item->title."</b><br>"; 
                          print $item->description."<br>"; 
                          print "<a href =".$item->link.">News Story</a><br>"; 
                          print "<br />" ;
					  if ($i >= 5)
					  break;
                   } 
                ?> 
        </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="getNewsTest.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']; ?>"/>-->
                    <input type="hidden" name="NewsID" id="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>

 

selectNewsTest.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.NewsID.value=xmlhttp.responseText;
   		    console.log(xmlhttp.responseText);
            var data = xmlhttp.responseText.split('||');
            console.log(data);
            document.retrieveddetails.NewsID.value = data[0];
            document.retrieveddetails.txtTitle.value = data[1];
            document.retrieveddetails.txtDate.value = data[2];
            document.retrieveddetails.txtContent.value = data[3];
	    //document.retrieveddetails.txtContent.value= data[3];			
	}
}

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

 

getNewsTest.php

<?php
include "connection.php";
if (isset($_GET['NewsID'])) {
  $NewsID = mysql_real_escape_string($_GET['NewsID']);
  $query = "SELECT Title, `Date`, Content FROM News WHERE NewsID = $NewsID LIMIT 1"; 
  if ($result = mysql_query($query)) { 
    if (mysql_num_rows($result)) {
      $row = mysql_fetch_array($result); 
      echo $row['NewsID'] . '||' . htmlentities($row['Title']) . '||' . htmlentities($row['Date']) . '||' . htmlentities($row['Content']);
    }
  }
}
?>

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

$query = "SELECT * FROM News WHERE NewsID = $NewsID"; 
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error()); 
	while ($row = @ mysql_fetch_array($result)) 
	{	 
		$NewsID = $row['NewsID'];
		$Title = $row['Title'];
		$Date = $row['Date'];
		$Content = $row['Content'];
		$Link = $row['Link'];
	}

echo $NewsID.'||'.htmlentities($Title).'||'.htmlentities($Date).'||'. htmlentities($Content);

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

 

The only other explanation I can possibly think of is that somewhere, somehow it is cashing the page and not using the correct one?

Actually, I didn't think of that. That can be an issue, but one that is easy fixed. Just tack a random number onto the request.

 

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+'&rand='+Math.floor(Math.random()*99);
   url=url+"&sid="+Math.random();
   xmlhttp.onreadystatechange=stateChanged;
   xmlhttp.open("GET",url,true);
   xmlhttp.send(null);
}

Actually, I didn't think of that. That can be an issue, but one that is easy fixed. Just tack a random number onto the request.

 

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+'&rand='+Math.floor(Math.random()*99);
   url=url+"&sid="+Math.random();
   xmlhttp.onreadystatechange=stateChanged;
   xmlhttp.open("GET",url,true);
   xmlhttp.send(null);
}

Tried that but unfortunately there is still no change. I've also deleted all cookies, just in case.

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.