How to push updates into form with ajax - javascript

I have table when i edit any of my rows updates will appear to table but the edit form itself doesn't get update.
Issue in screenshots
1- My row default values
2- Edit form
3- Input update values
4- Updates appear in table
5- Edit form after update still shows old data issue part
I know that I can use options like location.reload(); but the purpose of using ajax (to me) is to not reload the page at all.
code
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var table = $("#data_table2").DataTable();
$('#data_table2').on('click', '.groupUpdate', function(e){
var row = $(this).closest('tr');
e.preventDefault();
var ordID = $(this).data('id');
var name = $(this).closest("form").find("#nameUpdate").val();
var description = $(this).closest("form").find("#descriptionUpdate").val();
$.ajax({
type:'PUT',
url:'{{url('dashboard/banks')}}/'+ordID,
data:{
name:name,
desc:description
},
success:function(data){
table.cell( row, 0 ).data( data.data.id ); // return new values to table
table.cell( row, 1 ).data( data.data.name ); // return new values to table
table.cell( row, 2 ).data( data.data.desc ); // return new values to table
document.getElementById("updateForm").reset();
$(".message").append('<div class="alert alert-success fade in">'+data.success+'</div>').hide(4000); // show success message to user
$('.editModal').modal('hide'); // close the edit modal
}
});
});
});
Any idea how to show updates in edit form as well?

Reset a form that restores the default values. That's why you always see the initial values go back when submitting successfully. Please try just remove the reset operation on the form.

Related

JavaScript doesn't work after ajax loading (using table)

i have a table automatically generated by database using php with four rows ... the last row (4) has a button to trigger the function below... it repeats for every line.
after i click the button...the script sends a request to update database to switch the status "pendent" to "canceled".
at this point everything is okay... BUT...when i refresh the div with the table"$( '#lista' ).load(location.href + ' #lista > *' );"
the script doesnt work a second time after the loading. ( the div update is okay but only works a once)
i need the script working after the first refresh... everytime i clicked in the row button...
i think that may be a incompatibility of ajax request and javascript.
i really appreciate if you can help me.
thank you all.
<script>
var index, table = document.getElementById('table');
for(var i = 1; i < table.rows.length; i++)
{
table.rows[i].cells[4].onclick = function()
{ //inicio da função
var c = confirm('Você quer cancelar essa aula?');
if(c === true)
{//inicio confirmador
var table = document.getElementById('table');
index = this.parentElement.rowIndex;
value_index_id= table.rows[index].cells[0].innerHTML;
var id = value_index_id;
$.ajax({
type: 'GET',
url: 'cancelar_aulas.php',
data: {id_geral:id},
success: function(data){
alert(data);
$( '#lista' ).load(location.href + ' #lista > *' );
}
})
} //fim do confirmador
//validador
//console.log(index);
//console.log (value_index_id);
console.log(id);
};//fim da função
}
</script>";
You're only attaching the onclick event handler to the table when your page loads. That's why it only works on the first click. When you add new data to the table, you need to do something to add the onclick event to the new rows.
There's a few different ways to do this:
jQuery can attach events to dynamically created elements like so:
$("table").on("click", "table tr", function() {
// Note that this event would fire for ALL rows,
// but it will automatically attach this event to new rows
// that are added after page load
// This would work, you just would have to check if the clicked
// row is one of the last 4.
}
Create your own function to attach the event, and you'll run that function every time you add new rows. Something like:
function AttachClick() {
let table = document.getElementById("table");
let position = table.rows.length;
while (position > table.rows.length - 4) {
table.rows[position].addEventListener("click", function() {
// Do your on click here
// On success, you would fire this "AttachClick()" function
}
position--;
}
}
Notice the while loop starting from the end of the table instead of the start. If you had a table with a lot of rows it could be faster to iterate starting at the end (since those are the only rows you care about).

JQuery - Appended Table keeps multiplying itself or duplicating itself when a toggle button is clicked

I wish to have the user click a button to retrieve a table which has data from a mysql database once a button is clicked using an Ajax call using JQuery. The table is appended to a table element which toggles itself for the user to see and disappears once again by clicking a button. This has been achieved from the code below. However, every time the button is clicked, the table multiplies itself and adds two(2) additional copies of itself once it reappears. Which means every time the button is click, it appends itself once again to the table element. I wish that the user on sees the table once when a button is clicked and it disappears again when the same button is clicked again. Once it is clicked for the third time, the same table should reappear and not additional tables.
I have tried the remove method. I have tried the hide and show methods.
<HTML>
<button type = "button" id="allDataTable">Load Stores Table
Data</button>
<br/>
<br/>
<div id="storesT"></div>
<table class='table table-bordered table-striped' id='station_table'>
<JQUERY>
$(document).ready(() => {
$('#allDataTable').click(()=> {
$.ajax({
url:'http://localhost:5000/alldata',
type:'GET',
datatype:'json',
success:(data) => {
//console.log('You received some', data);
var station_data ='';
station_data
+='<tr>'+'<th>ID</th>'+'<th>Station</th>'+'<th>Address</th>'+
'<th>Monthly C-Store Sales</th>'+'<th>Operator</th>'+'<th>Top
SKU</th>'+'</tr>'
$.each(data, function (key,value){
station_data +='<tr><td>'+value.ID+'</td>
<td>'+value.Station+'</td><td>'+value.Address+'</td>
<td>'+value.monthly_cstore_sales+'</td><td>'+value.Operator+'</td>
<td>'+value.Top_SKU+'</tr></td>';
});
$('#station_table').append(station_data);
//NOT WORKING $('#station_table').remove(station_data);
//NOT WORKING $('#station_table').hide(station_data);
//NOT WORKING $('#station_table').show(station_data)
$('#station_table').toggle(station_data);
}
});
});
});
One solution would be to check if the data has already been added to the DOM before making the AJAX call. If not, make the call and then add the data. If yes, then simply toggle a class to hide/show the table.
$(document).ready(() => {
$('#allDataTable').click(()=> {
// Check for the existence of the data table here
if (!$('#station_table').children.length) {
$.ajax({
url:'http://localhost:5000/alldata',
type:'GET',
datatype:'json',
success:(data) => {
//console.log('You received some', data);
var station_data ='';
station_data +='<tr>'+'<th>ID</th>'+'<th>Station</th>'+'<th>Address</th>'+'<th>Monthly C-Store Sales</th>'+'<th>Operator</th>'+'<th>Top SKU</th>'+'</tr>';
$.each(data, function (key,value){
station_data +='<tr><td>'+value.ID+'</td> <td>'+value.Station+'</td><td>'+value.Address+'</td><td>'+value.monthly_cstore_sales+'</td><td>'+value.Operator+'</td> <td>'+value.Top_SKU+'</tr></td>';
});
$('#station_table').append(station_data);
}
});
}
else {
$('#station_table').toggleClass('hide');
}
});
});
CSS
.hide {
display: none;
}
The hide() function hides an element rather than a piece of code. I suggest adding an identifier to each row such as:
station_data +='<tr id="some-identifier"><td>...</td></tr>
You can then toggle the row visibility with
$('#some-identifier').hide() and $('#some-identifier').show()
Check if #station_table is empty first. If so, load content via Ajax. If not, toggle its visibility (if you don't want to reload its contents).
if ($('#station_table').is(':empty')) {
... load content via Ajax ...
}
else {
$('#station_table').toggle();
}

I created a form which will be displayed inside a table. When the information is already inside the table it should allow me to edit it

$('#dependents-info').on('click', '.btn-edit-dependent', function () {
var currentTD = $(this).closest("tr");
$('#modal2').modal({ show: true });
});
This is the code for edit button. I can't get the previous value of the modal where I created it.

Set Chosen value from option text

I have a form which uses the Chosen dropdown. If the option the user wants is not available then they can show a modal with a form to add a new option. After the new option is submitted then the modal closes and the data stays in the fields and the chosen option is selected.
How do I set the chosen option selected by the text with jquery/JS. I wont know the value as its an id that is added in the database
$('#save_town').click(function(e){
e.preventDefault();
var town_name = $('#new_town').val();
var region_id = $('#new_region').val();
$.ajax({
type: 'POST',
data: {town_name: town_name, region_id: region_id},
url: '{/literal}{$base_url}{literal}settings/towns/do-add',
success: function(result){
$('.modal').modal('hide');
location.reload();
},
error: function(){
}
});
});
I´m not sure I understand your question correctly, but maybe thats an solution:
$('option').each(function(){
if($(this).html() == "goodby"){
$(this).attr('selected','selected');
}
});
with this, you can select an option by its text.
example: http://jsfiddle.net/TQnTy/

Javascript validation on paging in kendo ui grid

The following code worked as expected, however on the paging click, it still execute and display message "Please select a record first, then press this button". Is there anyway to prevent this unless the export button click. Thank you
$(document).ready(function () {
$("#Product").on("click",function(){
var $exportLink = $('#export');
var href = $exportLink.attr('href');
var grid = $('#Product').data('kendoGrid'); //get a reference to the grid data
var record = grid.dataItem(grid.select()); //get a reference to the currently selected row
if(record !=null)
{
href = href.replace(/refId=([^&]*)/, 'refId='+record.ID);
$exportLink.attr('href', href);
}
else
{
alert("Please select a record first, then press this button")
return false;
}
});
});
Defining a click handler as $("#Product").on("click",function(){...}) you are actually defining it for any click on #Product not just on you Export button. You should define the on for the button and not for the grid

Categories

Resources