0

I am completely new to Ajax and JQuery. I am trying to figure out the best way to load some results based on user click without loading a new page.

First of all, I was able to implement an ajax search function by myself on the left side of the page.

What I want to do now is load some details based on what the user clicks onto the right side of the page. This will show details about the food they select from their search.

Should I use Ajax again for this or jQuery? Can someone please show me how to do this? I would like to be able to pass the id which you can see in the html search results on my site and load it when clicked on.

Here is an example returned result from a search that a user can click on. The class is the items id

<div class="foodRow"><span class="102">APPLE JUC,CND OR BTLD,UNSWTND,W/ ADDED VIT C</span></div>

Here is my site that you can check out to see what I mean.

http://challengeyourdiet.com/dev/usda/

Here is the relevant code that I have working now.

Ajax

<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript" src="js/jquery.watermark.js"></script>

<script type="text/javascript">
$(document).ready(function() {
    function ajax_delay(str){
        setTimeout("str",2000);
    }
$("#faq_search_input").watermark("Begin Typing to Search");
$("#faq_search_input").keyup(function()
{
     var faq_search_input = $(this).val();
     var dataString = 'keyword='+ faq_search_input;   
          if(faq_search_input.length>2)
          {
              $.ajax({
              type: "GET",
              url: "ajax-search.php",
              data: dataString,
              beforeSend:  function() {
                      $('input#faq_search_input').addClass('loading');
              },
              success: function(server_response)
              {
                  window.setTimeout(function() {
                  $('#searchresultdata').html(server_response).show();
                  $('span#faq_category_title').html(faq_search_input);
                         if ($('input#faq_search_input').hasClass("loading")) {
                                $("input#faq_search_input").removeClass("loading");
                         } 
              }, 1200);
           }
});
}return false;
});
});   
</script>

HTML

  <div class="innerLeft">
     <div class="prod-subcontent">
        <div class="prod-lcol fl-left">
           <div class="prod-content">
              <div class="faqsearch">
                 <div class="faqsearchinputbox">
                    <input  name="query" type="text" id="faq_search_input" />
                  </div>
               </div>
               <div id="searchresultdata" class="faq-articles"> </div>
            </div>
         </div>
         <div class="breaker"> </div>
      </div>
  </div> <!-- end innerLeft -->
  <div class="innerRight">
  <div class="prod-subsubhead">
  <h4 class="faq_title"> <strong>Food Details For : </strong> <span id="faq_category_title">Keyword </span> </h4>
  </div>
  <div id="searchresults" class="faq-articles"> </div>
  </div> <!-- end innerRight -->
  <div class="breaker"> </div>

Thanks for any help!!

MagentoMan
  • 553
  • 4
  • 8
  • 19

1 Answers1

1

Firstly, you should 'upgrade' to a much newer version of jQuery, 1.3.2 is very old, the latest version (with old IE support) is 1.11.0.

$('#searchresultdata').on('click', '.foodRow', function(e){
    e.preventDefault();
    var articleId = $(this).find('span').attr('class');
    $('#searchresults').empty()
                       .load('/url-to-article-page.aspx?id=' +articleId+ ' #selector-to-refine-data-to-load');
})

I'll explain the answer to help you. We keep a watch for events that bubble up to the #searchresultdata that originated from a .foodRow click. If so we get the class you defined on the inner span of that element as the id to pass as a parameter, clear the current contents and attempt to call the page specified and get the HTML, and then only retrieve the part of the page that is specified by the selector. I am assuming you have a page for the articles that you would be able to browse to.

Relevant links:

Don't bother doing your if check here, and just removeClass(), if the class is not there then it will not remove it or throw an error.

if ($('input#faq_search_input').hasClass("loading")) {
    $("input#faq_search_input").removeClass("loading");
} 

Some recommendations:

  • Upgrade your jQuery library to the latest version, the above will not work without it
  • Don't use class to pass the id for your article, instead use data attributes. The result should look like <span data-id="107">...</span> and then you can use $(this).find('span').data('id');. Apaprt from which, numbers only are invalid class names.
  • Forget about the watermark plugin, instead set the placeholder attribute and use a placeholder plugin
  • I don't understand why you have the setTimeouts, the first one isn't used and the one in the AJAX succeed is simply delaying displaying your results for 1.2seconds AFTER you have received them.

Hope that helps.

Community
  • 1
  • 1
jammykam
  • 16,940
  • 2
  • 36
  • 71
  • Thank you @jammykam! This helps alot! The page I am wanting to call is results.php. (Which is in the same directory) This will grab the id using the $_GET method and then run an mysqli query that will grab the data for that food. Finally, it gets echoed to the page. I tried a simple if statement to check and see if the id is passed and echo it out. However, nothing showed up on the page. Any ideas? Shouldn't that grab the id and pass it back to this page? I am also not sure what this is doing `#selector-to-refine-data-to-load` ? P.S. I am using the data method and jquery 1.11.0 now. Thanks – MagentoMan Jan 27 '14 at 01:56
  • I also checked the console and I don't see the click function doing anything. Any advice? Thanks buddy – MagentoMan Jan 27 '14 at 02:00
  • @MagentoMan Looking at your updated page it looks like the .load() is now correct. Move the script to inside your `$(document).ready(function() {})` call. As you have it now, it executes inline, and at that point the html element is not present for it to attach to. – jammykam Jan 27 '14 at 02:12
  • Figured it out. I forgot the ever important `$(document).ready(function() {` function. To answer your other question, I have the delay set to simply slow down the result output and to allow the ajax loading wheel to show more than a fraction of a second. Thanks so much for this code!!!! – MagentoMan Jan 27 '14 at 02:15
  • Great, I thought that may be the case. Glad I could help :) You can simplify the code a little: http://pastebin.com/Gqr6mStX – jammykam Jan 27 '14 at 02:24
  • Thank you so much! I just simplified it and will look into your other suggestion about the watermark. I wished I could give you two votes up lol ;) Thanks man! – MagentoMan Jan 27 '14 at 02:31