Reputation: 269
I have the following code
$(function(){
displayRooms();
editRoom();
});
function displayRooms(){
$.getJSON("displayData.php", {action: "display"}, function(data){
$.each(data.roomData, function(i, room){
$("#display").append("<table><tr><td><a href='#?id=" + room.roomId + "'>Edit</a></td></tr></table>");
}
});
}
function editRoom(){
$("#display a").click(function(){
var roomid = $(this).attr("href").replace("#?id=","");
$.getJSON("displayData.php", {action: "edit", roomid: roomid}, function(data){
$.each(data.roomData, function(i, room){
$("#roomType").val(room.roomType);
});
});
});
}
My php file is correct and my sql statment is correct too but even though i can't make editRoom function execute. Can you please help me out?
Thanks!
I am posting the php function..
function displayData($dbh, $roomid){
$data = array();
$sql = "select roomtype from rooms where roomid = $roomid";
try{
$stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT)){
$data[] = array('roomType' => $row[0]);
}
echo '{"roomData":' . json_encode($data) . '}';
$stmt = null;
}catch(PDOException $e){
die($e);
}
}
Upvotes: -1
Views: 41
Reputation: 33399
What's happening is that editRoom()
is running before the JSON data is fetched. What you need to do is include editRoom()
in the success callback in displayRooms()
.
Upvotes: 2
Reputation: 1794
jQuery.getJSON allows define only success callback.
Try something like this using deferred object:
$.getJSON("displayData.php", {action: "display"})
.done(function(data) {
$.each(data.rooData, function i, room){
$("#display").append("<table><tr><td><a href='#?id=" + room.roomId + "'>Edit</a></td></tr></table>");
}
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert('error');
})
.always(function() {
alert('Error or success');
});
Upvotes: 0