Getting data from datatable then passing it to php with ajax - javascript

I am using jQuery DataTables, I can get data from selected row using this code
var str = $.map(table.rows('.selected').data(), function (item) {
return item[5]+" "+item[0]
});
where item[5] is id, item[0] is a string.
I want to split return string for passing id and string.
the error founded in ajax code specifically in
data : {}
where is the problem in this code.
<script>
$(document).ready(function() {
var table = $('#liveSearch').DataTable();
$('#liveSearch tbody').off('click', 'tr').on( 'click', 'tr', function () {
if ( $(this).hasClass('selected') ) {
$(this).removeClass('selected');
}
else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
} );
$('.example3-1').on('click', function () {
if ((table.rows('.selected').data().length) > 0) {
var str = $.map(table.rows('.selected').data(), function (item) {
return item[5]+" "+item[0]
});
console.log(str);
$.confirm({
confirmButtonClass: 'btn-info',
cancelButtonClass: 'btn-danger',
confirm: function () {
$.ajax({
type: 'post',
url: 'delete.php',
data: {
str1 : str.substr(0,str.indexOf(' ')),
str2 : str.substr(str.indexOf(' ')+1)
},
success: function( data ) {
console.log( data );
}
});
table.row('.selected').remove().draw(false);
}
});
}
});
} );

CAUSE
You're only allowing only one row selected. But you're using $.map which returns Array not a string as you expect. There is no sense in using $.map for just one row.
SOLUTION
Use the following code instead to get data for selected row and produce the string needed.
var rowdata = table.row('.selected').data();
var str = rowdata[5] + " " + rowdata[0];
It could be simplified further:
var rowdata = table.row('.selected').data();
// ... skipped ...
$.ajax({
// ... skipped ...
data: {
str1: rowdata[5],
str2: rowdata[0]
}
// ... skipped ...
});
NOTES
The solution would be different if you allow multiple row selection.

Related

Is it correct my ajax call and jQuery PHP for submit button only?

I'm using Kendo grid that has treeview with checkboxes. So, here I want to do POST using AJAX call to get the id of selected checkboxes. Is there any correction on this code? Because there is no function for submit button.
AJAX call for submit button
$("#primaryTextButton").kendoButton();
var button = $("#primaryTextButton").data("kendoButton");
button.bind("click", function(e) {
$.ajax({
type: "POST",
url: "getTest.php",
//data: { name: "John" }
data: function () {
return {
method: "getTemplate",
// employeeID: "<?php echo $_SESSION['employeeID'];?>",
// propertyID: "<?php echo $_SESSION['propertyID'];?>",
}
},
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
}
jQuery PHP
function getTemplate() {
global $ehorsObj;
$positionTemplateID = (isset($_POST['positionTemplateID']) ? $_POST['positionTemplateID'] : '');
$hrsPositionID = (isset($_POST['hrsPositionID']) ? $_POST['hrsPositionID'] : '');
$programID = (isset($_POST['programID']) ? $_POST['programID'] : '');
$propertyID = (isset($_POST['propertyID']) ? $_POST['propertyID'] : '');
$employeeID = (isset($_POST['employeeID']));
If they are using : If isset $_POST ,
I'm a little bit confused here. Is there any solution on this?
Demo Here
Your demo link has checkedNodeIds function. This function holds checked nodes in a multidimensional array like
nodes[i].moduleID
nodes[i].groupID
nodes[i].programID
So return this array from this function and pass it as ajax data. Then process it in your PHP back-end.
function checkedNodeIds(nodes, checkedNodes) {
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].checked) {
//checkedNodes.push(nodes[i].moduleID);
// checkedNodes.push(nodes[i].groupID);
checkedNodes.push(nodes[i].programID);
}
if (nodes[i].hasChildren) {
checkedNodeIds(nodes[i].children.view(), checkedNodes);
}
}
}

How can I call my validate function before sending my ajax when a button is clicked?

Hello everyone I have a table that's dynamically generated from database.
This is the table.
I have all the code that works fine,but I only need proper timing of execution
1) Check if all mandatory fields are populated on button click, if not don't send ajax.
2) When all mandatory fields are populated on button click then call ajax and send proper values to c# and later to database.
First I need to check if all mandatory fields are filled in(check Mandatory column(yes or no values):
$(function () {
$("#myButton").on("click", function () {
// Loop all span elements with target class
$(".IDMandatory").each(function (i, el) {
// Skip spans which text is actually a number
if (!isNaN($(el).text())) {
return;
}
// Get the value
var val = $(el).text().toUpperCase();
var isRequired = (val === "TRUE") ? true :
(val === "FALSE") ? false : undefined;
// Mark the textbox with required attribute
if (isRequired) {
// Find the form element
var target = $(el).parents("tr").find("input,select");
if (target.val()) {
return;
}
// Mark it with required attribute
target.prop("required", true);
// Just some styling
target.css("border", "1px solid red");
}
});
})
});
If not don't call ajax and send values. If all fields are populated then call ajax to send values to c#.
This is the ajax code that takes values from filed and table and send's it to c# WebMethod and later to database.
$(function () {
$('#myButton').on('click', function () {
var ddl = $('#MainContent_ddlBusinessCenter').val()
var myCollection = [];
$('#MainContent_gvKarakteristike tbody').find('tr:gt(0)').each(function (i, e) {
var row = $(e);
myCollection.push({
label: valuefromType(row.find(row.find('td:eq(1)').children())),
opis: valuefromType(row.find(row.find('td:eq(3)').children()))
});
});
console.log(myCollection);
function valuefromType(control) {
var type = $(control).prop('nodeName').toLowerCase();
switch (type) {
case "input":
return $(control).val();
case "span":
return $(control).text();
case "select":
('Selected text:' + $('option:selected', control).text());
return $('option:selected', control).text();
}
}
var lvl = $('#MainContent_txtProductConstruction').val()
if (lvl.length > 0) {
$.ajax({
type: "POST",
url: "NewProductConstruction.aspx/GetCollection",
data: JSON.stringify({ 'omyCollection': myCollection, 'lvl': lvl, 'ddl': ddl }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (parseInt(response.d) > 0)
alert("Saved successfully.");
else
alert("This object already exists in the database!");
console.log(response);
location.reload(true);
},
error: function (response) {
alert("Not Saved!");
console.log(response);
location.reload(true);
}
});
}
else {
alert("Please fill in the Product Construction field!")
}
});
});
I need code to execute first mandatory fields and when they are all filled in then call ajax part of the code!
Can anyone please help !
If you need more explanation just ask !
Thanks in advance !
Update Liam helped allot me but ajax is not working on button click.
function validate() {
// Loop all span elements with target class
$(".IDMandatory").each(function (i, el) {
// Skip spans which text is actually a number
if (!isNaN($(el).text())) {
return;
}
// Get the value
var val = $(el).text().toUpperCase();
var isRequired = (val === "TRUE") ? true :
(val === "FALSE") ? false : undefined;
// Mark the textbox with required attribute
if (isRequired) {
// Find the form element
var target = $(el).parents("tr").find("input,select");
if (target.val()) {
return;
}
// Mark it with required attribute
target.prop("required", true);
// Just some styling
target.css("border", "1px solid red");
}
});
}
function sendAjax() {
var ddl = $('#MainContent_ddlBusinessCenter').val()
var myCollection = [];
$('#MainContent_gvKarakteristike tbody').find('tr:gt(0)').each(function (i, e) {
var row = $(e);
myCollection.push({
label: valuefromType(row.find(row.find('td:eq(1)').children())),
opis: valuefromType(row.find(row.find('td:eq(3)').children()))
});
});
console.log(myCollection);
function valuefromType(control) {
var type = $(control).prop('nodeName').toLowerCase();
switch (type) {
case "input":
return $(control).val();
case "span":
return $(control).text();
case "select":
('Selected text:' + $('option:selected', control).text());
return $('option:selected', control).text();
}
}
var lvl = $('#MainContent_txtProductConstruction').val()
if (lvl.length > 0) {
$.ajax({
type: "POST",
url: "NewProductConstruction.aspx/GetCollection",
data: JSON.stringify({ 'omyCollection': myCollection, 'lvl': lvl, 'ddl': ddl }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (parseInt(response.d) > 0)
alert("Saved successfully.");
else
alert("This object already exists in the database!");
console.log(response);
location.reload(true);
},
error: function (response) {
alert("Not Saved!");
console.log(response);
location.reload(true);
}
});
}
else {
alert("Please fill in the Product Construction field!")
}
}
$(function () {
$('#myButton').on('click', function () {
if (validate()){
sendAjax();
}
})
});
If you want to execute these in order why don't you just add one click handler that calls each function:
function validate(){
// Loop all span elements with target class
$(".IDMandatory").each(function (i, el) {
// Skip spans which text is actually a number
....etc.
}
function sendAjax(){
var ddl = $('#MainContent_ddlBusinessCenter').val()
var myCollection = [];
..etc.
}
$(function () {
$('#myButton').on('click', function () {
validate();
sendAjax();
}
});
Seems it would make sense if your validate function actually returns true or false if your form was valid too. then you could:
$(function () {
$('#myButton').on('click', function () {
if (validate()){
sendAjax();
}
}
});
I'm not really sure why your doing this:
// Mark it with required attribute
target.prop("required", true);
when you validate? If you just add this into your HTML it will handle required. adding it here seems a bit strange. I'm guessing your not actually submitting the form? It'd make more sense to add the validation message yourself rather than use this attribute.
Your codes not working because your not returning anything from your validate function. It's not 100% clear to me what is valid and what isn't so I can't alter this. But you need to add return true; for valid cases and return false;for invalid cases for the if statement if (validate()){ to work.

Cannot POST more than one value with AJAX

I stucked on one thing. I have a 2 grid inside checkboxes. When I selected that checkboxes I want to POST that row data values like array or List. Actually when i send one list item it's posting without error but when i get more than one item it couldn't post values.
Example of my grid
Here my ajax request and how to select row values function
var grid = $("#InvoceGrid").data('kendoGrid');
var sel = $("input:checked", grid.tbody).closest("tr");
var items = [];
$.each(sel, function (idx, row) {
var item = grid.dataItem(row);
items.push(item);
});
var grid1 = $("#DeliveryGrid").data('kendoGrid');
var sel1 = $("input:checked", grid1.tbody).closest("tr");
var items1 = [];
$.each(sel1, function (idx, row) {
var item1 = grid1.dataItem(row);
items1.push(item1);
});
$.ajax({
url: '../HeadOffice/CreateInvoice',
type: 'POST',
data: JSON.stringify({ 'items': items, 'items1': items1, 'refnum': refnum }),
contentType: 'application/json',
traditional: true,
success: function (msg) {
if (msg == "0") {
$("#lblMessageInvoice").text("Invoices have been created.")
var del = $("#InvoiceOKWindow").data("kendoWindow");
del.center().open();
var del1 = $("#InvoiceDetail").data("kendoWindow");
del1.center().close();
$("#grdDlvInv").data('kendoGrid').dataSource.read();
}
else {
$("#lblMessageInvoice").text("Problem occured. Please try again later.")
var del = $("#InvoiceOKWindow").data("kendoWindow");
del.center().open();
return false;
}
}
});
This is my C# part
[HttpPost]
public string CreateInvoice(List<Pm_I_GecisTo_Result> items, List<Pm_I_GecisFrom_Result> items1, string refnum)
{
try
{
if (items != null && items1 != null)
{
//do Something
}
else
{
Log.append("Items not selected", 50);
return "-1";
}
}
catch (Exception ex)
{
Log.append("Exception in Create Invoice action of HeadOfficeController " + ex.ToString(), 50);
return "-1";
}
}
But when i send just one row it works but when i try to send more than one value it post null and create problem
How can i solve this? Do you have any idea?
EDIT
I forgot to say but this way is working on localy but when i update server is not working proper.
$.ajax({
url: '../HeadOffice/CreateInvoice',
type: 'POST',
async: false,
data: { items: items, items1: items1 }
success: function (msg) {
//add codes
},
error: function () {
location.reload();
}
});
try to call controller by this method :)

JQuery Ajax returns Source code

I'm using JQuery Ajax on my website. I've tested it on our test server it worked perfectly, but when I tried to put it on our productive server the Ajax just returns the source code of the website itself.
JS File:
$(document).ready(function () {
$('#sshin').keyup(function () {
var query = $(this).val();
console.log(query);
if (query != '') {
$.ajax({
url: "search.php",
method: "POST",
data: {
query: query
},
success: function (data) {
console.log(data);
}
});
}
});
$(document).on('click', 'article', function () {
var text = $('#sshin').val();
text = text.substring(0, text.lastIndexOf(',') + 1);
text += $(this).text();
var uniq = text.match(/\b\w+\b/g).filter(function (el, idx, a) {
return idx === a.lastIndexOf(el);
});
text = uniq.join(',');
$('#sshin').val(text);
$('#sshout').fadeOut();
});
});
PHP File:
<?php
if(isset($_POST["query"])){
$query = $_POST["query"];
return '<ul><li>1</li><li>2</li></ul>';
}
?>
Any idea why it returns something different than it should?
This method once worked for me, hope it might help. Let me know.
this->output->set_content_type('application/json');
return $this->output->set_output(json_encode('<ul><li>1</li><li>2</li></ul>'));

jquery Autocomplete is not loading the results correctly and menu doesn't show unless I press down key

This is what I have:
searchTimeoutID;
InitQuickSearch = function() {
$( 'input#quick-search' ).autocomplete({
source: []
});
$('input#quick-search', document).on('keyup', function(e) {
switch(e.which) {
default: // live search
window.clearTimeout(searchTimeoutID); // remove timer
var str = $(this).val(); // search string
if (str !== '') { // do the search
searchTimeoutID = window.setTimeout(LiveSearch, 100);
}
break;
}
});
};
LiveSearch = function() {
var str = $('input#quick-search').val();
if(str !== '') {
$.ajax({
type: 'POST',
url: '/livesearch',
data: { query: str },
cache: false,
success: function(data){
var results = data.split(',');
alert(results); // displays correct results here
$( 'input#quick-search' ).autocomplete( 'option', { source: results });
},
error: function(response) {
printError(response);
}
});
}
return false;
};
When I output the results variable using alert(results), the values look correct.
However, when I try and update the values in autocomplete it does not display the correct values. Also, I have to press the down key for the menu to appear.
$( 'input#quick-search' ).autocomplete( 'option', { source: results });
What am I doing wrong?
I just had to change:
searchTimeoutID = window.setTimeout(LiveSearch, 100);
to:
LiveSearch();

Categories

Resources