How to push Json object to Json array using for loop? - javascript

I have a html table where onclick dynamically rows added. I need to convert that row textbox values into JSON array.
Note: Ajax must be used because I need to save data to sql server.
Here is my attempt.
$(function() {
$("[id*=btnSave]").click(function() {
$("[id*=data_table] tbody").each(function() {
var arr = [];
var user = {};
for (i = 0; i <= 1; i++) {
user.DueDate = $(this).find('tr:eq(' + i + ') td:eq(0) input').val();
user.DueAmount = $(this).find('tr:eq(' + i + ') td:eq(1) input').val();
arr.push(user); // Json array has every json object value
$.ajax({
async: true,
cache: false,
type: "POST",
url: "Default.aspx/Save",
data: JSON.stringify(user),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert("Data added successfully.");
alert(JSON.stringify(user)); //Json object value //Alert 2
alert(JSON.stringify(arr)); //Json array value //Alert 3
}
}); //End of ajax
return false;
} //End of for loop
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table cellspacing="3" cellpadding="3" id="data_table" width="50%">
<thead>
<tr>
<th width="30%">Due date</th>
<th width="26%">Amount Due</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td width="30%">
<input type="text" id="Text1" autocomplete="off" placeholder="Due Date" runat="server" />
</td>
<td width="25%">
<input type="text" runat="server" id="new_Amount_1" placeholder="0.00" autocomplete="off" />
</td>
<td>
<input type="button" value="Delete" />
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<input type="button" value="Add row" id="btnAddRow" />
<input type="button" value="Save" id="btnSave" />
</td>
</tr>
</tfoot>
</table>
I used for loop to get every dynamically added row values.
My output should be like this.
Alert2 Json object format
{"DueDate":"17/09/2019","DueAmount":"100"}
Alert3 Json array format
[{"DueDate":"17/09/2019","AmountDue":"100"},{"DueDate":"18/09/2019","AmountDue":"200"},{"DueDate":"19/09/2019","AmountDue":"300"}]
But in My output Alert3 I am getting first object only
[{"DueDate":"17/09/2019","DueAmount":"100"}]
What I have done wrong? I think for loop is not correct. Please help me with that.

Yes, you can use .serialize() or .serializeArray() and these two functions only runs on a form tag.
In your code if you are adding tr tag each time that you press btnAddRow, your for loop is wrong:
for (i = 0; i <= 1; i++)
Replace with:
for (i = 0; i <= $(this).find('tr').length; i++)

Instead of looping this, you can directly use the serializeArray or serialize if you need a custom format
$("form").on("submit", function(event) {
event.preventDefault();
console.log($(this).serializeArray());
$.ajax({
async: true,
cache: false,
type: "POST",
url: "Default.aspx/Save",
data: JSON.stringify($(this).serializeArray()),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
console.log("Data added successfully.");
}
}); //End of ajax
});
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<form>
<table cellspacing="3" cellpadding="3" id="data_table" width="50%">
<thead>
<tr>
<th width="30%">Due date</th>
<th width="26%">Amount Due</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td width="30%">
<input type="text" name="Text1" autocomplete="off" placeholder="Due Date" runat="server" />
</td>
<td width="25%">
<input type="text" runat="server" name="new_Amount_1" placeholder="0.00" autocomplete="off" />
</td>
<td>
<input type="button" value="Delete" />
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<input type="button" value="Add row" id="btnAddRow" />
<input type="submit" value="Save" id="btnSave" />
</td>
</tr>
</tfoot>
</table>
</form>

Related

How to select all checkboxes without changing var parameters

I using ViewModel and I have table with checkboxes, I can only check one by one boxes, but I need check all option but I need my var values to be defined, because I pass that values to controller and do something.
$('.checktip').click(function () {
var idemployee = $('.idemployee').val();
var idtip= $(this).attr('idtip');
var chk = $(this).prop('checked');
$.ajax({
url: UrlSettingsDocument.Books,
data: { idemployee: idemployee, idtip: idtip, chk: chk },
type: "POST",
success: function (result) {
if (result.result == "Redirect") {
window.location = result.url;
}
}
});
});
My .cshtml
<table class="table table-striped grid-table">
<tr>
<th>Samp</th>
<th>Id of Book</th>
<th>
//Button for check all *(NOT IMPLEMENTED)*
<button type="button" class="checkall">Select/Deselect</button>
</th>
</tr>
#foreach (var item in (IEnumerable<cit.Models.getCheIdTip_Result>)Model)
{
<tr>
<td>#item.idtip</td>
<td>#item.tipname</td>
<td>
<div class="pure-checkbox">
<input type="checkbox" idtip="#item.idtip" class="checktip" checked="#(item.idemployee == ViewBag.idemployee ? true : false)" name="#item.id.ToString()" id="#item.id.ToString()" />
<label for="#item.id.ToString()"></label>
</div>
</td>
</tr>
}
</table>
<input type="hidden" value="#ViewData["idemployee"]" name="idemployee" id="idemployee" class="idemployee" />
</div>
Use check box to check all checkbox instead of button.
On check change, using the class check/uncheck all checkbox inside the table.
$('#checkall').on('change', function() {
$('.checktip:checkbox').prop('checked', $(this).is(":checked"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-striped grid-table">
<tr>
<td><input type="checkbox" id="checkall" />Check All</td>
<td><input type="checkbox" class="checktip" /></td>
</td>
</td>
</td>
<td><input type="checkbox" class="checktip" /></td>
</td>
</td>
<td><input type="checkbox" class="checktip" /></td>
</td>
<td><input type="checkbox" class="checktip" /></td>
</tr>
</table>

Universal form submitting function for all forms in a page

I'm trying to write a universal jquery function to submit all forms in a table when their submit button is clicked.
What I've got so far is this:
<div class="tabelaportes">
<div class="galltitle">Tabela de Portes de Envio</div>
<table cellpadding="0" cellspacing="0" border="1">
<tr>
<td class="tdleft">Peso inicial (kg) </td>
<td class="tdleft">Peso final (kg) </td>
<td class="tdleft">Valor (€) </td>
<td class="tdleft">Acção</td>
</tr>
<tr>
<td class="tdright">
1.00 kg
</td>
<td class="tdright">
2.00 kg
</td>
<td class="tdright">
3.00 €
</td>
<td class="tdright">
<form method="post">
<input type="hidden" name="kgid" value="34"/>
<input type="submit" name="rmkgid" value="Remover"/>
</form>
</td></tr>
<tr>
<td class="tdright">
3.00 kg
</td>
<td class="tdright">
4.00 kg
</td>
<td class="tdright">
5.00 €
</td>
<td class="tdright">
<form method="post">
<input type="hidden" name="kgid" value="56"/>
<input type="submit" name="rmkgid" value="Remover"/>
</form>
</td></tr>
<tr>
<form method="post">
<td>
<input type="text" name="kg_i"/>
</td>
<td>
<input type="text" name="kg_f"/>
</td>
<td>
<input type="text" name="kg_p"/>
</td>
<td>
<input type="submit" name="addprice" value="Adicionar"/>
</td>
</form>
</tr>
</table>
</div><script>
function submitPortes() {
var siteurl = window.location.href;
$("form").submit(function(sp) {
//get form values
var submitname = $(this).parents("tr").find("input[type=submit]").attr("name");
var submitval = $(this).parents("tr").find("input[type=submit]").val();
var dataString = $(this).serialize() + "&"+ submitname + "="+ submitval;
console.log("dataString: " + dataString);
//submit form
$.ajax({
type: "POST",
url: siteurl,
data: dataString,
success: function(){
$.ajax({
url: siteurl,
type:"GET",
success: function(portes){
//reload page
var reloadPortes = $(portes).find("div.tabelaportes table").html();
$("div.tabelaportes table").hide().html(reloadPortes).fadeIn("fast");
//reload form to add more
submitPortes();
}
});
}
});
return false;
});
}
submitPortes();
</script>
So, in this case all the forms are in a table. Each row has its own form to remove a row and in the last row, you add rows to the table.
The function submits the forms and reloads the table.
When removing a row, the function works every time, but when adding a row, it only works the first time. What can I do to make it work every time?
Is it even possible to have one function for all forms?
I'm not quite sure what you mean by "It only works the first time". but perhaps try registering the event at the table level, so that it will be re-evaluated to include the addition of more form elements.
$('#tabelaportes').on('submit', 'form', function(){...});
(note: this may not work with your initialization pattern, perhaps move init inside a $(document).ready( function() {}); block?)

iQuery ajax request returns empty $_POST

I'm creating a table containing a list of uploaded files and I wanted to add a link in the last column to allow the user to delete the corresponding file. I could simply use a link "delete.php?fileid=", but I prefer to use a POST request and so I decided to use a form with the ID of the file in the database being passed as hidden input.
Issue: console.log($(this).closest('form').find(":input").serialize()); returns an empty string. Can you help understanding what is the root cause?
Code of form submission:
$('.f-delete a'). click(function(e){
e.preventDefault();
console.log($(this).closest('form').find(":input").serialize());
$.ajax({
type: "POST",
url: 'delete_image.php',
dataType: 'json',
data: $(this).closest('form').find(":input").serialize(),
success: function(response){
console.log(response);
},
error: function(){
alert('Error: Could not delete the file');
}
});
});
The markup:
<table class="table table-striped">
<thead>
<tr>
<th>Title</th>
<th>Type</th>
<th>Size</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>Test file</td>
<td>image/png</td>
<td>302.65 KB</td>
<td>
<form id="f-1" class="f-delete" method="post" action="delete_image.php">
<input id="id-1" value="1" type="hidden">
<a id="a-1" href="">Delete image</a>
</form>
</td>
</tr>
<tr>
<td>Test file 2</td>
<td>image/png</td>
<td>37.88 KB</td>
<td>
<form id="f-2" class="f-delete" method="post" action="delete_image.php">
<input id="id-2" value="2" type="hidden">
<a id="a-2" href="">Delete image</a>
</form>
</td>
</tr>
</tbody>
</table>
The problem is in your html, for use serialize your input's should have name. For example:
<input id="id-1" value="1" name="id-1" type="hidden">
For serialize use
$(this).closest('form').serialize() //return id-1=1
Result https://jsfiddle.net/cmedina/1Lv8gkms/

input text is not validated by codeigniter

I have a password change form and when submit it only two inputs are validated and input with name "confirm-new-password" is not validated. what is my wrong?
please help me.
HTML and JS CODE
$(function($) {
$.fn.ajaxForm = function(url, data, msgHolderId) {
var self = this;
var result;
return $(self).bind('submit', function(e) {
e.preventDefault();
if (data != null)
data = "&" + $.param(data);
alert(data);
$.ajax({
url: '<?= base_url() ?>' + url,
async: false,
cache: false,
data: $(self).serialize() + data,
type: 'POST',
dataType: 'json',
success: function(response) {
$('#' + msgHolderId).html(response.msg);
}
});
});
}
}(jQuery));
$(document).ready(function() {
$('#password-change-form').ajaxForm('user/settings/password_change', null, 'msg-holder');
});
MY HTML FORM
<form id="password-change-form">
<table class="table table-bordered table-responsive table-condensed table-hover">
<tr>
<td colspan="3" style="background-color: #e8e8e8">Password Update</td>
</tr>
<tr>
<td style="width:20%">Current password</td>
<td style="width:50%"><input type="password" class="form-control" name="current-password" id="current-password" /></td>
<td></td>
</tr>
<tr>
<td style="width:20%">New Password</td>
<td style="width:50%"><input type="password" class="form-control" name="new-password" id="new-password" /></td>
<td></td>
</tr>
<tr>
<td style="width:20%">Confirm new password</td>
<td style="width:50%"><input type="password" class="form-control" name="confirm-new-password" id="confirm-new-password" /></td>
<td></td>
</tr>
<tr>
<td style="width:20%"></td>
<td colspan="2" style="width:50%"><input type="submit" class="btn btn-default" value="ذخیره تغییرات" /></td>
</tr>
</table>
</form>
SERVER SIDE CODE
$this->form_validation->set_rules('current-password', 'A', 'trim|callback_password_check');
$this->form_validation->set_rules('new-password', 'B', 'trim|required|min_length[8]');
$this->form_validation->set_rules('confirm-new-password', 'C', 'trim|matches[new-password]');
if($this->form_validation->run())
$this->Common_db_actions_model->update_data('users' ,array('password' => $hash_new_password) ,array('user_id' => $this->active_user['user_id']));
try this
$this->form_validation->set_rules('password', 'Password', 'required|matches[confirm-new-password]');
$this->form_validation->set_rules('confirm-new-password', 'Password Confirmation', 'required');
Try this code:
$this->form_validation->set_rules('current_pwd', 'Current password','required');
$this->form_validation->set_rules('new_pwd', 'New password' ,'required|min_length[6]|max_length[20]');
$this->form_validation->set_rules('confirm_pwd', 'Confirm password','required|matches[new_pwd]');
Then change your input name.

Knock javascript returns nulls to save function

Im new to using Knockout for data-binding and MVC, I can retrieve data just fine returning in a Json object, but when I attempt to return user data back and selections to save my values are null. If I separate remove saveContent div and place the save button control in the searchAudio div then I the user input data is returned but I need to return all the form data that the user selects and inputs.
<form action="AudioLookup" method="get" enctype="multipart/form-data">
<div id="saveContent" data-bind="with: saveContent">
<div id="allAudio" data-bind="with: $root.allAudio">
<h3>Audio Playback</h3>
<table>
<thead>
<tr>
<th>Bind Audio</th>
<th>ID</th>
<th>Text</th>
<th>Url</th>
<th>File Name</th>
<th>Prompt Type</th>
</tr>
</thead>
<tbody data-bind="foreach: AudioResults">
<tr>
<td><input type="radio" name="adgroup"/></td>
<td data-bind="text : _id"></td>
<td ></td>
<td data-bind="text: aUrl"></td>
<td data-bind="text: fileName"></td>
<td data-bind="text: PromptType"></td>
</tr>
</tbody>
</table>
<button data-bind="click: getAllAudio">Get Audio</button>
</div>
<br />
<hr />
<div id="searchAudio" data-bind="with: $root.searchAudio">
<h3>Refine Audio Lookup</h3>
<label for="CallCenterDLL">Choice Call Center: </label>
<select id="CallCenterDLL" data-bind ="value: searchfields.CCCode" name="CallCenterT">
<option value =""></option>
<option value = "11">Kansas City</option>
<option value = "6">Dallas</option>
<option value = "7">Houston</option>
<option value = "8">SanAntonio</option>
<option value = "12">Charlotte</option>
<option value = "9">Raleigh</option>
</select>
<div>
<label for="RBgroup">Choice Prompt Type: </label>
<br/>
<input type="radio" name="RBgroup" value='3' data-bind ="checked: searchfields.searchType"/> Agent<br/>
<input type="radio" name="RBgroup" value='4' data-bind ="checked: searchfields.searchType"/>Office<br/>
</div>
<input type="text" name="serchTxt" placeholder="search string Here" data-bind="value: searchfields.searchVal" onblur="minleng(this.value,25);Minimum(this,3);" onkeypress="minleng(this.value,25)" />
<button data-bind="click: runQuery">Search Data</button>
#* <div id="select-all" data-bind="with: $root.select-all"> *#
<table>
<thead>
<tr>
<th>
<input type="checkbox" name="select-all" id="select-all"/>Select All
</th>
</tr>
</thead>
<tbody data-bind="foreach: dataResult">
<tr>
<td><input data-bind="value: PK" class="selectedPK" type="checkbox" /></td>
<td data-bind="text: PKType"></td>
<td data-bind="text: DisplayVal"></td>
</tr>
</tbody>
</table>
#*</div>*#
</div>
<button data-bind="click: SaveQuery">Save Data</button>
</div>
</form>
function saveViewModel() {
var self = this;
var SviewModel = function (CCCode, PK, PKType, SearchType, SearchVal, Text, fileName, aUrl) {
self.searchfields.CCCode = ko.observable(CCCode);
self.searchfields.searchType = ko.observable(SearchType);
self.searchfields.searchVal = ko.observable(SearchVal);
self.PK = ko.observable(PK);
self.PKType = ko.observable(PKType);
self.Text = ko.observable(Text);
self.fileName = ko.observable(fileName);
self.aUrl = ko.observable(aUrl);
}
self.state = ko.observable();
self.dataResult = ko.observableArray();
self.SaveQuery = function () {
alert(ko.toJSON(SviewModel));
$.ajax(
{
url: "/CallCenter/SaveQuery",
contentType: "application/json",
type: "POST",
dataType: "json",
data: ko.toJSON(self.dataResult),
success: function (data) {
self.SaveResult(data);
}
});
}
}
you alert :-
alert(ko.toJSON(SviewModel));
the data you send :-
data: ko.toJSON(self.dataResult),
and that is :-
self.dataResult = ko.observableArray();
which seems unused.... so not too surprising everything is null

Categories

Resources