I am working on a project that uses JavaScript (AJax) to call a php file to query a MySQL Server. I have traced the call to php and see that it is working but the AJax call never gets anything. below is my JavaScript and PHP code, could someone look at it and tell me what I am missing.
javaScript:
$(function() {
$('#members').on('input', function() {
var opt = $('option[value="'+$(this).val()+'"]');
/*getMember(opt.length ? opt.attr('id'): 0);*/
$.ajax({
url: 'data/members.php',
type: 'POST',
data: {'action':'get', 'status':opt.attr('id')},
sucess: function(data) {
alert(data);
},
error: function() {
alert("We have a problem");
}
});
});
});
php:
$action = $_POST["action"];
if ($action == "get") {
$memberID = $_POST["status"];
try {
require "../../classes/data.php";
$data = new data();
$conn = $data->connect();
$sql = "SELECT * FROM members WHERE memberID = " . $memberID;
$result = $data->query($sql);
while($row = $result->fetch_assoc()) {
$returnData = $row;
}
echo $returnData;
} catch (Exception $ex) {
}
}
You have a syntax error:
Replace:
url: 'data/members.php';
for this:
url: 'data/members.php',
',' at the end
PHP part
// You have SQL injection here
$sql = "SELECT * FROM members WHERE memberID = " . $memberID;
$result = $data->query($sql);
while($row = $result->fetch_assoc()) {
// You probably want this as array
$returnData = $row;
}
// use json_encode
echo json_encode($returnData);
JS part:
$.ajax({
url: 'data/members.php',
type: 'POST',
// add data type here
dataType: 'JSON',
data: {'action':'get', 'status':opt.attr('id')},
sucess: function(data) {
...
}
});
As soon and I learn to spell life will be good....had a typo in the javascript...had success as sucess, no wonder it never fired. Now one more question data is being return a array:array how do I access the data? If I use data["key"] I get nothing. If I alert data I get all of the data returned from mysql.
$(function() {
$('#members').on('input', function() {
var opt = $('option[value="'+$(this).val()+'"]');
/*getMember(opt.length ? opt.attr('id'): 0);*/
$.ajax({
url: 'data/members.php',
type: 'POST',
data: {'action':'get', 'status':opt.attr('id')},
success: function(data) {
alert(data);
},
error: function() {
alert("We have a problem");
}
});
});
});
Does the data gets the record as array. As boris pointed out
while($row = $result->fetch_assoc()) {
// You probably want this as array
$returnData = $row;
}
$returnData always gets the last row as it over writen.
you need to code it like.
$returnData = [];
while($row = $result->fetch_assoc()) {
// You probably want this as array
array_push($returnData,$row);
}
And when the result is returned to javascript u need to use JSON.parse
$.ajax({
url: 'data/members.php',
type: 'POST',
data: {'action':'get', 'status':opt.attr('id')},
success: function(data) {
var result = JSON.parse(data);
alert(data);
},
error: function() {
alert("We have a problem");
}
});