Ajax not sending data as parameters - javascript

I'm trying to send an array via ajax so I have the following code:
Here is the code
function fncGetChecksToProcess() {
var allChecks = [];
$('input[type=text]').each(function() {
var key = $(this).attr("id").replace("txt_", "");
allChecks[key] = [];
});
$('input[type=checkbox]').each(function() {
if (this.checked) {
var className = $(this).attr('class');
if (className.includes('box_total_')) {
var ref = $(this).attr('id').replace("box_total_", "");
var amountDetails = [];
var docNs = [];
$('.' + ref).each(function() {
amountDetails.push(parseFloat($(this).closest('td').next().html().replace("$", "").replace(",", "")));
docNs.push($(this).attr('id').replace("box_", ""));
});
allChecks[ref].push({
docN: docNs,
amountTot: $("#sub_" + ref).text(),
amountDetails: amountDetails,
chkNum: $("#txt_" + ref).val()
});
} else {
var docN = $(this).attr('id').replace("box_", "");
allChecks[className].push({
docN: docN,
amountTot: $("#td_" + docN).text(),
amountDetails: "",
chkNum: $("#txt_" + className).val()
});
}
}
});
return allChecks;
}
$(document).ready(function() {
$("#btn").click(function() {
var checks = fncGetChecksToProcess();
console.log(checks);
$.ajax({
cache: false,
type: 'POST',
data: {
allChecks: checks
},
url: '/process',
beforeSend: function() {
console.log("Processing your checks please wait...");
},
success: function(response) {
console.log(response);
},
error: function() {
console.log("Error");
}
});
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="app.js"></script>
</head>
<body>
<table id="table" class="tablesorter" width="100%" cellspacing="0">
<thead>
<tr>
<th>H1</th>
<th>H2</th>
<th>H3</th>
<th>H4</th>
<th>H5</th>
<th></th>
<th>H6</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
<td>11002WR</td>
<td>201100</td>
<td>A</td>
<td class="center"><input class="11002WR" id="box_201100" type="checkbox" /></td>
<td id="td_201100">$320.00</td>
</tr>
<tr>
<td colspan="3"></td>
<td>Check. No</td>
<td><input id="txt_11002WR" type="text"></td>
<td><input id="box_total_11002WR" class="box_total_201100" type="checkbox" /></td>
<td id="sub_11002WR">$12.00</td>
</tbody>
</table>
<input id="btn" type="button" value="Test" />
</body>
</html>
Please check the two checkboxes and the input and press on the test.
The console prints out the array generated but Ajax does not send it.
Why my ajax call does not send any parameters? I don't see them in chrome console.
Thanks.

Since your keys are strings, not numbers, you should be using an object, not an array. Change
var allChecks = [];
to
var allChecks = {};
When you send an array with $.ajax, it only sends the elements with numeric indexes, not named properties.

You need to send an array to ajax , now you send an array of array inside array...
if you post to the server like form the post will looks like:
allchecks[] = x
allchecks[] = y ...
https://plnkr.co/edit/SnZmKgRLODYb8p6kPryn?p=preview
$.ajax({
cache: false,
type: 'POST',
data: {
allChecks: checks["11002WR"][0]
},
this is a fast solution for you . but it is not a good practice
instead of allchecks=[] . try to build objects with keys or ids and not string like the ref as a key of the array
objects is like the following :
var allChecks = {};

Related

jQuery sortable serialize not recognizing dynamically added content

I am trying to re-order a list via ajax on sortable update, however after adding a new item to this list via ajax after sortable has already been initialized on page load, it does not recognize the new item with the "serialize" function. It does allow me to drag it around as though it is working, but the code that gets sent with my update function is missing the new element.
//Sort categories
$('#categories-list').find('tbody').sortable({
connectWith: 'tbody',
opacity: 0.6,
cursor: 'move',
forcePlaceholderSize: true,
update: function(e) {
var serialized = $('#categories-list tbody').sortable('serialize');
console.log(serialized);
$.post('admin/ereg_forms/set_category_position', serialized, function(data) {
if (data.status == 'error') {
alert(data.message);
}
});
}
});
//Add category submit
$("#add-category-submit").click(function(e) {
e.preventDefault();
$(".errors-block").html('');
$('#add-category-submit').hide();
$.ajax({
url: $("#add-category-form").attr('action'),
type: 'POST',
data: $('#add-category-form').serialize(),
dataType: 'json',
success: function(data) {
$('#add-category-submit').show();
//Check if server side validation passed
if (data.status == 'error') {
//Show error on popup dialog
$("#add-category-form .errors-block").html(data.message);
alert('Sorry, the information that was sent is invalid. Please review the errors at the top of the form and try again.');
} else {
var category_data = data.data;
var tableRow = '<tr class="category-row-' + category_data.id + '"><td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span>' +
'</td><td>' + category_data.title +
'</td><td></tr>'
$(tableRow).appendTo('#categories-list tbody');
resetForm($('#add-category-form'));
//Close popup window
$('#add-category').dialog('close');
$("<div title='Success!'>Category has been saved.</div>").dialog({
modal: true,
width: 'auto'
});
}
},
error: function(data) {
alert('An unknown error has occurred, please try again.');
$('#add-category-submit').show();
}
});
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<table class="data" id="categories-list">
<thead>
<tr>
<th> </th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr id="category-row-19">
<td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td>
<td class="category-row-title">test1</td>
</tr>
<tr id="category-row-20">
<td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td>
<td class="category-row-title">test</td>
</tr>
</tbody>
</table>
I have looked everywhere for a solution but have not found one that has worked. I have tried using the "refresh" function with sortable, I have tried initializing sortable inside of the success function of the ajax call to add new categories but it also does not work.
when I console.log(serialized) it only has the originally loaded elements in the array.
IDK what is going on, but this fake add works, perhaps you can emulate this? Note I cleaned up a couple syntax issues and used the ajax promise methods to better organize it.
I suggest you update your jQuery version, some better stuff in more recent versions with bug fixes.
//Sort categories
$('#categories-list').find('tbody').sortable({
connectWith: 'tbody',
opacity: 0.6,
cursor: 'move',
forcePlaceholderSize: true,
update: function(e) {
var serialized = $('#categories-list tbody').sortable('serialize');
console.log(serialized);
// $.post('admin/ereg_forms/set_category_position', serialized, function(data) {
// if (data.status == 'error') {
// alert(data.message);
// }
// });
}
});
$('#addmorefool').on('click', AddMore);
function AddMore() {
let tbody = $('#categories-list').find('tbody');
let rowscount = tbody.find('tr').length;
let newRow = '<tr id="category-row-' + rowscount + '"><td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td><td class="category-row-title">test' + rowscount + '</td></tr>';
tbody.append(newRow);
}
AddMore();
//Add category submit
$("#add-category-sumbit").on('click', function(e) {
//console.log("howdy");
e.preventDefault();
var myform = $("#add-category-form");
var errorBlock = myform.find(".errors-block");
errorBlock.html('');
errorBlock.dialog({
modal: true,
width: 'auto',
autoOpen: false
});
var catSub = $('#add-category-submit');
catSub.hide();
var myjax = $.ajax({
url: myform.attr('action'),
type: 'POST',
data: myform.serialize(),
dataType: 'json'
})
.done(function(data) {
catSub.show();
//Check if server side validation passed
var category_data = data.data;
var tableRow = $('<tr class="category-row-' + category_data.id + '"><td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span>' +
'</td><td>' + category_data.title +
'</td><td></tr>');
let tbody = $('#categories-list').find('tbody');
tbody.append(tableRow);
resetForm(myform);
//Close popup window (out cause have none)
//('#add-category').dialog('close');
$("<div title='Success!'>Category has been saved.</div>").dialog({
modal: true,
width: 'auto'
});
}).fail(function(data) {
//Show error on popup dialog
errorBlock.html('<span>Sorry, the information that was sent is invalid. Please review the errors at the top of the form and try again.</span>' + data.message);
errorBlock.dialog("open");
//catSub.show(); (out cause not in code)
});
});
tr td {
border: 1px solid lime;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<div id="add-category-form" action="metoo">I am an empty form, so what
<div class="errors-block">me error aggain? no way</div>
</div>
<table class="data" id="categories-list">
<thead>
<tr>
<th> </th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr id="category-row-19">
<td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td>
<td class="category-row-title">test1</td>
</tr>
<tr id="category-row-20">
<td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td>
<td class="category-row-title">test</td>
</tr>
</tbody>
</table>
<button id="addmorefool" type="button">Add More</button>
<div class="errors-block">me error</div>
<button type="button" id="add-category-sumbit">add category</button>
I ended up solving this problem, the issue was in the add category function I was applying the "class" attribute instead of using the "id" attribute for the category-row-{id}.

jQuery DataTables filter rows based on multiple values

I am trying to have multiple filters that will hide/show rows on my datatable based on which filters are selected. My plan is to place the filter values in an array and compare those to the data-search attribute in the first column, but what I currently have does not work.
Here's a JSfiddle that I have plus code below
https://jsfiddle.net/dmcgrew/06j4pxjk/3/
HTML with checkboxes for filters and the table data..
<label>
<input type="checkbox" name="cat" value="cat" class="filter"> Cats
</label>
<label>
<input type="checkbox" name="dog" value="dog" class="filter"> Dogs
</label>
<table class="select_items">
<thead>
<tr>
<th>Item</th>
<th>Description</th>
<th>Crest Allowed</th>
<th> </th>
</tr>
</thead>
<tbody>
<tr>
<td data-search="cat">1</td>
<td>Testing Bowl</td>
<td>NO</td>
<td><button class="button">Select</button></td>
</tr>
<tr>
<td data-search="dog">32</td>
<td>Cup Test</td>
<td>NO</td>
<td><button class="button">Select</button></td>
</tr>
<tr>
<td data-search="dog">3335</td>
<td>Bowl Test</td>
<td>NO</td>
<td><button class="button">Select</button></td>
</tr>
</tbody>
</table>
The JS..
var select_items = $('.select_items').DataTable();
var filters = [];
$('input.filter').on('change', function(){
var filters = [];
$("input.filter:checked").each(function(){
var checkedBox = $(this).val();
if (filters.indexOf(checkedBox) === -1){
filters.push(checkedBox);
}
});
console.log(filters);
if(this.checked){
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex){
return (data[0].indexOf(filters) > -1) ? true : false;
}
);
}
select_items.draw();
if(this.checked){
$.fn.dataTable.ext.search.pop();
}
});
Considering, accepted answer refers to legacy interface fnFilter and, as of DataTables 1.10 new API is suggested, I'll allow myself to provide more up to date solution, which is, in my opinion, way more scalable, neat and simple:
//define statical data
var srcData = [
{search: 'Cat', item: '1', descr: 'Testing Bowl', crest: 'NO'},
{search: 'Dog', item: '32', descr: 'Cup Test', crest: 'NO'},
{search: 'Dog', item: '3335', descr: 'Bowl Test', crest: 'NO'},
];
//define dataTable object
var dataTable = $('#mytable').DataTable({
sDom: 't',
data: srcData,
columns: [
{title: 'Item', data: 'item'},
{title: 'Description', data: 'descr'},
{title: 'Crest Allowed', data: 'crest'},
]
});
//put in place dynamically created checkboxes
var searchValues = [];
dataTable.data().sort().toArray().forEach(row => {
if(searchValues.indexOf(row.search)==-1) searchValues.push(row.search);
});
var checkboxes = searchValues.reduce((html, item) => html += `<input type="checkbox" value="${item}" class="filter">${item}</input>`,'');
$(checkboxes).insertBefore($('#mytable'));
//employ $.fn.DataTable.ext.search
var lookupValues = [];
$.fn.DataTable.ext.search.push((settings, row, index, rowObj) => lookupValues.indexOf(rowObj.search) > -1 || lookupValues.length == 0);
//watch checkboxes and redraw table on change accordingly
$(".filter").on('change', () => {
lookupValues = [...$('.filter:checked')].map(checkbox => $(checkbox).val());
dataTable.draw();
});
<!doctype html>
<html>
<head>
<script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<table id="mytable"></table>
</body>
</html>
I made a few changes in your code, using the fnFilter API:
Documentation: https://datatables.net/docs/DataTables/1.9.0/DataTable.html#fnFilter
$(function() {
otable = $('.select_items').dataTable();
})
function filterme() {
//build a regex filter string with an or(|) condition
var types = $('input:checkbox[name="filter"]:checked').map(function() {
return '^' + this.value + '\$';
}).get().join('|');
//filter in column 0, with an regex, no smart filtering, no inputbox,not case sensitive
otable.fnFilter(types, 0, true, false, false, false);
}
You can see it working here: JSFiddle demo
You have to check for the filter length.
If there is no filter, the $.fn.dataTable.ext.search.push function has to return true for ALL rows.
And, I think that search.pop() should apply on uncheck too...
var select_items = $('.select_items').DataTable();
$('input.filter').on('change', function(){
var filters = [];
$("input.filter:checked").each(function(){
var checkedBox = $(this).val();
if (filters.indexOf(checkedBox) === -1){
filters.push(checkedBox);
}
});
console.log(filters.length);
$.fn.dataTable.ext.search.push(function(settings, data, dataIndex){
if(filters.length>0){
return (data[0].indexOf(filters) > -1) ? true : false;
}else{
return true;
}
});
select_items.draw();
$.fn.dataTable.ext.search.pop();
});
Updated Fiddle

Pass html table in POST using jQuery

I have an html page and I need to send the contents of a table in a POST.
How do I capture the content of the table using jQuery and pass it to the server (which is running node.js and express.js)?
This is the example of a table in a page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test</title>
<script src="scripts/jquery-3.2.1.min.js"></script>
</head>
<body>
<table id=horarios>
<tr>
<td>1 </td>
<td>2 </td>
<td>3 </td>
</tr>
<tr>
<td>4 </td>
<td>5 </td>
<td>6 </td>
</tr>
</table>
<form method=post>
<input type="submit" value="Save">
</form>
</body>
</html>
In the server I would capture that POST with something like:
var bodyParser = require('body-parser');
app.use( bodyParser.json() );
app.use( bodyParser.urlencoded({ extended: true }));
app.post('/mypage', function(req, res){
var content = req.body;
res.render('somepage');
});
You want to send a POST request with body set to $('#horarios').html()
You can do this with jQuery.post()
$.post(url, data, success, respType)
where data is the html string of your table, success is a callback if the server sends a success response, and resType is the type of data your server should send back (i.e. text, html, xml, json, script)
So for your example, try adding this inside a script tag on your html page:
// bind to form submit
$('form').submit(function(){
// get table html
var table = {html: $('#horarios').html()};
// POST the data
$.post('/mypage', table, function(response, textStatus){
// do anything with the response here ...
})
});
You need to convert your table into a data structure. You can achieve this with:
var tbl = $('#horarios tr').map(function(rowIdx, row) {
var rowObj = $(row).find('td').map(function(cellIdx, cell) {
var retVal = {};
retVal['cell' + cellIdx] = cell.textContent.trim();
return retVal;
}).get();
var retVal = {};
retVal['row' + rowIdx] = rowObj;
return retVal;
}).get();
In this way you will pass the table as an array of rows of cells.
$('input[value="Save"]').on('click', function(e) {
//
// prevent form submit
//
e.preventDefault();
//
// collect table data by row X col
//
var tbl = $('#horarios tr').map(function(rowIdx, row) {
var rowObj = $(row).find('td').map(function(cellIdx, cell) {
var retVal = {};
retVal['cell' + cellIdx] = cell.textContent.trim();
return retVal;
}).get();
var retVal = {};
retVal['row' + rowIdx] = rowObj;
return retVal;
}).get();
console.log('-->' + JSON.stringify({table: tbl}));
$.post('/mypage', {table: tbl}, function(data, textStatus, jqXHR) {
console.log('success');
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id=horarios>
<tr>
<td>1 </td>
<td>2 </td>
<td>3 </td>
</tr>
<tr>
<td>4 </td>
<td>5 </td>
<td>6 </td>
</tr>
</table>
<form method=post>
<input type="submit" value="Save">
</form>
If you want the data to send via post, first you have to extract values from the table and i recommend you put it into an array, then send it via ajax post.
$('form').on('submit', function(e) {
e.preventDefault();
var $dataElements = $('#horarios').find('td'),
data = [];
$.each($dataElements, function(i, elem){
data.push($(elem).html());
});
$.ajax({url:'/mypage', method: 'POST', data: {data:JSON.stringify(data)}});
});
In other hand if you only want to send the html just send it using $('#horarios').html() instead of loop through elements and add it to the post data.
I hope it helps...

After prepend, set value as input javascript then process values in php script

I am using script to print selected values from table into another div.
<script>
$(".addValues").click(function () {
$('#selection').show();
var $this = $(this),
myCol = $this.closest("td"),
myRow = myCol.closest("tr"),
targetArea = $("#selection");
var qte_input = ('<input type="text" name="kolicina" id="kolicina" placeholder="kg / m" size="10"/>');
var broj = ($("td.data-id", myRow).text());
targetArea.prepend(broj + qte_input +"<hr />");
var arr = { sifra:broj, kolicina:qte_input };
$.ajax({
url: 'script.php',
data: arr,
type: 'post',
});
});
</script>
I am trying to get selected values in script.php, multiple values will be selected and after each selection I need to type quantity that is var qte_input.
Could anyone tell me how to set var broj as input and in the same time print it to another div as selected?
html code
<table id="datatable" class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>-</th>
</tr>
</thead>
<tbody>
<?php while($r=$q->fetch()){ ?>
<tr>
<td class='data-id'><?=''. $r['Id']?> </td>
<td> <button class="addValues" value="<?=''. $r['Id']?>"><i class="ion-ios-cart-outline"></button></td>
</tr>
<?php } ?>
</tbody>
</table>
Once I click on button one value prints in div. Multiple values could be selected as displayed on the image. Once I finish selection I hit button "Pošalji zahtjev" it should pick up all
You should write a function which collect you all data from the table. After that this collection should be sent to you backend via ajax. Demo in this fiddle: https://jsfiddle.net/mgrem9gb/
/**
* Function collect the form data
*/
function collectData(container){
var data = [];
$(container).find('tbody').find('tr').each(function(index, item){
var rowData = {
id: $(item).find('td.data-id').text(),
value: $(item).find('input[name="kolicina"]').val()
};
data.push(rowData);
});
return data;
}
/**
* Excecute the data collect function and the ajax post
*/
$.ajax({
url: 'script.php',
data: collectData('#datatable'),
type: 'post',
});

How to get the value of the first td of the table using JQuery?

I have a table where in I have binded the values which are coming from the Form.In that form I have a primary key Field as TicketId which I have kept as hidden in the form and while inserting it into the table I am showing it.For Binding the data I have used Knockout.So I want to delete the row that I will select.So while selecting it I should get the id of that row so that I can passed it to the Delete action using ajax.But My problem is that I am not getting that id.So how to do this?
My code:
<table id="table2" style="border: double">
<thead>
<tr>
<td>Ticket ID</td>
<td>Ticket Type</td>
<td>No of Tickets</td>
<td>Ticket Price</td>
<td>Start Date</td>
<td>End Date</td>
<td>Action</td>
</tr>
</thead>
<!--Iterate through an observableArray using foreach-->
<tbody id="ticketid" data-bind="foreach:TicketDatas">
<tr style="border: solid" data-bind="click: $root.getselectedTicket" id="updtr">
<td id="rowid" data-bind="text:TicketId">#*<span data-bind="text:No_Of_Ticket"></span>*#</td>
<td data-bind="text:SelectedTicketType">#*<span data-bind="text:No_Of_Ticket"></span>*#</td>
<td data-bind="text:No_Of_Ticket">#*<span data-bind="text:No_Of_Ticket"></span>*#</td>
<td data-bind="text:Ticket_Price">#*<span data-bind="text:Ticket_Price"></span>*#</td>
<td data-bind="text:Start_Date">#*<span data-bind="text:Start_Date"></span>*#</td>
<td data-bind="text:End_Date">#*<span data-bind="text:End_Date"></span>*#</td>
<td>
<button data-bind="click: $root.deleterec">Delete</button></td>
</tr>
</tbody>
</table>
<script type="text/javasript">
self.deleterec = function () {
if (confirm('Are you sure to Delete this ticket ??')) {
var tickid = $("#table2 tr:eq(0)").attr("id");
$.ajax({
type: "POST",
data: { id: tickid },
url: "Ticket/DeleteTicket",
//data: "{id:" + ko.toJSON(id) + "}",
success: function (data) {
self.TicketDatas.remove(data);
alert("Record Deleted Successfully");
//GetTickets();//Refresh the Table
},
error: function (error) {
alert(error.status + "<--and--> " + error.statusText);
}
});
}
};
</script>
so just want the solution for this statement if I ask in short
var tickid = $("#table2 tr:eq(0)").attr("id");
I'm not sure how the rest of your code goes, but here's the jQuery parts when you have a reference to the DOM node for the delete link.
I assigned most parts to variable names to be more descriptive here, but you can make this more concise for your use.
$('#table2 .delete-link').click(function() {
var deleteLink = $(this);
var tableRow = deleteLink.closest('tr');
var firstCell = tableRow.find('td:first-child');
var ticketId = firstCell.attr('id');
// ... Do what you need to do with the ticket ID.
return false;
});
Additional References:
CSS pseudo-class :first-child
jQuery click()
jQuery closest()
jQuery find()
var tickid = $("#table2 tr:eq(0)").html();
OR
var tickid = $("#table2 tr:eq(0)").val();

Categories

Resources