I am trying to receive an array from a PHP document in JavaScript using JSON. The PHP document sends the array (it is printed when I open the PHP file with my browser) but the success()
or done()
methods are not called. What am I doing wrong here?
Code:
JavaScript:
function updateHighscores() {
//var functionName = "showData";
$.ajax({
//type: "GET",
dataType: "json",
url: "gesallprov.php",
//data: {functionName: functionName},
}).done(function(data) {
window.alert("GGGG");
var table = "<table style='width:100%'>" +
"<tr>" +
"<th>No.</th>" +
"<th>Name</th>" +
"<th>Date & Time</th>" +
"<th>Score</th>" +
"</tr>";
$(data).each(function(index, value) {
var i = 1;
table += "<tr>" +
"<td>" + i + "</td>" +
"<td>" + value.name + "</td>" +
"<td>" + value.when + "</td>" +
"<td>" + value.score + "</td>" +
"</tr>";
i++;
});
}
PHP:
function showData() {
try {
$dbh = new PDO(...);
$st = $dbh->prepare("SELECT `name` , `when` , `score` FROM `snake` ORDER BY `score` DESC");
$st->execute();
$result = $st->fetchAll(PDO::FETCH_ASSOC);
return $result;
$st = null;
$dbh = null;
}
catch (PDOException $ex) {
echo 'Connection failed: ' . $ex->getMessage();
}
}
echo json_encode(showData());
why don't you try the following code it might help you fine the problem
jQuery.ajax({
type: "POST",
url: "gesallprov.php",///contain the url of ajax
// data:formData,
dataType:"json",
success : function (data)
{
window.alert("GGGG");
var table = "<table style='width:100%'>" +
"<tr>" +
"<th>No.</th>" +
"<th>Name</th>" +
"<th>Date & Time</th>" +
"<th>Score</th>" +
"</tr>";
$(data).each(function(index, value) {
var i = 1;
table += "<tr>" +
"<td>" + i + "</td>" +
"<td>" + value.name + "</td>" +
"<td>" + value.when + "</td>" +
"<td>" + value.score + "</td>" +
"</tr>";
i++;
});
},
error :function(xhr, ajaxOptions, thrownError){
console.log(xhr);
console.log(ajaxOptions);
// console.log(thrownError);
//alert(xhr.status);
//alert(ajaxOptions);
}
})
If I test your code, I see this message in the browser console:
SyntaxError: missing ) after argument list
Maybe it will help if you add the closing parentheses and curly brace in your updateHighscores
function:
function updateHighscores() {
//var functionName = "showData";
$.ajax({
//type: "GET",
dataType: "json",
url: "gesallprov.php",
//data: {functionName: functionName},
}).done(function (data) {
window.alert("GGGG");
var table = "<table style='width:100%'>" +
"<tr>" +
"<th>No.</th>" +
"<th>Name</th>" +
"<th>Date & Time</th>" +
"<th>Score</th>" +
"</tr>";
$(data).each(function (index, value) {
var i = 1;
table += "<tr>" +
"<td>" + i + "</td>" +
"<td>" + value.name + "</td>" +
"<td>" + value.when + "</td>" +
"<td>" + value.score + "</td>" +
"</tr>";
i++;
});
});
}