Home > OS >  Undefined array key when sending ID name to php variable (AJAX)
Undefined array key when sending ID name to php variable (AJAX)

Time:08-08

I have an error

Warning: Undefined array key "data" in C:\xampp\htdocs\php\recipe-container.php on line 9 ($product = $_POST["data"];)
Warning: Undefined variable $response in C:\xampp\htdocs\php\recipe-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  id="pizza">pizza</div>
<div  id="lasagna">lasagna</div>
<div  id="sushi">sushi</div>
<div >
  <?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?

CodePudding user response:

You have to send data as an object not as a variable: Inside tha ajax request :

 data:{
   data: product
 },
 processData:false,

CodePudding user response:

This is probably what you wanted to do:

data: JSON.stringify{
  data: product
})
  • Related