PDA

View Full Version : Resolved AJAX dynamic content through links



SMartin91
06-19-2009, 04:34 AM
Okay, I have a page that lists the headline and subheadline of a story retrieved from a database in php. I am trying to get the story to be dynamically loaded when the user clicks on the headline. However, when the user clicks on the headline, nothing happens. At all. I am somewhat experienced with php but I am totally new to javascript. Backwards, I know. So needless to say, jumping right into AJAX with it is really confusing. So far, this is what I have. I would really appreciate any help you have to offer. Thanks in advance.



$query = "SELECT * FROM `May 2009` WHERE `category` = 'News' ORDER BY `id` DESC LIMIT 0 , 30";
$result= mysql_query($query) or die(mysql_error());

while ($row = mysql_fetch_row($result)){

echo "<div class=\"pad\"></div>\n";
echo "<div class=\"post\">\n";
echo "<h1 class=\"title\" onclick=\"showStory(" .$row[5]. "," .$row[0]. ")\">" . $row[3] . "</a></h1>\n";
echo "<h3 class=\"title\"><a href=\"#\">" . $row[4] . "</a></h3>\n";
echo "<div class=\"entry\" name=\"" .$row[0]. "\">";
echo "</div>";
echo "</div>";
}
?>



<script type="application/javascript">

var xmlhttp, story, id;

function showStory(story, id){

xmlhttp=GetXmlHttpObject();
if (xmlhttp==null){
alert ("Your browser does not support XMLHTTP!");
return;
}

xmlhttp.onreadystatechange=stateChanged();
}

function stateChanged(){

if (xmlhttp.readyState==4){
document.getElementsByName(id).innerHTML=story;
}
}

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

clueful
06-20-2009, 03:17 AM
var xmlhttp, story, id;

function showStory(story, id){

xmlhttp=GetXmlHttpObject();
if (xmlhttp==null){
alert ("Your browser does not support XMLHTTP!");
return;
}

xmlhttp.onreadystatechange=stateChanged();
}

function stateChanged(){

if (xmlhttp.readyState==4){
document.getElementsByName(id).innerHTML=story;
}
}
The id parameter passed to showStory isn't made visible to stateChanged. This must be generating a console error.

SMartin91
06-20-2009, 07:35 AM
Ah, I see. I did make some advancement with that help but instead, I opted for a pre-coded solution as this is only for a personal site. Thank you though, it was much appreciated :]