Reputation: 2004
I habe built a cascading drop down that functions very well. when the form is submitted, the Id is passed to second script. I can´t seem to get the callback function to ...function properly. Don´t know what wrong.
note I updated the code with the suggested changes, but something still goes wrong.
The php:
<?php
if (!empty($_GET['id'])) {
$id = $_GET['id'];
try {
$objDb = new PDO('mysql:host=localhost;dbname=blankett', 'root', 'root');
$objDb->exec('SET CHARACTER SET utf8');
$sql = "SELECT *
FROM `forms`
WHERE `id` = '$id'";
$statement = $objDb->prepare($sql);
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if (!empty($list)) {
$out = array();
foreach ($list as $row ) {
$out[] = '<tr><td><a href="'.$row['link_form'].'">'.$row['name_form'].'</a></td> <td>'.$row['date_added'].'</td></tr>';
}
echo json_encode(array('error' => false, 'list' => $out));
} else {
echo json_encode(array('error' => true));
}
} catch(PDOException $e) {
echo json_encode(array('error' => true));
}
}else {
echo json_encode(array('error' => true));
}
?>
The Jquery ajax call.
$('#blankett_form').submit(function() {
var id = $(this).find('.update:last').val();
if (id == '') {
alert('Välj land och region.'); //glöm inte bort att ändra beroende på land.
} else {
var table = '<table class="table table-hover table-bordered"><thead><tr><th>blanketter.</th><th>datum tillagt.</th></tr></thead><tbody></tbody></table>'
$('#formsubmit').empty().append(table)
$ajax({
url: 'func/blankett_func2.php',
data: {'id':id},
dataType: 'JSON',
success: function(data)
{
$.each(data.list, function(index, value){
$('#formsubmit tbody').append(value);
});
}
});
return false
});
Upvotes: 0
Views: 230
Reputation: 318192
Replace :
$each(data.out, function(){
var trow = out;
$('#formsubmit tbody').append(trow);
});
With :
$each(data.form, function(i, val){
$('#formsubmit tbody').append(val);
});
as there is no out
variable inside the each function, and it looks like you're naming the key form
in the returned array ?
In the PHP you are redeclaring the array inside the loop, needs to be:
$out = array();
foreach ($list as $row ) {
$out[] = '<tr><td><a href="'.$row['link_form'].'">'.$row['name_form'].'</a></td> <td>'.$row['date_added'].'</td></tr>';
}
and there's no need to pass an empty array to execute():
$statement->execute();
Upvotes: 1
Reputation: 97672
You arent sending the data properly, you have to send the id key and the id value e.g.
data: {'id':id},
Also your json output is of the form {"error": false, "form": "html string"}
so to access the html string you have to use data.form
instead of data.out
. So try
$.each(data.form, function(index, value){
$('#formsubmit tbody').append(value);
});
Upvotes: 1