Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Live search

Hello,

I downloaded live search code from here http://www.phpgang.com/how-to-integrate-live-search-in-php-and-mysql-with-jquery_309.html (I really hope posting a link in the forum is not a problem if so I am sorry) and i am trying to get the id of the clicked item. But i dont know how .

15 Answers

I'm not familiar with this live search but the general way you would get the id of a clicked element in jQuery would be:

var id = $(this).attr('id');

Thanks for the information but as I have little knowledge of jQuery i am still unable to get the id . when I use the code I get undefined .

Hi Krstian,

Maybe I've misunderstood the problem. Can you post what the markup looks like for one of the items in the search results? I'd like to see where the id is at that you're trying to retrieve..

And also post the code for the click handler you're using?

Here's some info on how to post code in the forums if you're not sure how to do that:
https://teamtreehouse.com/forum/posting-code-to-the-forum

This is my output file and all of my jQuery

    <?php

$content ='<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(function(){
$(".search").keyup(function() 
{ 
var searchid = $(this).val();
var dataString = \'search=\'+ searchid;
if(searchid!=\'\')
{
    $.ajax({
    type: "POST",
    url: "search.php",
    data: dataString,
    cache: false,
    success: function(html)
    {
    $("#result").html(html).show();
    }
    });
}return false;    
});

jQuery("#result").live("click",function(e){ 
    var $clicked = $(e.target);
    var $name = $clicked.find(\'.name\').html();
    var decoded = $("<div/>").html($name).text();
    $(\'#searchid\').val(decoded);
});
jQuery(document).live("click", function(e) { 
    var $clicked = $(e.target);
    if (! $clicked.hasClass("search")){
    jQuery("#result").fadeOut(); 
    }
});
$(\'#searchid\').click(function(){
    jQuery("#result").fadeIn();
});
});

</script>

<style type="text/css">
    .searchBar{
        width:500px;
        margin:0 auto;
    }
    #searchid
    {
        width:500px;
        border:solid 1px #000;
        padding:10px;
        font-size:14px;
    }
    #result
    {
        position:absolute;
        width:500px;
        padding:10px;
        display:none;
        margin-top:-1px;
        border-top:0px;
        overflow:hidden;
        border:1px #CCC solid;
        background-color: white;
    }
    .show
    {
        padding:10px; 
        border-bottom:1px #999 dashed;
        font-size:15px; 
        height:50px;
    }
    .show:hover
    {
        background:#4c66a4;
        color:#FFF;
        cursor:pointer;
    }
</style>

<div class="searchBar">
<input type="text" class="search" id="searchid" placeholder="???????" />&nbsp; &nbsp;<br /> 
<div id="result"></div>
</div>';


$pre = 1;
include("html.inc");
?>

This outputs the following result : http://imgur.com/F1IrbQl

My goal is to be able to get the id from the clicked item so I can use it somehow to output the name the image ,the information and the google maps location about the item. And make them look the same way that they look in the screenshot.

As I said I am not experienced with JQuery. So by "click handler" you mean these two functions

   jQuery("#result").live("click",function(e){ 
    var $clicked = $(e.target);
    var $name = $clicked.find(\'.name\').html();
    var decoded = $("<div/>").html($name).text();
    $(\'#searchid\').val(decoded);
});
jQuery(document).live("click", function(e) { 
    var $clicked = $(e.target);
    if (! $clicked.hasClass("search")){
    jQuery("#result").fadeOut(); 
    }
});

I still can't see where the id is that you're trying to retrieve. Have you modified "result.php" so that the search results contain an id? Or are you talking about the id that is the primary key in the database?

This is what one of the search results in the demo looks like:

div class="show" align="left">
<img style="width:50px; height:50px; float:left; margin-right:6px;" src="https://fbcdn-sphotos-e-a.akamaihd.net/hphotos-ak-prn1/27301_312848892150607_553904419_n.jpg">
<span class="name">
<strong>Neelam Ara</strong>
</span>
<br>
neelam@phpgang.com
<br>
</div>

I don't see an id anywhere in there to retrieve. Have you modified result.php so that you are outputting an id somewhere in your search result items or is that what you need help with?

I'm sorry I didn't explain it properly. the program livesearches a MySQL database and i want to get the table id of the element that is clicked. so then i can get the information about it with SELECT * FROM sights WHERE id=the id of the clicked element

Ok, so have you modified "result.php" so that it is outputting the table id into the html so that you can retrieve it when clicked?

I think that's the first thing you need to do. When you click on an item, the id needs to be somewhere in the search result so that it can be retrieved client side. Then I suppose you'll have to do another ajax request where you send that id back to your php script so that you can retrieve the page content for that clicked element.

You could possibly store it in an html5 data attribute.

Going back to the demo markup you could do something like this: (added data-id to the container div)

<div class="show" align="left" data-id="1">
<img style="width:50px; height:50px; float:left; margin-right:6px;" src="https://fbcdn-sphotos-e-a.akamaihd.net/hphotos-ak-prn1/27301_312848892150607_553904419_n.jpg">
<span class="name">
<strong>Neelam Ara</strong>
</span>
<br>
neelam@phpgang.com
<br>
</div>

Then when you click on that search result you could retrieve the id and send it back to a php script to retrieve it's content.

Yes I have modified it because i wanted to search only by name. The file looks like this.

search.php:

<?php
include('db.php');
if($_POST)
{
    $q = mysql_real_escape_string($_POST['search']);
    $strSQL_Result = mysql_query("SELECT id,name FROM obekti WHERE name LIKE '%$q%' ORDER BY id LIMIT 5");
    while($row=mysql_fetch_array($strSQL_Result))
    {
        $username   = $row['name'];
        $b_username = '<strong>'.$q.'</strong>';
        $final_username = str_ireplace($q, $b_username, $username);
        ?>
            <div class="show" align="left">
                <img src="https://fbcdn-sphotos-e-a.akamaihd.net/hphotos-ak-prn1/27301_312848892150607_553904419_n.jpg" style="width:50px; height:50px; float:left; margin-right:6px;" /><span class="name"><?php echo $final_username; ?></span>&nbsp;<br/><br/>
            </div>
        <?php
    }
}
?>

The other thing is that upon downloading the code from the website I dont have a file result.php the file is called search.php I dont think that this is a problem since the code connects to the database and outputs the items in the search bar without a problem.

Sorry, I missed that you changed your ajax request url to "search.php". I was going by what the tutorial used and it's result.php. So they made a mistake between their tutorial and the code download I think.

Anyways, see my previous comment to see one example of how you might want to output the id in that search result.

So I think you're going to want to modify your search.php to output the table id somewhere in that div. Otherwise, I don't see how you can get that table id if it doesn't exist anywhere.

Edit: I realize now the demo code is somewhat broken and this won't work. .live is also deprecated. See comment for updated answer.

Assuming you're going to store your id in a data attribute...

jQuery("#result").live("click",function(e){ 
    var $clicked = $(e.target);
    var $name = $clicked.find(\'.name\').html();
    var decoded = $("<div/>").html($name).text();
    $(\'#searchid\').val(decoded);
    var id = $clicked.data('id');
});

Once you have the id is your plan to do another ajax request for the content? google maps, content paragraph, etc...

The demo code at the link you gave is somewhat broken. Try clicking directly on the name and you'll see the search box reverts back to the placeholder text rather than showing the name in the search box. if you click anywhere else in the result area, the image, the email, or the empty space it works ok Also, as mentioned in the edit the .live method is deprecated.

I recommend that you update this click handler to the following: (also I forgot to escape the single quotes)

jQuery("#result").on("click", "div", function(e){ 
    var name = $(this).find(\'strong\').text();
    $(\'#searchid\').val(name);
    var id = $(this).data(\'id\');
});

This uses the .on method with event delegation.

I also simplified it a little bit. I think the whole point of that code is just to get the name into the search box after you click on one of them.

upon using this code I get this error:Parse error: syntax error, unexpected 'id' (T_STRING) in C:\xampp\htdocs\mapProject\output\output.php on line 30

Where line 30 is var id = $clicked.data('id');

When I have the id I plan to use php to get the data as I have much more experience with php than with ajax.

It might be that I forgot to escape the single quotes. I guess your script is one big string and so all single quotes need to be escaped.

You probably should switch over to the updated code using .on

Did you put it in the click handler?

You still need to figure out how you're getting that id back to php. Did you want to be able to click on a result and its contents would be displayed right there without a page refresh? If so, you'll probably need to submit the id as the data in an ajax request and then have your php script use that id to send back the contents for that search result.

I tried to do what you recommended but I get some strange result when i click on the item for example I have an item named asd when i type a and click on asd item it just doubles the "a" in the input box.

The code I changed is this one :

jQuery("#result").on("click", "div", function(e){ 
    var name = $(this).find(\'strong\').text();
    $(\'#searchid\').val(name);
    var id = $(this).data(\'id\');
});
jQuery(document).on("click", function(e) { 
    var $clicked = $(e.target);
    if (! $clicked.hasClass("search")){
    jQuery("#result").fadeOut(); 
    }
});

Have you looked at your output html to make sure it is what you think your php scripts are doing?

I would compare your html to the codepen and see if there are any differences. The name is inside of a strong element correct?

The codepen can't show the live search results in action but if you type a 'J' in the search box and then click on "John Doe" it seems to show the correct name in the search box and also the correct id in the alert box.

Maybe add in a few more names with different letters and see if you notice some kind of pattern.

Just to make sure we're on the right track here I did a codepen with the updated click handler. You can verify that the input field is updated with the name when clicked and the alert box shows the correct id of what was clicked. You can compare this to your own code. Although I think you have to escape all single quotes in the click handler.

http://codepen.io/anon/pen/evFJj

Is your search.php echoing the id like you see in the codepen?

At this point then you should have the correct id retrieved. You'll have to decide then how you're getting it back to the php script.

upon using this code the alert box shows "The is is undefined" .Could some previous code interfere ? Ofcourse I excluded all the ' with a backslash. I'll post the whole file so it can be easier.

    <?php

$content ='<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(function(){
$(".search").keyup(function() 
{ 
var searchid = $(this).val();
var dataString = \'search=\'+ searchid;
if(searchid!=\'\')
{
    $.ajax({
    type: "POST",
    url: "search.php",
    data: dataString,
    cache: false,
    success: function(html)
    {
    $("#result").html(html).show();
    }
    });
}return false;    
});

jQuery("#result").on("click", "div", function(e){
  var name = $(this).find(\'strong\').text();
    $(\'#searchid\').val(name);
    var id = $(this).data(\'id\');
  alert(\'The id is \' + id);

});
jQuery(document).live("click", function(e) { 
    var $clicked = $(e.target);
    if (! $clicked.hasClass("search")){
    jQuery("#result").fadeOut(); 
    }
});
$(\'#searchid\').click(function(){
    jQuery("#result").fadeIn();
});
});
</script>

<style type="text/css">
    .searchBar{
        width:500px;
        margin:0 auto;
    }
    #searchid
    {
        width:500px;
        border:solid 1px #000;
        padding:10px;
        font-size:14px;
    }
    #result
    {
        position:absolute;
        width:500px;
        padding:10px;
        display:none;
        margin-top:-1px;
        border-top:0px;
        overflow:hidden;
        border:1px #CCC solid;
        background-color: white;
    }
    .show
    {
        padding:10px; 
        border-bottom:1px #999 dashed;
        font-size:15px; 
        height:50px;
    }
    .show:hover
    {
        background:#4c66a4;
        color:#FFF;
        cursor:pointer;
    }
</style>

<div class="searchBar">
<input type="text" class="search" id="searchid" placeholder="???????" />&nbsp; &nbsp;<br /> 
<div id="result"></div>
</div>';


$pre = 1;
include("html.inc");
?>

I get an undefined message in the codepen if I remove the data-id from the result div's.

Have you updated search.php so that it is echoing the div like this:

<div class="show" align="left" data-id="1">

Except instead of '1' you would have a variable representing the current id.

I am not sure this will work for me as I see here:

<div id="result">
  <div class="show" data-id="1">
    <img src="http://www.placehold.it/75/75" alt="" />
    <span class="name"><strong>John Doe</strong></span>
  </div>
  <div class="show" data-id="2">
    <img src="http://www.placehold.it/75/75" alt="" />
    <span class="name"><strong>Jane Doe</strong></span>
  </div>
  <div class="show" data-id="3">
    <img src="http://www.placehold.it/75/75" alt="" />
    <span class="name"><strong>Blah Blah</strong></span>
  </div>
</div>

You listed the names in divs mine are in database. my div with id show will look like this:

<?php
include('db.php');
if($_POST)
{
    $q = mysql_real_escape_string($_POST['search']);
    $strSQL_Result = mysql_query("SELECT id,name FROM obekti WHERE name LIKE '%$q%' ORDER BY id LIMIT 5");
    while($row=mysql_fetch_array($strSQL_Result))
    {
        $username   = $row['name'];
        $b_username = '<strong>'.$q.'</strong>';
        $final_username = str_ireplace($q, $b_username, $username);
        ?>
            <div class="show" align="left" data-id="1">
                <img src="https://fbcdn-sphotos-e-a.akamaihd.net/hphotos-ak-prn1/27301_312848892150607_553904419_n.jpg" style="width:50px; height:50px; float:left; margin-right:6px;" /><span class="name"><?php echo $final_username; ?></span>&nbsp;<br/><br/>
            </div>
        <?php
    }
}
?>

But then it will say that id is always 1?

well, you would want to echo the id where the 1 is so it would be the id that matches that name.

I don't know anything about working with databases but inside your loop are you able to save the id to a variable like you did with the name?

Something like:

$id = $row['id'];

Then you would do something like this:

<div class="show" align="left" data-id="<?php echo $id; ?>">

This way each of your search results will have the id that corresponds to that name.

Is the name in the search box being correctly updated now? You mentioned getting a double 'a' before.

Yes I managed to assign the id to a variable in the loop and then put it in data-id attribute. The problem with the "a" stays I noticed that id doesn't double other characters which is strange. For example I put an other element in the database called "qwe".

When I type "q" the item shows and upon clicking it does not double "q" but it does not replace it with the full name.

Hmmm, maybe add another alert statement inside your click handler. To see what the name is that it's retrieving.

jQuery("#result").on("click", "div", function(e){
  var name = $(this).find('strong').text();
    $('#searchid').val(name);
    var id = $(this).data('id');
  alert('The name is ' + name  + 'and the id is ' + id);                          
});

Click on different results and see if it's reporting the name and/or the id correctly.

Have you tried inspecting the html as I mentioned earlier? That might be the easiest way to see what's wrong here.

Also, try typing 'qw' and then click on the 'qwe' name and see what shows up in the search box.

I inspected the html and I am pretty sure that it is correct.

I added Textarea and echoed $final_username to be sure.

   <?php
include('db.php');
if($_POST)
{
    $q = mysql_real_escape_string($_POST['search']);
    $strSQL_Result = mysql_query("SELECT id,name FROM obekti WHERE name LIKE '%$q%' ORDER BY id LIMIT 5");
    while($row=mysql_fetch_array($strSQL_Result))
    {
        $username   = $row['name'];
        $b_username = '<strong>'.$q.'</strong>';
        $final_username = str_ireplace($q, $b_username, $username);
        $id = $row['id'];
        ?>
        <textarea>
            <?php  echo $final_username?>
        </textarea>
            <div class="show" align="left" data-id="<?php echo $id; ?>">
                <img src="https://fbcdn-sphotos-e-a.akamaihd.net/hphotos-ak-prn1/27301_312848892150607_553904419_n.jpg" style="width:50px; height:50px; float:left; margin-right:6px;" /><span class="name"><?php echo $final_username; ?></span>&nbsp;<br/><br/>
            </div>
        <?php
    }
}
?>

I think the problem is somewhere in this line:

$final_username = str_ireplace($q, $b_username, $username);

as it does not replace the input with the full name.

When i try with qw instead of only q $final_username also changes to qw. The strange thing again is when I try with "a" before clicking on any element the textarea content is "a". After clicking however it adds again an other "a".

I'm sorry,. I misunderstood what it was doing. It's bolding the letters in the name which were typed in the search box.

I'm bringing back some of the original code in the click handler.

jQuery("#result").on("click", "div", function(e){
  var $name = $(this).find(\'.name\').html();
    var decoded = $("<div/>").html($name).text();
    $('#searchid').val(decoded);
    var id = $(this).data(\'id\');
alert(\'The id is \' + id);
});

Try this one and let me know what happens with the 'a' and the 'q'. Also, verify that the letters you're typing are bolded where they match in the results. Also, use the alert statement to verify the id is correct. Then we can go from there.

I'm sorry again, that was a big oversight on my part that caused a lot of back and forth.

This worked and all bugs are gone. Thank you a lot for the help.

I am doing this for a school project and its hard for me as it is my first project of this scale. May I ask if its possible to ask you when I have a problem or a question as you are already familiar with the code I used. And if you don't mind that (will understand if you do as i took a lot of your time) should I contact you via IM or I should post it as a response to this discussion.

Krstian Terziev

You're welcome. Glad we finally got through that.

I would recommend that you confine this discussion to the original question since it has already gotten pretty long.

I would start a new discussion when you move on to the content part. You're certainly welcome to tag me in any new discussion you start if you think I can help. I will then get an email saying I've been mentioned in a discussion.

I started this comment off by tagging you. You type the @ symbol and then start typing the person's name and you'll get a drop down list where you can select the user you want.

Let me know how the project turns out.

Edit: Comment double posted.

Forgot to mention this as we got caught up in the other stuff but the page in your screenshot might be generating a php notice error.

I was looking at the tab text for your "page.php" and it looks like the beginnings of a notice error. <br/><b>Notice:</b>...

Are you outputting the page <title> with php? It might be generating an error.

It was trying to post a variable $title as a title to the page. I just removed this part of the code as i dont need the title to be changed based on the selected element.