Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

can PHP reload a div with new data? 2

Status
Not open for further replies.

jon24422531

Technical User
Jan 27, 2004
295
GB
Hi

I am very new at PHP, and foolishly I've decided to create my own blog....
So I have a database, and I can create new blog entries and then display them on my web page and so far so good. Now down the right column I will have a list of subjects etc that I want a user/reader to click to go straight to that blog entry. What I don't know is can I reload the middle column with just that blog entry or do I have to load a new page.

Jonathan

 
php does not interact with a browser. it interacts with a web server or the command line (or sometimes a GUI).

so the short answer is 'no'.

the longer answer is that javascript on the browser can interact with a web server (and thus php in turn) using ajax. you can write your script to provide data in a format that will be intelligible to your javascript receiving script.
 
You don't really need to open a new page, you could simply refresh the current page and have PHP load a blog entry based on some type of identifier.

For instance, if your blog links contain a blog entry Id in the form of a url parameter you can take that and have PHP find the relevant entry in the database and print it out when the page is refreshed.

Code:
<a href="blog.php?id=idforentry1">Blog Entry One</a>
<a href="blog.php?id=idforentry2">Blog Entry Two</a>


And simply check for an existing value to use in the GET superglobal:

Code:
if(isset($_GET['id'])){
  [green]// Take the ID and use it to retrieve the correct blog entry from the DB[/green]

}



----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
Phil

Thankyou for your help, but as I said, this is new to me and I got lost at the GET superglobal......

As I see it, when a visitor clicks on the blog link then I load every entry in the table:
Code:
<div id="Blog">
<span class="shadow">The Blog - Musings &amp; Mutterings by a Malcontent</span><p />
Hello, today is <?php echo date('l, F jS, Y'); ?>.
<?php
// Connect to the database
$database_username = 'xxxxxx';
$database_password = 'xxxxxx';
$database_host = 'xxxxxx';
$database_name = 'xxxxxx';
$connection = mysql_connect($database_host, $database_username, $database_password);
if(!$connection) { // if our attempt to connect failed
   die('Could not connect: ' . mysql_error());
}
mysql_select_db($database_name, $connection); // makes other mysql_ functions act on this database
// Query our Database
$results = mysql_query("SELECT  DATE_FORMAT( InsertDate,  '%W %D %M %Y %H:%i' ) AS InsertDate, BlogText, BLIndex, BlogHeader FROM MyBlog WHERE UserID = 'MyUser' AND BLIndex > '13' ORDER BY BLIndex DESC");
// Print out our results
echo "<table border='0'><tr><th colspan='2'>Jonathan's Blog<hr /></th></tr>";
while($row = mysql_fetch_array($results))
 {
 echo "<tr>";
 echo "<td><span class='shadowSmall'>" . $row['InsertDate'] . "</span></td>";
 echo "<td align='right'><span class='tdTextHeader'>" . str_replace("\n", "<br />",$row['BlogHeader']) . "</span></td></tr>";
 echo "<tr><td  width=450px colspan='2'><br /><br />" . str_replace("\n", "<br />",$row['BlogText']) . "<br /><br />";
 echo "Blog No." . $row['BLIndex'] . "<hr /></td>";
 echo "</tr>";
 }
echo "</table>";
// Close our connection to the database
mysql_close($connection);
?>
</div>
so are you saying that I need to create a new page similar to what I already have but with the SQL just selecting the ?id=subject

Sorry if I seem to be struggling with this, HTML and CSS are OK, but this is new.

Wait till I get to the bit where I want visitors to add their comments!

To me coding is like Shakespeare, I can read it, I can appreciate it - I can't write it.

Jonathan
 
As I see it, when a visitor clicks on the blog link then I load every entry in the table...
That's where the identifier comes in. I don't know how your table is set up. But there should be a key for each row that uniquely identifies said row.

If you construct your query to search for a particular identifier it will only return a single row, or blog entry.

I could assume that Identifier is your BLIndex, though I don't quite understand why you are limitng your results to blogs with an index greater than 13 in any case:

You don't need to construct a new page, simply modify your query to return a single result if the id parameter exists:
Code:
mysql_select_db($database_name, $connection); // makes other mysql_ functions act on this database
// Query our Database

if(isset($_GET['id'])){
$idToSearchFor=mysql_real_escape_string($_GET['id']);
$qry="SELECT  DATE_FORMAT( InsertDate,  '%W %D %M %Y %H:%i' ) AS InsertDate, BlogText, BLIndex, BlogHeader FROM MyBlog WHERE UserID = 'MyUser' AND BLIndex = $idToSearchFor ORDER BY BLIndex DESC";
}
else{
$qry="SELECT  DATE_FORMAT( InsertDate,  '%W %D %M %Y %H:%i' ) AS InsertDate, BlogText, BLIndex, BlogHeader FROM MyBlog WHERE UserID = 'MyUser' AND BLIndex > '13' ORDER BY BLIndex DESC";
}

$results = mysql_query($qry);



----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
to explain once more with a html/javascript only example:

Code:
<html>
<head><script language="JavaScript">

function pushContent(content) {
    div = document.getElementById('contentdiv');
    div.innerHTML = content;
}

</script>
</head>
<body>
<div id='contentdiv' style='width:200px;height:50px;backgroundcolor:#888;'>initial content</div>
<form method='post' action='javascript:pushContent(document.forms[0].elements["editor"].value);'>
<input name='editor' type='text' value='new content'>
<input type='submit' value='update content'>
</form>
</body>
</html>

Save as test.html and load it. Clicking the button updates the content. That doesn't mean it only works with forms. Also a button could call that javascript in it's onclick.

In the next step, of course you don't preload all blog entries you want to display into some value to push into the main content div, instead you change the javascript to request the content via php, eg:

Code:
function pushContent(contentid) {
    content = requestcontent("[URL unfurl="true"]www.yoursite.com/blogentry.php?id="+contentid)[/URL]
    div = document.getElementById('contentdiv');
    div.innerHTML = content;
}

function requestcontent(url)
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET",url,false);
xmlhttp.send();
return xmlhttp.responseXML;
}

The XMLHttpRequest is calling PHP as any normal browser request would, the responseXML is simply what the called php script returns, it doesn't need to be XML, as the name responseXML suggests, it can also be the innerHTML you put into the div.

So the blog.php script would get a parameter $_GET('id') with the blog entry id you can query from mysql and return it's html to javascript, which in turn updates the content div.

That said, it also has problems with codepages mismatches of database and html page, so you better store UTF-8 in the mysql database and set the html page to UTF-8 encoding, too.

With liegtweight html pages it's also not unusual to reload the whole page and forget about that ajax technique.

The downside of updating the current page: no change will go into the browser history. If you start a browser and load my first html sample and change the page, the browsers back button will not get active.

Bye, Olaf.
 
Phil / Olaf

Thank you very much for your input, when I get chance (in between working for a living) I shall have a shot at trying your suggestions.
Incidentally, the reason my query parameter is for BLIndex > 13 is that entries prior to that were just tests that I haven't deleted yet.

After this hurdle I want to try to allow users to add comments.... May be a step too far for me.

Jonathan
 
Phil
I tried your suggestion, but I can't seem to get it to work and I am sure I am missing something... The page loads but there is no data returned from mySQL, I have discovered with PHP that if there are any errors then the page is blank, and here that is not the case, so I think I may have missed a step.

I have added the complete page here:
Code:
<!doctype html>
<head>
<meta charset="utf-8" />
    <link href="BlogStyle.css" rel="stylesheet" type="text/css" />
    <title>The Blogging Page</title>
</head>
<?php
// Connect to the database
$database_username = 'XXXXXX';
$database_password = 'XXXXXX';
$database_host = 'XXXXXX';
$database_name = 'XXXXXX';
$connection = mysql_connect($database_host, $database_username, $database_password);
if(!$connection) { // if our attempt to connect failed
   die('Could not connect: ' . mysql_error());
}
mysql_select_db($database_name, $connection); // makes other mysql_ functions act on this database
// Query our Database
?>
<body>
<form action="BlogPage.php" method="post">
<div id="pagewidth" >
	<div id="header">
	JonSchofield.com
	</div>
	<div id="wrapper" class="clearfix">
			<div id="maincol">
			
			   <ul id="nav">
      <li><a href="About.html">About Cars</a></li>
      <li><a href="index.html">Home</a></li>
      <li><a href="FAQs.html">FAQs</a></li>
      <li><a href="Contact.html">Contact</a></li>
      <li><a href="Gallery.html">Gallery</a></li>
	  <li><a href="BlogPage.php">Blog Page</a></li>
   </ul>
<!-- Content goes below -->
<div id="rightcol">
<br />
SELECT Below:
<?php
$results2 = mysql_query("SELECT BLIndex, BlogHeader FROM JMWSBlog WHERE BLIndex > '13' ORDER BY BLIndex DESC");
echo "<table border='0' width=150px><tr><th>Topics</th></tr>";
while($row2 = mysql_fetch_array($results2))
{
echo "<tr><td align='left'><a href=BlogPage.php?id=" . $row2['BLIndex'] .">" . str_replace("\n", "<br />",$row2['BlogHeader']) . "</a></td></tr>";
}				
echo "</table>"
?>
<br />
As and when I get the time and necessary PHP skills then I 
shall add the abilty to comment on the blogs,<br />
This may take a little time, so if you are keen to pass judgement 
then please use the <a href="Contact.html">Contact Page</a>.
<br />
Many thanks<br />
Jonathan.
</div>

<div id="Blog">
<span class="shadow">The Blog - Musings &amp; Mutterings by a Malcontent</span><p />
Hello, today is <?php echo date('l, F jS, Y'); ?>.

<?php
if(isset($_GET['id'])){
$idToSearchFor=mysql_real_escape_string($_GET['id']);
$qry="SELECT  DATE_FORMAT( InsertDate,  '%W %D %M %Y %H:%i' ) AS InsertDate, BlogText, BLIndex, BlogHeader FROM MyBlog WHERE UserID = 'MyUser' AND BLIndex = $idToSearchFor ORDER BY BLIndex DESC";
}
else{
$qry="SELECT  DATE_FORMAT( InsertDate,  '%W %D %M %Y %H:%i' ) AS InsertDate, BlogText, BLIndex, BlogHeader FROM MyBlog WHERE UserID = 'MyUser' AND BLIndex > '13' ORDER BY BLIndex DESC";
}
$results = mysql_query($qry);
// OLD QUERY- $results = mysql_query("SELECT  DATE_FORMAT( InsertDate,  '%W %D %M %Y %H:%i' ) AS InsertDate, BlogText, BLIndex, BlogHeader FROM JMWSBlog WHERE UserID = 'MyUser' AND BLIndex > '13' ORDER BY BLIndex DESC");
// Print out our results		Add this to end of query to select top 1    LIMIT 0,1
echo "<table border='0'><tr><th colspan='2'>Jonathan's Blog<hr /></th></tr>";
while($row = mysql_fetch_array($results))
 {
 echo "<tr>";
 echo "<td><span class='shadowSmall'>" . $row['InsertDate'] . "</span></td>";
 echo "<td align='right'><span class='tdTextHeader'>" . str_replace("\n", "<br />",$row['BlogHeader']) . "</span></td></tr>";
 echo "<tr><td  width=450px colspan='2'><br /><br />" . str_replace("\n", "<br />",$row['BlogText']) . "<br /><br />";
 echo "Blog No." . $row['BLIndex'] . "<hr /></td>";
 echo "</tr>";
 }
echo "</table>";
// Close our connection to the database
mysql_close($connection);
?>
</div>
</div>
</div>
</form>
</body>
</html>

Jonathan
 
to debug do the following.

1. create a page called index.php with just the following on it
Code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
require_once 'index2.php';
?>

2. then rename your other file index2.php

because we _know_ that the first file is bug free, that will load fine and switch the error functionality on to high. if you added the language to the other file then often syntax and parser errors in your script will cause a silent fatal error and your page will be blank because php does not execute functions (such as the error_reporting()) before it has parsed the page.

you can also make changes in your php.ini or a local htaccess or global httpd (assuming apache).
 
Phil (Vacunita)

Schoolboy error... I am a buffoon and failed to check my query properly. Your code works perfectly, many thanks.

Have another star

When I feel ready to attempt allowing readers to add comments then I shall be back here I'm sure.

Jonathan
 
Glad I could help.

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top