php - return the value of a database column from its ID
945
I try to return the value of a database column from its ID.
I want to display it in a<span>
with that ID "#name_page"
I'm sending the ID through POST "$(this).attr("id")
"
I have my AJAX call
$(document).on('click', '.update_btn', function(e){
e.preventDefault();
$.ajax({
url:"fetch_single.php",
type:"POST",
data:{
user_id: $(this).attr("id"),
},
success:function(data) {
$('#name_page').val(data.name_page);
$('#user_id').val(user_id);
}
});
Then I receive it in fetch_single.php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT name_page FROM table WHERE id = '".$_POST["user_id"]."'
LIMIT 1");
$stmt->execute();
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
But impossible to get the value back in my webpage
Answer
Solution:
Your not fetching the result, so it will be empty, jquery is also expecting json so you need to json_encode your response.
Also as your using PDO you should be using prepared queries.
For your jQuery try this: