skip to Main Content

I have an error

Warning: Undefined array key "data" in C:xampphtdocsphprecipe-container.php on line 9 ($product = $_POST["data"];)
Warning: Undefined variable $response in C:xampphtdocsphprecipe-container.php on line 24 (echo $response;)

I’m trying to send clicked div’s ID (divs that have a "product" class) via AJAX. Div ID name seems to show up in the network tab, but it’s undefined in PHP code.

//AJAX (head HTML tag)
$(function () { 
        $('.product').on('click', function (e) {
            var product = $(this).attr('id');
            
            $.ajax({
                type: "post",
                url: 'php/recipe-container.php',
                data: product,
                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 = $_POST["data"];
    $sql = "SELECT * FROM product WHERE name = '$product'";
    $res = mysqli_query($con,$sql);

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

    $response = $name.'<br>';
    $response .= $description.'<br>';
    $response .= $date.'<br>';
    
}
echo $response;

mysqli_close($con);
}

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

?>

I tried using isset and !empty for $_POST["data"];, but it didn’t work. Right now it displays "test", but nothing else. How can I fix it?

2

Answers


  1. This is probably what you wanted to do:

    data: JSON.stringify{
      data: product
    })
    
    Login or Signup to reply.
  2. You have to send data as an object not as a variable:
    Inside tha ajax request :

     data:{
       data: product
     },
     processData:false,
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search