skip to Main Content

I’m using AJAX to transport id name of my div to use it as a string in a query. The problem is that it does not want to display any content related to the database (it can display a normal text echo from my function).

// head HTML (AJAX)
$(function () { 
        $('.product').on('click', function (e) {
            var product = $(this).attr('id');
            
            $.ajax({
                type: "post",
                url: 'php/recipe-container.php',
                data: JSON.stringify({
                    data: product,
                }),
                processData:false,
                processData:false,
                contentType: false,
                success: function(response) {
                    $(".display_recipe").html(response);
                }
            });
        });
});
//HTML
<div class="product" id="pizza">pizza</div>
<div class="product" id="lasagna">lasagna</div>
<div class="product" id="sushi">sushi</div>
<div class="display_recipe">
  <?php
    require "php/recipe-container.php";
  ?>
</div>
//PHP (recipe-container.php)
<?php

function display(){
    $con = mysqli_connect("localhost", "root", "", "cookbook");
    echo "test ";
    $product = substr(file_get_contents("php://input"), 9, -2);
    
    $sql = "SELECT * FROM product WHERE name = '$product'";
    $res = mysqli_query($con,$sql);

    while($row = mysqli_fetch_assoc($res)) {
        echo "test2 ";
        $name = $row['name'];
        $description = $row['description'];
        $date = $row['date'];

        echo $name;
        echo $description;
        echo $date;
    }

mysqli_close($con);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST'){ 
    display(); 
}

?>

This is what I see after the button click – "test test2 pizza". "pizza" is the ID name, not the actual name from the database. I don’t know how to remove that. I know everything has something to do with the "success" function (response), but I have no idea how to fix that.

2

Answers


  1. Your solution is:

    Change:

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

    To:

    var product = $(this).html();
    
    Login or Signup to reply.
  2. you have to make an array in php before while loop as:

    $data = [];
    while($row = mysqli_fetch_assoc($res)){
    
        $data['name'] = $row['name'];
        $data['description'] = $row['description'];
    }
    return $data;
    // return json_encode($data);
    exit();
    

    I hope this works fine for you. Now you just have to pass json format in your ajax request and decode and then it works fine for you

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search