binding an id passed through button to data in Jquery - javascript

I have a table with rows. In each row is a button that is specific to that row of data through the value of the data's id.
When a button in a specific row is clicked it fires the AJAX function 'options'. If that is successful then I want to append the data from $newElement to the row in which that button is located. The row is not always the same however so I cant just give it a tr#.
In the code below I have the append working with that data I want but it appends it to every row, not limited to the specific row and that button's id. What am I doing wrong?
AJAX/jQuery where I am appending the data from $newElement but am having trouble binding the id from the button. As a result it adds the data from $newElement to every row instead of ONLY the row in which I clicked the button.
function options(id){
jQuery.ajax({
type: 'post',url: my_ajax.ajax_url,
data: {action: 'options_function',cid : id_In},
success: function (data) {
var $id = id
var $newElement=jQuery("<tr>",
{id:'ideal_option'+id,html:data})
jQuery('#list-table tr').append($newElement)}
});
}
The button and its initial table are generated with a combo of jQuery and HTML. This function is launched on page load. :
function Pop(){ ?>
<script>
jQuery('document').ready(function(){
jQuery.ajax({ data: {action: 'list_ct'},
type: 'post', url: my_ajax.ajax_url,dataType: 'JSON', success: function(data) {
var lnth = data.length-1;jQuery.each( data, function( i, val ) {
console.log(val);
jQuery('<tr><td>'+val.Customer_FName+' '+val.Customer_LName+'<br></td><td class="tdid_'+val.id+'">'+val.Status+'</td><td><button id="options" href="javascript:void(0)" class="button" onclick="options('+val.id+')" data-id="'+val.id+'"></button></td></tr>');
});
}
});
});
</script>
<table id='list-header'>
<th>Name</th>
<tbody id='list-table'>
</tbody>
</table>
<?php
}

Related

Removing item from table with Ajax

I'm building up a table in the View from clicking items in a dropdown menu; I already have a script that does this.
It is also set up so that when an item in the table is clicked, it is removed by the line $(this).parent().remove();
The above two features work
What I need help with is using Ajax to remove the item from the DB as well as just from the table in the View. I already have the controller set up to do this.
My desire is to pass in the id of a removed row to the Ajax section
//Function to append each item clicked in dropdown box to table
$("#subjectlist")
.change(function () {
$("select option:selected").each(function () {
console.log($("select option:selected"));
//the below line of code is setting the id to the
//string: "this.value" and not the number as desired.
//I have confirmed this.value is a number by console
//logging it
$('#overview').append("<tr id='this.value'><td>" +
$(this).text() + "</td><td id=" + this.value + ">" /*+
"X"*/ + "</td></tr>");
});
})
.trigger("change");
//Function to remove fields from table
$("#overview").on('click', 'td', function () {
$(this).parent().remove();
$.ajax({
type: "POST",
url: "ProgrammeMarketing/RemoveOverviewFields",
data: JSON.stringify({ Item: item }),
contextType: "application/json",
Success: function (result) {
}
})
//If anyone wants to see ,below is the table and the form tag helper
using mvc core's ajax helpers to add and display items items to the
table with Ajax
<select asp-for="SubjectAreasOfProgramme"
asp-items="Model.SubjectAreasForDropdown"></select>
<table id="overview" class="table table-sm table-borderless">
#foreach (var item in Model.SubjectAreasOfProgramme)
{
<tr><td>#item</td><td id="Remove">X</td></tr>
}
</table>
In your click function you have to get the Id value before sending it the database via ajax.
$("#overview").on('click', 'td', function () {
var item = $(this).parent().find("td").eq(2).html(); // replace 2 with whatever cell that holds id value
$(this).parent().remove();
$.ajax({
type: "POST",
url: "ProgrammeMarketing/RemoveOverviewFields",
data: JSON.stringify({ Item: item }),
contextType: "application/json",
Success: function (result) {
}
})

send jQuery generated table to another php page

In my project (some kind of online game store), i have a jQuery generated table from click on original table row. The original table is populated from mysql database. On submit i need to send that generated table to another php page. I'm quite new with it and so far this is my code:
on php_first.php
generated table
<form action="php_second.php" id ="form_send" name ="form_send1" method="POST">
<div>
<table id="generated_table" style="display:none" name ="generated_table1">
<tr><th>Game</th><th>Platform</th> <th>Genre</th> <th>Price</th><tr>
// generated rows here
</table>
<input type="submit" value="Confirm" id="btnOrder" style="display:none"></input>
</div>
</form>
generated rows
$(document).ready(function(){
$('#original_table tbody tr').click(function(){
var data = $(this).children("td").map(function(){
return $(this).text();
}).get();
var row= '<tr name ="new_row"><td name = "game">' + data[0] + '</td><td name = "platform">' + data[1] +
'</td><td name = "genre">' + data[2] + '</td><td name = "price">' + data[3] +
'<button type="button" onclick="remove(this)" class ="btn_remove">Remove</button>' +'</td></tr>';
$("#generated_table tbody").append(row);
$('#generated_table').show();
$('#btnConfirm').show();
});
ajax post to php_second.php
$('#btnOrder').click(function(){
var table= $('#generated_table');
$.ajax({
url: 'php_second.php',
type: 'POST',
data: {data: table},
async: false,
success: function(data){
alert(data);
}
});
However, ajax dosen't do alert(data) so i asume this is the problem but i cant determine it.
and on php_second.php
<table id="table_order" name = "table_order1" style="display:show">
<?php
if(isset($_POST['generated_table'])){
$table= $_POST['generated_table'];
echo $table;
}
?>
</table>
The problem is that i cannot post table data to another php (and print that table on other php when redirected). Tried to use ajax to send row data on row click, or passing div where table is but nothing. It shows no errors but no data is passed.
This is my first question so it is possible that i missed out some details to make the problem more clear. Thanks!
EDIT
I've tried Kalaikumar Thangasamy's code and ajax is working fine now, but the problem is on other php page.
<?php
if(isset($_POST['data'])){
$table = $_POST['data'];
echo $table;
}
else {
echo "None selected";
}
?>
The $_POST['data'] or any other parameter from first php is always null.
Change data: {data: table} to data: {'generated_table': escape(table)}. Posting data as but referring post data in $_POST['generated_table']. You suppose to be used $_POST['data']. Try this
var table= $('#generated_table').html();
$.ajax({
url: 'php_second.php',
type: 'POST',
data: {'generated_table': escape(table)},
async: false,
success: function(data){
alert(data);
}
});

unable to delete newly added rows on the table with dataTable jquery

I have a html table that has a content came from a database by using ajax and php.
When i try to add a new row manually by filling all the inputs and click save button it will add the data to the table.
My problem is when i try to delete the newly added rows and click the delete button on that specific row it doesn't delete. But when i try to delete the rows that came from the database it is deleted from the html table.
script:
$.ajax({
url: 'process.php',
type: 'post',
data: {tag: 'getData'},
dataType: 'json',
success: function(data){
if(data.success){
$("#myTable2 tbody").empty();
$.each(data, function(index, record){
if($.isNumeric(index)){
var row = $("<tr />");
$("<td />").text(record.name).appendTo(row);
$("<td />").text(record.age).appendTo(row);
$("<td />").text(record.gender).appendTo(row);
$("<td />").html(record.action).appendTo(row);
row.appendTo("#myTable2 tbody");
}
})
}
var oTable = $('#myTable2').DataTable();
$("#myTable2 tbody .dltRow").bind( 'click', function(event) {
var row = $(this).closest('tr').get(0);
oTable.row(row).remove().draw();
oTable.row($(this).closest('tr')).remove().draw();
$(this).parent().parent().closest('tr').remove();
oTable.fnDeleteRow(oTable.fnGetPosition(row));
});
$('#Save2').on( 'click', function () {
var data = [
$('#name').val(),
$('#age').val(),
$("[name='gender']:checked").val(),
"<center><button type='button' class='btn btn-default dltRow'><i class='glyphicon glyphicon-trash'></i></button></center>"
];
oTable.row.add(data).draw();
});
}
});
use event delegation to attach events to dynamically added delete buttons.
$("#myTable2 tbody").on( 'click','.dltRow', function(event) {
var row = $(this).closest('tr').get(0);
oTable.row(row).remove().draw();
oTable.row($(this).closest('tr')).remove().draw();
$(this).parent().parent().closest('tr').remove();
oTable.fnDeleteRow(oTable.fnGetPosition(row));
});

Updating the database on click of a table row

I am having a table in which data is being populated through the database.Now what i want is that as soon as i click on one of the row a alert message displays and the READSTATUS of that row become true in my database that is database gets updated .
Now my problem is where to write the code for updating the database as i dont want to move to a different page to do so.
Like my table is something like this :
<input type=hidden name="notifyidd" id="notifyidd" value="<%=messageid%>"/>
<tr bgcolor="#5D1B90" color="#FFFFFF" onmouseover="ChangeColor(this, true,false);" onmouseout="ChangeColor(this, false,false);" onclick="DoNav('shownotification.jsp?mid=<%=messageid%>');">
<td><input type="checkbox" name="" onclick="DoRemove(event);" width="20" class="select_all_mail" value=<%=messageid%>></td>
<td callspan="3" width="1000px"><%=messagesubject%> at <%=sendingtime%></td>
</tr>
and in onclick method of each row i had called the alert.But how to update the database now ?
function DoNav(theUrl)
{
var tt = document.myinbox.notifyidd.value;
alert(tt);
//document.location.href = theUrl;
}
As if i uncomment this line then it will move to next page.But i want to do it on same page only.Please help
EDIT :
I wrote a ajax code to do it.But it gives error.Please help
$(document).ready(function() {
$('#myrow').click(function ()
{
$.ajax({
type: "post",
url: "shownotification.jsp", //this is my servlet
data: {
notifyidd: $('#notifyidd').val()
},
success: function(msg){
if(msg == "success")
alert('Data updated.');
}
});
});
});
Here i assign myrow as id to my table row.Also i removed doNav function now
My error image clicked :
http://postimg.org/image/vix1vzvq5/
Though the error is resolved but this ajax call is not functioning.For test i make my shownotification.jsp as :
<body>
<% String notifyid = request.getParameter("notifyidd");%>
success
</body>
The error message says the server-side code is failing when looking for the attribute "groupid". The post you are sending has notifyidd instead. The server code has no way of knowing if this should map to groupid or not.
Try this. If it doesn't work, update us with the error.
$(document).ready(function() {
$('#myrow').click(function ()
{
$.ajax({
type: "post",
url: "shownotification.jsp", //this is my servlet
data: {
groupid: $('#notifyidd').val()
},
success: function(msg){
if(msg == "success")
alert('Data updated.');
}
});
});
});

retrieve data from database without refreshing the page

When the user press entre the data will be save into database.
Ajax
$('td.edit').keydown(function(event){
arr = $(this).attr('class').split( " " );
var clientid=document.getElementById("client").value;
account_id=document.getElementById("account_id").value;
if(event.which == 13)
{
$.ajax({ type: "POST",
url:"clientnetworkpricelist/update.php",
data: "value="+$('.ajax input').val()+"&rowid="+arr[2]+"&field="+arr[1]+"&clientid="+clientid+"&account_id="+account_id,
success: function(data){
$('#CPH_GridView1_Status').append(data);
$('.ajax').html($('.ajax input').val());
$('.ajax').removeClass('ajax');
}});
}
}
Html
<td id="CPH_GridView1_Status'.$rows['net_id'].'" class="edit2 status '.$rows["net_id"].' "><img src="image/'.$rows["status"].'f.png" /></td>
After success I want to retrieve data from database and place it in the proper td ( in the same row of the clicked td) i am success to retrieve data but not retrieve in the correct td
which row you want to load data?
change it:
$('#CPH_GridView1_Status').append(data);
to
$('#CPH_GridView1_Status'+arr[2]).append(data);
Before appending data first clear current '' using
$('#CPH_GridView1_Status'+arr[2]).empty();
and then append data
$('#CPH_GridView1_Status'+arr[2]).append(data);

Categories