r/PHPhelp • • 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

4 comments sorted by

3

u/krues8dr Nov 27 '12

Ah, where to even begin?

You're sending the text of the item you've clicked here:

{parent: $(this).text()}

But you're casting it as an integer here:

$query = sprintf('SELECT * FROM listitems WHERE parent=%d', mysql_real_escape_string($_REQUEST['parent']));

So this will always return 1 for parent.

You're also using the deprecated mysql_ functions where mysqli_ or PDO would be preferable.

$listitems = mysql_query($query) or die(mysql_error());

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.

3

u/MikeOnTrees Nov 27 '12

Sorry about the deprecated functions and the poor code in general. I'm still learning and I'm better off writing any code at all than no code when learning, as long as I have an aspiration to write quality, clean, secure code in the long term, right?

I have been learning from an older book and just diving straight in. I'm getting way ahead of my self in trying to do this but I need to try something I want to do to stay interested rather than just the book examples.

How do I cast the the parent to the sql query properly then?

Edit.... Thanks for the help.

1

u/krues8dr Nov 27 '12

Is the parent an id? If so, assuming you have a column named "id" that it relates to:

while($info = mysql_fetch_array( $lists )) 
{  
    echo '<a href="?parent='.$info['id'].'">'.$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(e){
     e.preventDefault();
     $('#listitems').load($(this).attr('href'));
 });
}
</script>

1

u/MikeOnTrees Nov 27 '12 edited Nov 27 '12

Edit: Got it working. Copied the code below from the AJAX script in to the listitems area. Don't know if this is right but it works. Back to learning now so I can fix all the bad code in this and learn how to do it right in the first place. Thanks again for the help.

	    $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 />";
    }

Ok, that got the parent ID passing to the sql query but nothing loads in to the listitems section when a list is clicked. It changes the url but nothing displays and from what I can tell the listitems array has the data because the ID matches the list items parent number. I tested the sql query from the ajax and it pulls the items so it's not a bad parent match.

What have I dont wrong now?