r/PHPhelp • u/MikeOnTrees • Nov 27 '12
PHP JQuery/AJAX Help
Trying to get a list from a table to be clickable to show child items next to it from another table.
I'm learning PHP at the moment and have very little knowledge of JS. Here's the code I got from another place. When I click an item in the first list nothing shows up. Anyone know what's going on?The parent ID isn't been sent on click so the sql query returns nothing.
<div id='container'>
<div id='header'>
</div>
</div>
<?php require ('./includes/connection.inc.php');
/* AJAX request */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
$query = sprintf('SELECT * FROM listitems WHERE parent=%d',
mysql_real_escape_string($_REQUEST['parent']));
$listitems = mysql_query($query)
or die(mysql_error());
printf('<h3>List %d Items</h3>', $_REQUEST['parent']);
while($info = mysql_fetch_array( $listitems ))
{
echo $info['itemName']."<br />";
}
exit;
}
/* Normal request */
?>
<div id="lists">
<h3>Lists</h3>
<?php
$lists = mysql_query("SELECT * FROM lists")
or die(mysql_error());
while($info = mysql_fetch_array( $lists ))
{
echo "<a href=\"\">".$info['listName']."</a><br />";
}
?>
</div>
<div id='listitems'>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>jQuery(function($)){
$('#lists').delegate('a', 'click', function(){
$('#listitems').load(window.location.pathname, {parent: $(this).text()});
return false;
});
}
</script>
7
Upvotes
3
u/krues8dr Nov 27 '12
Ah, where to even begin?
You're sending the text of the item you've clicked here:
But you're casting it as an integer here:
So this will always return 1 for
parent.You're also using the deprecated
mysql_functions wheremysqli_or PDO would be preferable.Never, ever, ever do things like this. Handle your errors, don't just
die()with a useless message to the user.And you probably shouldn't be
exit()ing later either. Really, this should be two scripts - one that renders the initial page, and one that gives you back the content of the ajax call. Otherwise you'll have to strip out the header from the response anyway.