Reputation: 99
I have a following php file to display SELECT data from database
$connection = mysql_connect(SQL_HOST, SQL_USERNAME, SQL_PASSWORD) or die("Pripojeni se nezdarilo" . mysql_error());
mysql_select_db('svatepole');
$sql = "SELECT * FROM novinky";
$result = MySQL_Query($sql, $connection);
while($zaznam = MySQL_Fetch_Row($result)):
echo "<form class='newsholder'>";
echo "<input value='$zaznam[1]'>";
echo "<input value='$zaznam[2]'>";
echo "<textarea>$zaznam[3]</textarea>";
echo "<input id='prime' attr='id' value='$zaznam[0]'>";
echo "<div class='buttonsholder'>";
echo "<button id='deletebutton'>Smazat</button>";
echo "<button>Upravit</button>";
echo "</div>";
echo "<div class='clearfix'></div>";
echo "</form>";
endwhile;
and I'm trying to add jquery ajax
$('#deletebutton').on('click', function(){
var idVal = $(this).parent().parent().find('#prime').val();
alert(idVal)
$.post("deleterecord.php",
{id:idVal}
);
});
to find the row's ID and pass it to the DELETE file, so the row gets deleted on click.
$connection = mysql_connect(SQL_HOST, SQL_USERNAME, SQL_PASSWORD) or die("Pripojeni se nezdarilo" . mysql_error());
$id = $_POST['id'];
if(! $connection )
{
die('Could not connect: ' . mysql_error());
}
$sql = "DELETE FROM novinky WHERE id = $id"
;
mysql_select_db('svatepole');
$retval = mysql_query( $sql, $connection );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($connection);
However, I can't get this to work. According to Chrome console, there is an event handler attached only to the FIRST row, although the database contains a lot more. Also the added alert only pops out on the click of the very first button.
Any idea, what am I doing wrong and how to pass the data correctly to the DELETE query?
Thanks.
Upvotes: 0
Views: 858
Reputation: 2104
echo "<button id='deletebutton'>Smazat</button>";
change this to
echo "<button class='deletebutton'>Smazat</button>";
and in jquery use.
$('.deletebutton').on('click', function(){
var idVal = $(this).parent().parent().find('#prime').val();
alert(idVal)
$.post("deleterecord.php",{id:idVal},function(response){ alert(response);});
});
when u are using id='deletebutton' .jquery checks for first element with id 'deletebutton'. so the event handler is attached to only first element with id="deletebutton"
Upvotes: 1