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 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 = 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.
CodePudding user response:
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
CodePudding user response:
Your solution is:
Change:
var product = $(this).attr('id');
To:
var product = $(this).html();