Local storage with jQuery - html

I create a table with CRUD operations in jQuery. All CRUD operations worked, no issues with them. I need to store the every uploaded data in local storage. When I add data to the table, the data is stored in the local storage. But when I added one more data to the table, the first data was deleted automatically in local storage. Local storage displays only current data. If I made any changes to the table, local storage data wouldn't be updated. Please help me to solve the issue.
<!DOCTYPE html>
<html lang="en">
<head>
<title>CRUD Table jQuery</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12 text-right">
<input type="button" id="btnAdd" class="btn btn-primary para" value="Add New" />
</div>
</div>
<div class="row pt-3">
<div class="col-md-12 col-sm-12 col-12 p-2 ">
<table id="tblData" class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
<th>Age</th>
<th class="tdaction">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
<script>
var emptyRow = "<tr><td colspan='4' class='text-center'></td></tr>";
var emptyNewRow = "<tr class='trNewRow'>";
emptyNewRow = emptyNewRow + " <td class='tdID'>";
emptyNewRow = emptyNewRow + " <input type='text' class='form-control txtID' />";
emptyNewRow = emptyNewRow + " </td>";
emptyNewRow = emptyNewRow + " <td class='tdName'>";
emptyNewRow = emptyNewRow + " <input type='text' class='form-control txtName' />";
emptyNewRow = emptyNewRow + " </td>";
emptyNewRow = emptyNewRow + " <td class='tdAddress'>";
emptyNewRow = emptyNewRow + " <input type='text' class='form-control txtAddress' />";
emptyNewRow = emptyNewRow + " </td>";
emptyNewRow = emptyNewRow + " <td class='tdAge'>";
emptyNewRow = emptyNewRow + " <input type='text' class='form-control txtAge' />";
emptyNewRow = emptyNewRow + " </td>";
emptyNewRow = emptyNewRow + " <td class='tdAction'>";
emptyNewRow = emptyNewRow + " <button class='btn btn-sm btn-success btn-save'> Save</button>";
emptyNewRow = emptyNewRow + " <button class='btn btn-sm btn-success btn-cancel'> Delete</button>";
emptyNewRow = emptyNewRow + " </td>";
emptyNewRow = emptyNewRow + "</tr>";
var rowButtons ="<button class='btn btn-success btn-sm btn-edit' > Edit </button> <button class='btn btn-danger btn-sm' > Delete </button>";
var rowUpdateButtons ="<button class='btn btn-success btn-sm btn-save' > Update </button> <button class='btn btn-danger btn-sm btn-save' > Delete </button> ";
$(document).ready(function () {
//debugger;
$("#tblData tbody").append(emptyRow); // adding empty row on page load
$("#btnAdd").click(function () {
//debugger;
if ($("#tblData tbody").children().children().length == 1) {
$("#tblData tbody").html("");
}
//debugger;
$("#tblData tbody").append(emptyNewRow); // appending dynamic string to table tbody
});
$('#tblData').on('click', '.btn-save', function () {
const id = $(this).parent().parent().find(".txtID").val();
$(this).parent().parent().find(".tdID").html(""+id+"");
const name = $(this).parent().parent().find(".txtName").val();
$(this).parent().parent().find(".tdName").html(""+name+"");
const address = $(this).parent().parent().find(".txtAddress").val();
$(this).parent().parent().find(".tdAddress").html(""+address+"");
const age = $(this).parent().parent().find(".txtAge").val();
$(this).parent().parent().find(".tdAge").html(""+age+"");
$(this).parent().parent().find(".tdAction").html(rowButtons);
});
$('#tblData').on('click', '.btn-danger', function () { // registering function for delete button
$(this).parent().parent().remove();
if ($("#tblData tbody").children().children().length == 0) {
$("#tblData tbody").append(emptyRow);
}
});
$('#tblData').on('click', '.btn-cancel', function () {
$(this).parent().parent().remove();
});
$('#tblData').on('click', '.btn-edit', function () {
const id =$(this).parent().parent().find(".tdID").html();
$(this).parent().parent().find(".tdID").html("<input type='text' value='"+id+"' class='form-control txtID' />");
const name =$(this).parent().parent().find(".tdName").html();
$(this).parent().parent().find(".tdName").html("<input type='text' value='"+name+"' class='form-control txtName' />");
const address =$(this).parent().parent().find(".tdAddress").html();
$(this).parent().parent().find(".tdAddress").html("<input type='text' value='"+address+"' class='form-control txtAddress' />");
const age =$(this).parent().parent().find(".tdAge").html();
$(this).parent().parent().find(".tdAge").html("<input type='text' value='"+age+"' class='form-control txtAge' />");
$(this).parent().parent().find(".tdAction").html(rowUpdateButtons);
});
$('.btn-save').click(function() {
localStorage.setItem('txtId', id);
localStorage.getItem('txtId');
localStorage.setItem('txtName', name);
localStorage.getItem('txtName');
localStorage.setItem('txtAddress', address);
localStorage.getItem('txtAddress');
localStorage.setItem('txtAge', age);
localStorage.getItem('txtAge');
});
$('.btn-danger').click(function() {
localStorage.removeItem('txtID');
localStorage.removeItem('txtName');
localStorage.removeItem('txtAddress');
localStorage.removeItem('txtAge');
});
});
</script>
</body>
</html>

Consider the following jsFiddle Example. I used jsFiddle as it allows for the use of localStorage where Stack Overflow Snippets do not.
Fiddle: https://jsfiddle.net/Twisty/3u6gpc49/
JavaScript
$(function() {
var myEmptyRow = [{
class: "tdID",
content: $("<input>", {
type: "text",
class: "form-control txtID"
})
}, {
class: "tdName",
content: $("<input>", {
type: "text",
class: "form-control txtName"
})
}, {
class: "tdAddress",
content: $("<input>", {
type: "text",
class: "form-control txtAddress"
})
}, {
class: "tdAge",
content: $("<input>", {
type: "text",
class: "form-control txtAge"
})
}, {
class: "tdAction",
content: [
$("<button>", {
class: "btn btn-sm btn-success btn-save"
}).html("Save"),
$("<button>", {
class: "btn btn-sm btn-success btn-cancel"
}).html("Delete")
]
}];
var myButtons = {
edit: [
$("<button>", {
class: "btn btn-success btn-sm btn-edit"
}).html("Edit"),
$("<button>", {
class: "btn btn-danger btn-sm"
}).html("Delete")
],
update: [
$("<button>", {
class: "btn btn-success btn-sm btn-save"
}).html("Update"),
$("<button>", {
class: "btn btn-danger btn-sm"
}).html("Delete")
]
};
function getStore(index) {
console.log("Get data for " + index);
return JSON.parse(localStorage.getItem(index));
}
function saveStore(index, data) {
console.log("Saving Data to " + index, data);
localStorage.setItem(index, JSON.stringify(data));
}
function deleteStore(index) {
console.log("Deleting Data for " + index);
localStorage.removeItem(index);
}
function addRow(target, data, empty) {
if (target == undefined) {
target = $("table:eq(0)");
}
if (empty == undefined) {
empty = false;
}
if (data == null) {
return false;
}
console.log("Add Row to " + target.attr("id"), empty);
if (empty) {
$("tbody", target).html("");
}
var row = $("<tr>").appendTo($("tbody", target));
if (data == undefined) {
// Add Empty Row
$("<td>", {
colspan: 4,
class: "text-center"
}).appendTo(row);
} else {
row.addClass("trNewRow");
$.each(data, function(i, cell) {
$("<td>", {
class: cell.class
}).append(cell.content).appendTo(row);
});
}
console.log(data, data.length);
if (data.length == 4) {
$("<td>", {
class: "tdAction"
}).append(myButtons.edit).appendTo(row);
}
return row;
}
function saveRow(row) {
if (row == undefined) {
return false;
}
var rowData = [{
class: "tdID",
content: $(".txtID", row).val()
},
{
class: "tdName",
content: $(".txtName", row).val()
}, {
class: "tdAddress",
content: $(".txtAddress", row).val()
}, {
class: "tdAge",
content: $(".txtAge", row).val()
}
];
$.each(rowData, function(i, c) {
$("." + c.class, row).html(c.content);
});
$(".tdAction", row).html(myButtons.edit);
saveStore("row-" + row.index(), rowData);
}
function init() {
if (localStorage.length == 0) {
addRow($("#tblData"));
} else {
console.log("Found Local Storage. Rows: " + localStorage.length);
$.each(localStorage, function(k, o) {
var rowData = getStore(k);
console.log(k, rowData);
addRow($("#tblData"), rowData);
});
}
}
init();
$("#btnAdd").click(function() {
addRow($("#tblData"), myEmptyRow, $("#tblData tbody tr td").length == 1 ? true : false);
});
$('#tblData').on('click', '.btn-save', function() {
saveRow($(this).closest("tr"));
});
$('#tblData').on('click', '.btn-danger, .btn-cancel', function() {
// registering function for delete button
deleteStore("row-" + $(this).closest("tr").index());
$(this).closest("tr").remove();
if ($("#tblData tbody tr").length == 0) {
addRow($("#tblData "));
}
});
$('#tblData').on('click', '.btn-edit', function() {
var row = $(this).closest("tr");
$(".tdID", row).html("<input type='text' value='" + $(".tdID", row).html() + "' class='form-control txtID' />");
$(".tdName", row).html("<input type='text' value='" + $(".tdName", row).html() + "' class='form-control txtName' />");
$(".tdAddress", row).html("<input type='text' value='" + $(".tdAddress", row).html() + "' class='form-control txtAddress' />");
$(".tdAge", row).html("<input type='text' value='" + $(".tdAge", row).html() + "' class='form-control txtAge' />");
$(".tdAction", row).html(myButtons.update);
});
});
There is a lot to break down here. I will try to focus on the Save, Edit, and Delete buttons. To help with this, it is best to create functions for these operations. Also, you must remember that localStorage can only contain String data.
We will start with Saving a Row. We gather all the details for the Row and then pass them to the saveStore() function. This takes two parameters, an index and the data.
function saveStore(index, data) {
console.log("Saving Data to " + index, data);
localStorage.setItem(index, JSON.stringify(data));
}
As we're passing in an Array of Objects, and not a String, we must convert this to a String. I use JSON.stringify() to accomplish this. This results in a JSON String that can be parsed later.
If we are Deleting a row, we can do this.
function deleteStore(index) {
console.log("Deleting Data for " + index);
localStorage.removeItem(index);
}
I am using the format row-0, row-1, row-2... for the indexes.
If rows are saved and the browser crashes or the user reloads the page for some reason, you might want to display the currently saved Rows. this is where our final function comes in handy.
function getStore(index) {
console.log("Get data for " + index);
return JSON.parse(localStorage.getItem(index));
}
Here we can collect the saved Row data and parse it back into an Array of Objects. Often times, we will know the index name. When we load the page, we may not know the names or how many rows are saved. We can treat localStorage similar to an Object to check on this.
$.each(localStorage, function(k, o) {
var rowData = getStore(k);
console.log(k, rowData);
addRow($("#tblData"), rowData);
});
This iterates over each of the localStore items and gets the index name.
there are a lot of other parts to this that I updated to jQuery. I used what is considered best practices. That might be a matter of opinion, and you can choose to setup your code any way you like. To address this question, please focus on the functions created to help with localStorage.
In regards to your selectors, using .children(), this is not a good method. Consider that $("tr").find(".tdID") is the same as $(".tdID", "tr")
Selector context is implemented with the .find() method; therefore, $( "li.item-ii" ).find( "li" ) is equivalent to $( "li", "li.item-ii" ).
This means that if you can target the parent Row, you can more easily select child elements. Example: $(".tdID", row).html()

localStorage.setItem() does exactly what it suggests... It sets that value to that key in local storage. If any previous value was set, it overwrites that value.
If you want to append to the previous value in some way, you need to read that value, update it, and write it back. For example, this would append the value as an array element:
let txtId = localStorage.getItem('txtId') || [];
txtId.push(id);
localStorage.setItem('txtId', txtId);
(Make sure to clear existing values before debugging this.)
The idea above is to read the stored value, which should be an array if it was previously set. If no value exists, default to an empty array. Then append the new id value to that array. Then write that array back to local storage.
Basically, local storage won't organize your data for you. It will store whatever you write to it and only what you write to it. It's up to you to manage how that data is organized and what you're writing to it.

Related

Is there a good package/library to add Pagination/Sorting/Searching to my table? ASP.NET Core

I am new to web development in ASP.NET Core. I have a table with information, I would like to add pagination/sorting/searching to the table. Is there an easy way to add this using some sort of library/package? Thanks
I need pagination, sorting, and searching for my ASP.NET Core table.
I would like to add pagination/sorting/searching to the table. Is
there an easy way to add this using some sort of library/package?
Well, considering all the requirement you can go for jquery data table regardless of simplicity, quick implementation and free subscription. Importantly, its light weight and easy to use.
Here is the compplete example how you can implement that:
Controller:
[HttpGet]
public IActionResult ConAction()
{
var controlleractionlist = _context.Controller.ToList();
return Json(controlleractionlist);
}
Note: I am returning a simple list to demonstrate you , sorting, searching and paging functionality.
View:
<table id="userTable_info" >
<thead>
<tr>
<th>action </th>
<th>controller </th>
<th>returnType</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tBody"> </tbody>
</table>
#section scripts {
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
<script>
//Button Click Functions
function DetailsFunc(data) {
alert("User Id:" + data + " Details!");
}
function EditFunc(data) {
alert("User Id:" + data + " will be Edited!");
}
function DeleteFunc(data) {
alert("User Id:" + data + " will be deleted!");
}
//On Load
$(document).ready(function () {
$.ajax({
type: "GET",
url: 'http://localhost:5094/Home/ConAction',
dataType: "json",
contentType: "application/json",
success: function (response) {
console.log(response);
var id = 0;
$.each(response, function (index, value) {
id++;
console.log(id);
var tr = "<tr>";
tr += "<td>" + value.action + "</td>";
tr += "<td>" + value.controller + "</td>";
tr += "<td>" + value.returnType + "</td>";
tr += "<td>" + "<input type='button' id='" + id + "' class='btn btn-info' onclick='DetailsFunc(" + value.id + ")' value='Details'>" + " " + "<input type='button' id='" + value.id + "' class='btn btn-warning' onclick='EditFunc(" + value.id + ")' value='Edit'>" + " " + "<input type='button' id='" + value.id + "' class='btn btn-danger' onclick='DeleteFunc(" + value.id + ")' value='Delete'>" + "</td>" + "</tr>";
$("#tBody").append(tr);
});
$("#userTable_info").DataTable();
}
});
});
</script>
}
Output:
You could refer to official document for more details.

Save the data in Local storage using jQuery

I create a table with CRUD operations in jQuery. All CRUD operations worked, no issues on it. I need to save the data in local storage. But I don't know the code for how to save the data in local storage. Please help me to code for save the data in local storage. Below, my code for create table with CRUD operations in jQuery.
<!DOCTYPE html>
<html lang="en">
<head>
<title>CRUD Table jQuery</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12 text-right">
<input type="button" id="btnAdd" class="btn btn-primary para" value="Add New" />
</div>
</div>
<div class="row pt-3">
<div class="col-md-12 col-sm-12 col-12 p-2 ">
<table id="tblData" class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
<th>Age</th>
<th class="tdaction">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
<script>
var emptyRow = "<tr><td colspan='4' class='text-center'></td></tr>";
var emptyNewRow = "<tr class='trNewRow'>";
emptyNewRow = emptyNewRow + " <td class='tdID'>";
emptyNewRow = emptyNewRow + " <input type='text' class='form-control txtID' />";
emptyNewRow = emptyNewRow + " </td>";
emptyNewRow = emptyNewRow + " <td class='tdName'>";
emptyNewRow = emptyNewRow + " <input type='text' class='form-control txtName' />";
emptyNewRow = emptyNewRow + " </td>";
emptyNewRow = emptyNewRow + " <td class='tdAddress'>";
emptyNewRow = emptyNewRow + " <input type='text' class='form-control txtAddress' />";
emptyNewRow = emptyNewRow + " </td>";
emptyNewRow = emptyNewRow + " <td class='tdAge'>";
emptyNewRow = emptyNewRow + " <input type='text' class='form-control txtAge' />";
emptyNewRow = emptyNewRow + " </td>";
emptyNewRow = emptyNewRow + " <td class='tdAction'>";
emptyNewRow = emptyNewRow + " <button class='btn btn-sm btn-success btn-save'> Save</button>";
emptyNewRow = emptyNewRow + " <button class='btn btn-sm btn-success btn-cancel'> Delete</button>";
emptyNewRow = emptyNewRow + " </td>";
emptyNewRow = emptyNewRow + "</tr>";
var rowButtons ="<button class='btn btn-success btn-sm btn-edit' > Edit </button> <button class='btn btn-danger btn-sm' > Delete </button>";
var rowUpdateButtons ="<button class='btn btn-success btn-sm btn-save' > Update </button> <button class='btn btn-danger btn-sm btn-save' > Delete </button> ";
$(document).ready(function () {
//debugger;
$("#tblData tbody").append(emptyRow); // adding empty row on page load
$("#btnAdd").click(function () {
//debugger;
if ($("#tblData tbody").children().children().length == 1) {
$("#tblData tbody").html("");
}
//debugger;
$("#tblData tbody").append(emptyNewRow); // appending dynamic string to table tbody
});
$('#tblData').on('click', '.btn-save', function () {
const id = $(this).parent().parent().find(".txtID").val();
$(this).parent().parent().find(".tdID").html(""+id+"");
const name = $(this).parent().parent().find(".txtName").val();
$(this).parent().parent().find(".tdName").html(""+name+"");
const address = $(this).parent().parent().find(".txtAddress").val();
$(this).parent().parent().find(".tdAddress").html(""+address+"");
const age = $(this).parent().parent().find(".txtAge").val();
$(this).parent().parent().find(".tdAge").html(""+age+"");
$(this).parent().parent().find(".tdAction").html(rowButtons);
});
$('#tblData').on('click', '.btn-danger', function () { // registering function for delete button
$(this).parent().parent().remove();
if ($("#tblData tbody").children().children().length == 0) {
$("#tblData tbody").append(emptyRow);
}
});
$('#tblData').on('click', '.btn-cancel', function () {
$(this).parent().parent().remove();
});
$('#tblData').on('click', '.btn-edit', function () {
const id =$(this).parent().parent().find(".tdID").html();
$(this).parent().parent().find(".tdID").html("<input type='text' value='"+id+"' class='form-control txtID' />");
const name =$(this).parent().parent().find(".tdName").html();
$(this).parent().parent().find(".tdName").html("<input type='text' value='"+name+"' class='form-control txtName' />");
const address =$(this).parent().parent().find(".tdAddress").html();
$(this).parent().parent().find(".tdAddress").html("<input type='text' value='"+address+"' class='form-control txtAddress' />");
const age =$(this).parent().parent().find(".tdAge").html();
$(this).parent().parent().find(".tdAge").html("<input type='text' value='"+age+"' class='form-control txtAge' />");
$(this).parent().parent().find(".tdAction").html(rowUpdateButtons);
});
});
</script>
</body>
</html>
add this
localStorage.setItem('x', y);
x = name of whatver you want the local storage var to be
y = the value of what you want to save
for example:
const id = $(this).parent().parent().find(".txtID").val();
you would save it in local storage as
localStorage.setItem('txtId', id);
now to call it or to see the value later on you simply just put
localStorage.getItem('txtId');

How to edit array value using jquery?

I am trying to edit array values using jquery. here is what I did.
From a modal, everytime I click the "Add item" button it will push values to an array and just append the data to a table
var iteminfo = {
"row": 'row' + cnt,
"make": make,
"body": body,
"cabin": cabin,
"horsepower": horsepower,
"wheels": wheels,
"chassis": chassis,
"engine": engine,
"remarks": remarks,
"shipmenttag": shipmenttag
};
trucksarray.push(iteminfo);
//append to table:
$("#truckstable > tbody").prepend(<tr><td>.....</td></tr>);
and my html table looks like this:
now I am able to delete a table row and the corresponding data from the array with this code:
//removing the table row
$("#truckstable").on('click', '.remrow', function () {
var id = $(".remrow").attr("id");
$(this).parent().parent().remove();
removeitem(id)
});
//removing array item
function removeitem(row) {
const itemToRemoveIndex = trucksarray.findIndex(function (item) {
return item.row === row;
});
if (itemToRemoveIndex !== -1) {
trucksarray.splice(itemToRemoveIndex, 1);
}
toastr.warning('Item removed!');
}
Now, my problem is, If I click the edit button a modal should popup and be able to edit the selected item value , the table data and the array values as well? Any idea?
You can give data-* to your edit button i.e : data-id="row1"..etc then on click of this button get the data-id value and use filter to filter the JSON Array already created and get only data where row == data-id.
Now , once you got the array values put this values inside the input-box of modal using .val("yourfromarray"). Then, onclick of save button get the value from input box and loop through your JSON Array and update value of array with new values.Lastly add these updated value inside trs.
Demo Code :
var cnt = 0;
var trucksarray = [];
$('#BtnAddTruck').on('click', function() {
var make = $('#tmake').val();
var body = $('#tbody').val();
var cabin = $('#tcabin').val();
var horsepower = $('#thorsepower').val();
var wheels = $('#twheels').val();
var chassis = $('#tchassis').val();
var engine = $('#tengine').val();
var remarks = $('#tremarks').val();
var shipmenttag = 'Truck';
cnt = cnt + 1;
var iteminfo = {
"row": 'row' + cnt,
"make": make,
"body": body,
"cabin": cabin,
"horsepower": horsepower,
"wheels": wheels,
"chassis": chassis,
"engine": engine,
"remarks": remarks,
"shipmenttag": shipmenttag
};
trucksarray.push(iteminfo);
//added here `id` to tr and `data-id` to edit button
$("#truckstable > tbody").
prepend("<tr id='trow" + cnt + "'>" +
"<td>" + make + " " + body + " " + cabin + " " + horsepower + " " + wheels +
"</td>" +
"<td>" + chassis + "</td>" +
"<td>" + engine + "</td>" +
"<td>" + remarks + "</td>" +
"<td>" +
" <button class='btn-primary edit' data-toggle='modal' data-target='#myModal' data-id='row" + cnt + "'>Edit</button>" +
" <button class='remrow btn-danger' id='row" + cnt +
"'>delete</button>" +
"</td>" +
"</tr>"
);
//clearmodalinput();
$(".empty_k input").val("");
//toastr.info('Item added!');
console.log(trucksarray)
});
var id;//delcare this globally
//on click of edit
$(document).on('click', '.edit', function() {
id = $(this).data('id');//get id
console.log(id)
//filter json array and get value only where match
var trucks = $(trucksarray)
.filter(function(i, n) {
return n.row === id;
});
//put value inside input in modal
$('.make').val(trucks[0].make);
$('.body').val(trucks[0].body);
$('.cabin').val(trucks[0].cabin);
$('.horsepower').val(trucks[0].horsepower);
$('.wheels').val(trucks[0].wheels);
$('.chassis').val(trucks[0].chassis);
$('.engine').val(trucks[0].engine);
$('.remarks').val(trucks[0].remarks);
});
//click on save button
$(".save").click(function() {
//loop through array
$(trucksarray).each(function() {
if (this.row == id) {
//creplace value inside array
this.horsepower = $('.horsepower').val();
this.make = $('.make').val();
this.remarks = $('.remarks').val();
this.engine = $('.engine').val();
this.chassis = $('.chassis').val();
this.cabin = $('.cabin').val();
this.body = $('.body').val();
this.wheels = $('.wheels').val();
return false;//got it stop loop
}
});
replace_values(); //replace table datas
})
function replace_values() {
//get values
var make = $('.make').val();
var body = $('.body').val();
var cabin = $('.cabin').val();
var horsepower = $('.horsepower').val();
var wheels = $('.wheels').val();
var chassis = $('.chassis').val();
var engine = $('.engine').val();
var remarks = $('.remarks').val();
//replace trs values
$("#t" + id).html("<td>" + make + " " + body + " " + cabin + " " + horsepower + " " + wheels +
"</td>" +
"<td>" + chassis + "</td>" +
"<td>" + engine + "</td>" +
"<td>" + remarks + "</td>" +
"<td>" +
" <button class='btn-primary edit' data-toggle='modal' data-target='#myModal' data-id='" + id + "'>Edit</button>" +
" <button class='remrow btn-danger' id='" + id +
"'>delete</button>" +
"</td>")
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="empty_k">
<input type="text" id="tmake">
<input type="text" id="tbody">
<input type="text" id="tcabin">
<input type="text" id="thorsepower">
<input type="text" id="twheels">
<input type="text" id="tchassis">
<input type="text" id="tengine">
<input type="text" id="tremarks">
<button id="BtnAddTruck">Add</button>
</div>
<div class="table-responsive">
<table class="table table-bordered" id="truckstable">
<thead>
<tr>
<th scope="col">Description</th>
<th scope="col">Chassis</th>
<th scope="col">Engine</th>
<th scope="col">Remarks</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Edit..</p>
tmake : <input type="text" class="make"><br/> tbody : <input type="text" class="body"> <br/>tcabin : <input type="text" class="cabin"> <br/>thorsepower :<input type="text" class="horsepower"> <br/>twheels : <input type="text" class="wheels"><br/> tchassis :
<input type="text" class="chassis">
<br/> tengine :<input type="text" class="engine"><br/> tremarks : <input type="text" class="remarks">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default save" data-dismiss="modal">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

How do I get the form data in Codeigniter controller using ajax?

http://zivite.com/salary/
Hi, Guys please visit the link above mentioned.
Whenever choosing the designation from the dropdown, it will be listed all the data associated with that particular designation.
In the loop data, I have added form around the tr and submit button as well as added some additional fields like attendance, loan, rate etc. Whenever hit the submit button for a particular person. it should be stored in my database table which called the salary table.
Now my problem is not getting the data inside the model when we hit the submit button,
If you inspect it you can see array is creating there but no data from the submitted form
see this image link below
https://ibb.co/h11SgMV
// view
<?php include "template/header.php"; ?><!-- Start Page content -->
<div class="content">
<div class="container-fluid">
<div class="card-box">
<form action="%3C?php%20echo%20base_url('con_employee/employeeSearch');%20?%3E" class="form-inline" method="post">
<div class="form-group" style="padding-right:10px; width:100%;">
<select class="custom-select" id="empDesignation" name="empDesignation">
<option selected>
Designation
</option><?php foreach($categories as $category){ ?>
<option value="<?php echo $category['cat_id']; ?>">
<?php echo $category['cat_name']; ?>
</option><?php } ?>
</select>
</div>
</form><br>
<div class="row">
<table class="table table-hover table-centered m-0 table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Designation</th>
<th>Account Number</th>
<th>Attendance</th>
<th>Rate</th>
<th>Loan</th>
<th>Action</th>
</tr>
</thead>
<tbody id="salaryData"></tbody>
</table>
</div>
</div>
</div><!-- container -->
</div><!-- content -->
<!-- end row -->
<script>
$(function() {
$('#empDesignation').change(function() {
var user_designation = $(this).val();
if (user_designation == '') {
$('#empName').prop('disabled', true);
} else {
$('#empName').prop('disabled', false);
$.ajax({
url: "<?php echo site_url(); ?>con_salary/add_salary_for_employee",
type: "POST",
data: {
'user_designation': user_designation
},
dataType: 'json',
success: function(data) {
var html = '';
var i;
for (i = 0; i < data.length; i++) {
html += '<tr>' +
'<form class="" id="myform">' +
'<td>' + data[i].emp_name + ' <\/td>' +
'<td>' + data[i].cat_name + '<\/td>' +
'<td>' + data[i].emp_account_number + '<\/td>' +
'<td>' +
'<input type="text" class="form-control" name="attendance" placeholder="Attendance" required>' +
'<\/td>' +
'<td>1<\/td>' +
'<td>' +
'<input type="text" class="form-control" name="loan" placeholder="Loan" required>' +
'<\/td>' +
'<td>' +
'<a href="javascript:;" class="btn btn-primary item-edit" id="btnSave">Submit<\/a>' +
'<\/td>' +
'<\/form>' +
'<\/tr>';
}
$('#salaryData').html(html);
// $('#salaryData').html(data);
},
error: function() {
alert('No Data');
}
});
}
});
});
//insert data to salary table
$('#salaryData').on('click', '.item-edit', function() {
$('#myform').attr('action', '<?php echo base_url() ?>con_salary/addSalary');
var url = $('#myform').attr('action');
var data = $('#myform').serialize();
var attendance = $('input[name=attendance]');
var loan = $('input[name=loan]');
$.ajax({
type: 'ajax',
method: 'POST',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response) {
},
error: function() {
}
});
});
</script> <?php include "template/footer.php"; ?>
// controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Con_salary extends CI_Controller
{
public function __construct(){
parent:: __construct();
$this->load->model('queries_salary');
}
public function index()
{ $data['categories'] = $this->queries_salary->fetchCategory();
$this->load->view('employee_salary_view',$data);
}
public function add_salary_for_employee()
{
$designation_id=$this->input->post('user_designation');
$users = $this->queries_salary->fetchEmployeeforsalary($designation_id);
echo json_encode($users);
}
public function addSalary()
{
$result = $this->queries_salary->addSalary();
// $msg['success']=false;
// $msg['type']='add';
// if($result){
// $msg['success']=true;
// }
// echo json_encode($msg);
}
//end
}
?>
// model
<?php
class Queries_salary extends CI_Model
{
public function fetchCategory()
{
$query= $this->db->get('category');
return $query->result_array();
}
public function fetchEmployeeforsalary($designation_id)
{
$this->db->where('emp_designation_id',$designation_id);
$this->db->join('category','employee.emp_designation_id = category.cat_id');
$query=$this->db->get('employee');
if($query->num_rows()>0){
return $query->result();
}
else{
return false;
}
// $this->db->where('emp_designation_id',$designation_id);
// $query=$this->db->get('employee');
}
public function addSalary()
{
$field = array(
'salary_attendance'=>$this->input->post('attendance'),
'salary_loan'=>$this->input->post('loan')
);
print_r($field);
exit();
// $this->db->insert('salary',$field );
// if($this->db->affected_rows()>0)
// {
// return true;
// }
// else{
// return false;
// }
}
//end
}?>
A form is not allowed to be a child of a table, tbody or tr HTML elements.
If attempting to put one there will tend to cause the browser to move the form to it appears after the table.So in your case form results an empty data.
Here i adjusted code your code little bit and will work for you.
for (i = 0; i < data.length; i++) {
html += '<tr class="user_data" >' +
'<td>' + data[i].emp_name + ' <\/td>' +
'<td>' + data[i].cat_name + '<\/td>' +
'<td>' + data[i].emp_account_number + '<\/td>' +
'<td>' +
'<input type="text" class="form-control attendance" name="attendance" placeholder="Attendance" required>' +
'<\/td>' +
'<td>1<\/td>' +
'<td>' +
'<input type="text" class="form-control loan" name="loan" placeholder="Loan" required>' +
'<\/td>' +
'<td>' +
'<a href="javascript:;" class="btn btn-primary item-edit" id="btnSave">Submit<\/a>' +
'<\/td>' +
'<\/tr>';
}
Bottom side script
$('#salaryData').on('click', '.item-edit', function() {
var url = '<?php echo base_url() ?>con_salary/add_salary_for_employee';
var current_row = $(this).closest('.user_data');
var data = { attendance: current_row.find('.attendance').val(), loan: current_row.find('.loan').val() };
$.ajax({
type: 'ajax',
method: 'POST',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response) {
},
error: function() {
}
});
});
One important note is that if you are using single form and using same type of input with same name use it as Array.
Eg : name="loan[]"

How to insert value (codeigniter)

help please
I just learned codeigniter, I have a problem when inserting data.
I want to input or insert data that is looking for from the database, for example can be seen in the picture.
when I insert it into the database, the error message is the data that I inserted NULL
Search by kode
{
"result":
[
{
"id_runsheet":"6",
"kd_runsheet":"RUNSHEET-0000-0003",
"reciver_name":"arif",
"tracking_number":"RJC-0000-0003",
"status":"Consignee Unknown",
"id_runsheet_detail":"6",
"id_outdes":"3"
},
{
"id_runsheet":"6",
"kd_runsheet":"RUNSHEET-0000-0003",
"reciver_name":"hendra",
"tracking_number":"RJC-0000-0004",
"status":"Closed",
"id_runsheet_detail":"6",
"id_outdes":"3"
}
]
}
Controller
public function cari(){
$id=$_POST['kd_runsheet'];
$data['result']=$this->M_inbound_undel->caridb($id);
echo json_encode($data);
}
Model
public function save(){
$data = array(
'id_runsheet' => $this->input->post('id_runsheet'),
'id_runsheet_detail' => $this->input->post('id_runsheet_detail'),
'id_outdes' => $this->input->post('id_outdes')
);
$this->M_inbound_undel->db_save($data);
echo $this->session->set_flashdata('message','success');
redirect('backend/inbound_undel');
}
View
<form class="form-signin" method="post" action="<?php echo base_url().'backend/inbound_undel/save';?>">
<div class="box">
<div class="box-header">
<div class="row">
<div class="form-group col-md-2">
<label for="field-1" class="control-label">Tanggal</label>
<input name="" value="<?php echo(date('Y-m-d H:i:s')) ?>" class="form-control" type="text" placeholder="" readonly required="">
</div>
<div class="form-group col-md-4">
<label for="field-1" class="control-label">KODE RUNSHEET</label>
<input name="kd_runsheet" class="form-control" id="kode" type="text" placeholder="Masukan Kode Runsheet" style="" required="">
<span style="font-size:11px; color:#00a65a;">No resi hanya bisa tampil apabila resi sudah di Inbound</span>
</div>
</div>
</div>
</div>
<div class="box">
<div class="box-body">
<table id="databel" class="table table-bordered table-striped" style="width: 100%; cellspacing: 0;">
<thead>
<tr>
<th>Kode Runsheet</th>
<th>Kode Resi</th>
<th>Penerima</th>
<th>status terakhir</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
<div class="box-footer">
<button type="submit" class="btn bg-orange btn-flat margin">Simpan</button>
</div>
</div>
</div>
</form>
AJAX
$(document).ready(function(){
$('#kode').on('input',function(){
var kode=$(this).val(); //serach by kode
$.ajax({
url : "<?php echo base_url('backend/inbound_undel/cari')?>",
type: 'POST',
dataType: 'JSON',
data : {kd_runsheet: kode},
success:function (data) {
//result
var result = data.result;''
var row = "";
for(i=0; i < result.length; i++) {
row += "<tr>";
row += "<td>"+result[i].kd_runsheet+"</td>";
row += "<td>"+result[i].tracking_number+"</td>";
row += "<td>"+result[i].reciver_name+"</td>";
row += "<td class='label bg-red'>"+result[i].status+"</td>";
row += "</tr>";
}
$('#tbody').html(row);
}
});
event.preventDefault();
});
});
when I insert it into the database, the error message is the data that I insert all NULL
It happens because your save() model expected 3 post parameters to be received, yet none of them are present.
After looking at the returned json data that you've provided, you could make a hidden input for each of the required save() parameters :
<script>
$(document).ready(function() {
$('#kode').on('input', function() {
var kode = $(this).val(); //serach by kode
$.ajax({
url: "<?php echo base_url('backend/inbound_undel/cari') ?>",
type: 'POST',
dataType: 'JSON',
data: {
kd_runsheet: kode
},
success: function(data) {
//result
var result = data.result;
var row = "";
for (i = 0; i < result.length; i++) {
row += "<tr>";
row += "<td>" + result[i].kd_runsheet + "</td>";
row += "<td>" + result[i].tracking_number + "</td>";
row += "<td>" + result[i].reciver_name + "</td>";
row += "<td class='label bg-red'>" + result[i].status + "</td>";
row += "</tr>";
}
$('#tbody').html(row);
// begin appended hidden inputs
let input = "";
for (i = 0; i < result.length; i++) {
input += "<input type='hidden' name='id_runsheet' value='" + result[i].id_runsheet + "' />";
input += "<input type='hidden' name='id_runsheet_detail' value='" + result[i].id_runsheet_detail + "' />";
input += "<input type='hidden' name='id_outdes' value='" + result[i].id_outdes + "' />";
}
$('#databel').html(input);
// end appended hidden inputs
}
});
event.preventDefault();
});
});
</script>