I'm trying to make an AJAX request to fetch some data from the database but the only thing returned is the name of the column. Can somebody explain why? Here is my code:
=> Table Name :- tblstudents
id = 0
fname = john
lname = doe
tel = 555-564-1585
id = 1
fname = paul
lname = smith
tel = 555-134-5644
id = 2
fname = laura
lname = mcdo
tel = 555-465-7512
=> AJAX method:
function fetchFromDBPHP(column, fname, id, tel) {
$.ajax({
type: "post",
url: "./php/fetchFromDB.php",
dataType: 'json',
data: { column: column, fname: fname, id: id },
success: function(data) {
localStorage.setItem(tel, data);
},
error:function(request, status, error) {
console.log("** Error from fetchFromDBPHP **");
console.log("Error: " + error + "
Message: " + request.responseText);
}
});
}
=> Javascript :
fetchFromDBPHP(column, fname, id, "one");
var result = localStorage.getItem("one");
console.log("Result: " + result);
=> PHP :
<?php
$column = $_POST['column'];
$fname = $_POST['fname'];
$id = $_POST['id'];
if (isset($column)) {
$sql = "SELECT '$column' FROM tblstudents WHERE fname = '$fname' AND id = '" . intval($id) . "'";
$con = mysqli_connect("localhost", "root", "", "test");
if (!$con) {
die("Connection failed: " . mysqli_error($con));
}
$result = mysqli_query($con, $sql);
$to_encode = array();
while($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
$to_encode[] = $row;
}
echo json_encode($to_encode);
mysqli_close($con);
}
?>
As you might know, column
, fname
and id
have values in the Javascript code. As my database is way longer, I tried to be as much close as possible to my real code. The only thing is, the result of the AJAX request gives me a JSON object result containing the name of the column, and not its content.
Anybody can help? Thanks in advance :)