0

I am trying to create an AJAX filter using jQuery and PHP. When my user selects an ingredient from the dropdown I look to see in my database if a recipe exists with that ingredient and if the user created the recipe. This query works perfectly and allows me to loop through and create HTML for each recipe. I want to update the HTML via AJAX. At the moment I have this for my AJAX:

$(document).ready(function() {
    $('#filterButton').click(function(e) {
        e.preventDefault();
        // When the filter button is clicked, grab the ingredient ID and the cuisine ID
        var mainIngred = $('#sel1').val();
        var cuisine = $('#cuisine').val();
        var userID = $('#userIDHidden').val();

        var data = {
            "ingredID"  :   mainIngred,
            "tagID"     :   cuisine,
            "userID"    :   userID
        }

        var filterajaxurl = '/recipe-project/filter-ajax.php';

        $.ajax({
            url: filterajaxurl,
            type: "POST",
            data: data,
            success:function(data) {
                $("#cookbook-recipe").html(data);
            }
        });
    });
});

This is the PHP script I call, when it's called I want to replace the default data in the div with the ID cookbook-recipe with the HTML below after the PHP has looped through and got each recipe.

include_once('classes/class-database-functions.php');
$db_functions = new Database_Functions();    
$ajax_recipes = $db_functions->ajax_filter_search(23,6);    
$recipes_array = array();    
foreach ($ajax_recipes as $ajax_recipe) {
    $search_recipes = $db_functions->get_single_recipe($ajax_recipe);
    $rows = mysqli_fetch_array($search_recipes, MYSQL_ASSOC);
    array_push($recipes_array,$rows);
} ?>


    <?php
       if (isset($recipes_array) ) {
           foreach ( $recipes_array as $single_recipe ) { ?>
               <div class="col-md-4 portfolio-item">
                   <a href="single-recipe.php?id=<?php echo $single_recipe['recipe_id'];?>">
                       <?php if ( $single_recipe['recipe_image'] == '' ) { ?>
                           <img class="img-responsive" src="http://placehold.it/300x200" alt="">
                       <?php } else { ?>
                           <img class="img-responsive" src="<?php echo $single_recipe['recipe_image']; ?>" alt="">
                       <?php } ?>
                   </a>
                   <h4>
                       <a href="#">
                           <?php echo $single_recipe['recipe_name']; ?>
                       </a>
                   </h4>
               </div>
           <?php } } else { ?>
           <div class="col-md-4 portfolio-item">
               <h4>Please Add Some Recipes</h4>
           </div>
      <?php } ?>

Below is my default HTML

<button id="filterButton" class="btn btn-lg active" role="button">Filter Recipes</button>
<div id="cookbook-recipes" class="col-md-9">
           <?php
           if (isset($recipes_array) ) {
           foreach ( $recipes_array as $single_recipe ) { ?>
            <div class="col-md-4 portfolio-item">
                <a href="single-recipe.php?id=<?php echo $single_recipe['recipe_id'];?>">
                  <?php if ( $single_recipe['recipe_image'] == '' ) { ?>
                      <img class="img-responsive" src="http://placehold.it/300x200" alt="">
                  <?php } else { ?>
                    <img class="img-responsive" src="<?php echo $single_recipe['recipe_image']; ?>" alt="">
                   <?php } ?>
                </a>
                <h4>
           <a href="#">
             <?php echo $single_recipe['recipe_name']; ?>
           </a>
         </h4>
            </div>
          <?php } } else { ?>
          <div class="col-md-4 portfolio-item">
              <h4>Please Add Some Recipes</h4>
          </div>
          <?php } ?>
        </div>

However the HTML doesn't get replaced when I click the button and I get no console errors, can anyone see why?

5
  • Does the #cookbook-recipe element exist in the DOM? Have you checked the response of the request using console.log(data)? Also note that your HTML in the AJAX response will have multiple elements with the same cookbook-recipes id, which is invalid. This won't be causing your immediate problem, but it should be amended to a class. Commented Apr 1, 2016 at 15:39
  • it brings back all the data I want and yes it does exist Commented Apr 1, 2016 at 15:40
  • What type of element is #filterButton? Commented Apr 1, 2016 at 15:40
  • I have added the default HTML as now and edited my ajax HTML Commented Apr 1, 2016 at 15:44
  • 1
    Are you sure that element exists? I see $("#cookbook-recipe") but the element has id="cookbook-recipes" note the S Commented Apr 1, 2016 at 15:56

1 Answer 1

1

It may help you.

Setting all HTML in a variable and finally echoing it:

$html_reponse = "";
<?php
 if (isset($recipes_array) ) {
     foreach ( $recipes_array as $single_recipe ) {
         $html_reponse .= "<div class='col-md-4 portfolio-item'>";
             $html_reponse .= "<a href='single-recipe.php?id=".$single_recipe['recipe_id']."'>";
                 if ( $single_recipe['recipe_image'] == '' ) {
                    $html_reponse .= "<img class='img-responsive' src='http://placehold.it/300x200' alt=''>";
                 } else {
                    $html_reponse .= "<img class='img-responsive' src='".$single_recipe['recipe_image']."' alt=''>";
                 }
             $html_reponse .= "</a>";
             $html_reponse .= "<h4>";
                 $html_reponse .= "<a href='#'>".$single_recipe['recipe_name']."</a>";
             $html_reponse .= "</h4>";
         $html_reponse .= "</div>";
     }
 }else{
    $html_reponse .= "<div class='col-md-4 portfolio-item'>";
      $html_reponse .= "<h4>Please Add Some Recipes</h4>";
    $html_reponse .= "</div>";
}

echo $html_reponse;exit;

In your JS:

success:function(data) {
    // remove this alert after your testing.
    // It is just to placed that we successfully got the reponse
    alert("We got Response");
    // Just showing response in Browser console 'press F12 shortcut to open console in your browser'
    console.log(data);
    // removing existing HTML from the container and then entering new one!
    $("#cookbook-recipe").empty().html(data);
}

If it still doesn't work, you might have some problem in getting response. Make sure that it comes to your Ajax success callback event.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.