this is related to my previous question about jqgrid. im doing now a search button that would search my inputed text from the server and display those data (if there is) in the jqgrid. Now, what i did is i create a global variable that stores the filters. Here's my javascript code for my searching and displaying:
filter = ''; //this is my global variable for storing filters
$('#btnsearchCode').click(function(){
var row_data = '';
var par = {
"SessionID": $.cookie("ID"),
"dataType": "data",
"filters":[{
"name":"code",
"comparison":"starts_with",
"value":$('#searchCode').val(),
}],
"recordLimit":50,
"recordOffset":0,
"rowDataAsObjects":false,
"queryRowCount":true,
"sort_descending_fields":"main_account_group_desc"
}
filter="[{'name':'main_account_group_code','comparison':'starts_with','value':$('#searchCode').val()}]";
$('#list1').setGridParam({
url:'json.php?path=' + encodeURI('data/view') + '&json=' + encodeURI(JSON.stringify(par)),
datatype: Settings.ajaxDataType,
});
$('#list1').trigger('reloadGrid');
$.ajax({
type: 'GET',
url: 'json.php?' + $.param({path:'data/view',json:JSON.stringify(par)}),
dataType: Settings.ajaxDataType,
success: function(data) {
if ('error' in data){
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
if ( (JSON.stringify(data.result.main.row)) <= 0){
alert('code not found');
}
else{
var root=[];
$.each(data['result']['main']['rowdata'], function(rowIndex, rowDataValue) {
var row = {};
$.each(rowDataValue, function(columnIndex, rowArrayValue) {
var fldName = data['result']['main']['metadata']['fields'][columnIndex].name;
row[fldName] = rowArrayValue;
});
root[rowIndex] = row;
row_data += JSON.stringify(root[rowIndex]) + '\r\n';
});
}
alert(row_data); //this alerts all the data that starts with the inputed text...
}
}
});
}
i observed that the code always enter this (i am planning this code to use with my other tables) so i put the filter here:
$.extend(jQuery.jgrid.defaults, {
datatype: 'json',
serializeGridData: function(postData) {
var jsonParams = {
'SessionID': $.cookie("ID"),
'dataType': 'data',
'filters': filter,
'recordLimit': postData.rows,
'recordOffset': postData.rows * (postData.page - 1),
'rowDataAsObjects': false,
'queryRowCount': true,
'sort_fields': postData.sidx
};
return 'json=' + JSON.stringify(jsonParams);
},
loadError: function(xhr, msg, e) {
showMessage('HTTP error: ' + JSON.stringify(msg) + '.');
},
});
now, my question is, why is it that that it displayed an error message "Server Error: Parameter 'dataType' is not specified"? I already declared dataType in my code like above but it seems that its not reading it. Is there anybody here who can help me in this on how to show the searched data on the grid?(a function is a good help)
I modified your code based on the information from both of your questions. As the result the code will be about the following:
var myGrid = $("#list1");
myGrid.jqGrid({
datatype: 'local',
url: 'json.php',
postData: {
path: 'data/view'
},
jsonReader: {
root: function(obj) {
var root = [], fields;
if (obj.hasOwnProperty('error')) {
alert(obj.error['class'] + ' error: ' + obj.error.msg);
} else {
fields = obj.result.main.metadata.fields;
$.each(obj.result.main.rowdata, function(rowIndex, rowDataValue) {
var row = {};
$.each(rowDataValue, function(columnIndex, rowArrayValue) {
row[fields[columnIndex].name] = rowArrayValue;
});
root.push(row);
});
}
return root;
},
page: "result.main.page",
total: "result.main.pageCount",
records: "result.main.rows",
repeatitems: false,
id: "0"
},
serializeGridData: function(postData) {
var filter = JSON.stringify([
{
name:'main_account_group_code',
comparison:'starts_with',
value:$('#searchCode').val()
}
]);
var jsonParams = {
SessionID: $.cookie("ID"),
dataType: 'data',
filters: filter,
recordLimit: postData.rows,
recordOffset: postData.rows * (postData.page - 1),
rowDataAsObjects: false,
queryRowCount: true,
sort_descending_fields:'main_account_group_desc',
sort_fields: postData.sidx
};
return $.extend({},postData,{json:JSON.stringify(jsonParams)});
},
loadError: function(xhr, msg, e) {
alert('HTTP error: ' + JSON.stringify(msg) + '.');
},
colNames:['Code', 'Description','Type'],
colModel:[
{name:'code'},
{name:'desc'},
{name:'type'}
],
rowNum:10,
viewrecords: true,
rowList:[10,50,100],
pager: '#tblDataPager1',
sortname: 'desc',
sortorder: 'desc',
loadonce:false,
height: 250,
caption: "Main Account"
});
$("#btnsearchCode").click(function() {
myGrid.setGridParam({datatype:'json',page:1}).trigger("reloadGrid");
});
You can see the code live here.
The code uses datatype:'local' at the beginning (at the 4th line), so you will have no requests to the server if the "Search" button is clicked. The serializeGridData the data from the postData parameter of serializeGridData will be combined with the postData parameter of jqGrid (the parameter "&path="+encodeURIComponent('data/view') will be appended). Additionally all standard jqGrid parameters will continue to be sent, and the new json parameter with your custom information will additionally be sent.
By the way, if you want rename some standard parameters used in the URL like the usage of recordLimit instead of rows you can use prmNames parameter in the form.
prmNames: { rows: "recordLimit" }
Related
I have a table using Datatable plugin. I have filtered what I want to delete and after deletion, I manage to empty the value.
After that, if I want to filter using the same text again, for example, I have ba 1 and ba 2 and after deleting ba 1, it still shows the cell when I entered ba on the filter textarea field. It suppose to display the remaining ba which are not deleted yet.
For your information, I'm not using built in Datatable Ajax method.
what I'm trying to do is I want it to reload the table with the new data without refreshing the page after ajax on success. How to do that?
My datatable :
var table1 = $('#table1').DataTable(
{
pageLength : 500,
lengthChange: false,
deferRender: true,
scrollY: 800,
scrollCollapse: true,
scrollX: true,
bSort: false,
cache: true,
autoWidth: false,
columnDefs: [
{
targets: 0,
checkboxes:
{
selectRow: true
}
}
],
select: {
style: 'multi',
selector: 'td:not(:nth-child(4), :nth-child(5), :nth-child(6), :nth-child(9), :nth-child(10), :nth-child(13), :nth-child(14), :nth-child(15), :nth-child(16), :nth-child(17), :nth-child(18), :nth-child(19), :nth-child(20), :nth-child(21), :nth-child(22), :nth-child(23), :nth-child(24), :nth-child(25))'
}
});
Here's my filtering function code :
table1.columns().every(function ()
{
var table = this;
$('.filter', this.header()).on('keyup change', delay(function (settings, data, dataIndex)
{
if (table.search() !== this.value)
{
table.search(this.value).draw();
}
}, 500));
});
Here's my AJAX success code for deletion based on selected checkbox:
$('.btnN2').click(function(){
var answer = confirm('Delete N2 : Are you sure you want to delete selected items?');
if (answer)
{
console.log('yes');
var rows = $(table1.rows({selected: true}).$('input[type="checkbox"]').map(function()
{
return $(this).prop("checked") ? $(this).closest('tr').attr('data-getstockcode') : null;
}));
var getstockcodes = [];
$.each(rows, function(index, rowId)
{
console.log(rowId)
getstockcodes.push(rowId);
});
$.ajax({
url: 'del_n2',
type: 'GET',
data: {"getstockcodes": JSON.stringify(getstockcodes)},
dataType: 'JSON',
success:function(data){
console.log(data);
$(table1.rows({selected: true}).$('input[type="checkbox"]').map(function()
{
if($(this).prop("checked"))
{
$(this).parents("tr:eq(0)").find(".note2").val('');
console.log('reset');
}
}));
}
});
}
else
{
console.log('cancel');
}
});
Here's my insert data based on keyup event
$(".note2").keyup(delay(function()
{
var stockcode = $(this).data("stockcode");
var stockname = $(this).data("stockname");
var value = $(this).val().replace(/(\r\n|\n)/g, "\\n");
$.ajax({
url: 'saveNote2',
type: 'GET',
data: 'stockcode='+stockcode+'&stockname='+stockname+'&value='+value,
dataType: 'JSON',
success: function(data){
console.log(data);
},
error: function(data){
console.log(data);
}
});
}, 300));
Just add this in your success function
table1.ajax.reload()
If you are using ajax datatable or local you need to make it like this
table1.clear();
table1.rows.add(your response data array);
table1.draw()
I have the below custom button added to my navigation pager, but i want it to look at what i multi selected and send it to the JQGrid's editurl for processing which is a ASHX.CS page
But i can't make sense of the documentation when it comes to custom button
I can get it call a local function with onClickButton: customButtonClicked but it doesn't send the data like the EDIT button does
In the end what i want to do it select multiple rows and press a button on the navbar and approve all the selected records
// add first custom button
$('#jQGrid').navButtonAdd('#jQGridPager',
{
buttonicon: "ui-icon-mail-closed",
title: "Send Mail",
caption: "Send Mail",
position: "last",
editData: {
WrkId: function () {
var sel_id = $('#jQGrid').jqGrid('getGridParam', 'selarrrow');
var value = "";
for (var a = 0; a < sel_id.length; a++) {
value = value + $('#jQGrid').jqGrid('getCell', sel_id[a], 'wrkid') + ',';
}
return value;
},
CurrentUser: function () {
return '<% =System.Web.HttpContext.Current.User.Identity.Name %>';
}
},
afterSubmit: function (response, postdata) {
if (response.responseText == "") {
$("#jQGrid").trigger("reloadGrid", [{ current: true }]);
return [false, response.responseText]
}
else {
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid')
return [true, response.responseText]
}
}
}
);
using a few different words (how to manually post data to server json) i was able to find a snippet of an ajax code that made more sense (i'm sure i came across this before but as someone who has no jquery experience i didn't recognize it)
but the below sends to the C# handler page the data in a JSON string that was processable, had to use dynamic to read it in but it worked, couldn't get it to not return an error even though there was no error, so i used the complete: instead of success: and then called the trigger to reload the JQGrid
Final Code:
$('#jQGrid').navButtonAdd('#jQGridPager',
{
buttonicon: "ui-icon-check",
title: "Approve all selected entries",
caption: "Approve",
position: "last",
onClickButton: function () {
var sel_id = $('#jQGrid').jqGrid('getGridParam', 'selarrrow');
var value = "";
for (var a = 0; a < sel_id.length; a++) {
value = value + $('#jQGrid').jqGrid('getCell', sel_id[a], 'wrkid') + ',';
};
$.ajax({
type: "POST",
url: "AdministrationHandler.ashx?oper=approve",
data: JSON.stringify({
WrkId: value,
CurrentUser: "<% =System.Web.HttpContext.Current.User.Identity.Name %>"
}),
dataType: "json",
contentType: "application/json; charsset=utf-8",
complete: function (xhr, x) {
if (xhr.responseText.toUpperCase().indexOf("SUCCESS") >= 0) {
alert('Success!\n' + xhr.responseText);
}
else {
alert('Failed!\n' + xhr.responseText + '\n' + x);
};
$("#jQGrid").jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
}
})
}
});
C# Code
try
{
String postData = new System.IO.StreamReader(context.Request.InputStream).ReadToEnd();
var data = JsonConvert.DeserializeObject<dynamic>(postData);
Approve(data.WrkId.ToString(), data.CurrentUser.ToString());
strResponse = "Employee records successfully approved";
}
catch
{
strResponse = "Employee records not approved";
}
context.Response.Write(strResponse);
I am using select2 dropdown and I am trying to build it as such that it dynamically displays the leads based on the JSON response.
As u can see in the image below, the text inserted correctly returns a JSON array, however, select2 is not capable of assigning the results into options. Therefore, I am literally quite stuck on what to do from here.
https://i.imgur.com/9OnvJzK.pnghere
I already tried setting a variable equal to the selectbox and appending the data in there, but my editor indicates that the code will be unreachable.
Create.tpl - contains front-end code
{literal}
<script>
$(document).ready(function() {
$('.select2lead').select2({
minimumInputLength: 3,
ajax: {
type: 'GET',
url: '/modules/support/ajax.php',
dataType: 'json',
delay: 250,
}
});
$('#select2lead').select2({
tags: true,
minimumInputLength: 3,
ajax: {
type: 'GET',
url: '/modules/support/ajax.php',
dataType: 'json',
delay: 250,
data: function (params) {
var query = {
search: params.term
};
// Query parameters will be ?search=[term]&type=public
return query;
},
processResults: function (data) {
var select2lead = $('#select2lead');
// Tranforms the top-level key of the response object from 'items' to 'results'
return {
results: data.items
}
// var option = new Option(data.name, data.id, true, true);
// select2lead.append(option).trigger('change');
}
}
});
$('#summernote').summernote({
height: 150,
minHeight: null,
maxHeight: null,
focus: true
});
})
</script>
{/literal}
ajax.php - handles the search term and returns JSON
<?php
require_once('../../config.php');
$login = new Login();
if (!$login->checkLogin()) {
echo lang($_SESSION['language'], "INSUFFICIENT_RIGHTS");
exit();
}
$db = new Database();
$query = "
SELECT
LeadID AS lead_id,
REPLACE(CONCAT_WS(' ', LeadInitials, LeadInsertion, LeadLastName), ' ', ' ') AS name,
REPLACE(CONCAT_WS(' ', LeadStreet, LeadStreetNumber, LeadNumberAdjective), ' ', ' ') AS address,
LeadZiPCode AS zipcode,
LeadCity AS city
FROM
`LeadTBL`
WHERE
LeadID > 0
AND
LeadLastName LIKE :leadName
ORDER BY
LeadLastName
ASC
";
$binds = array(':leadName' => $_GET['term'].'_%'.'_%');
$result = $db->select($query, $binds);
$json = [];
foreach ($result as $row){
$json[] = ['id'=>$row['lead_id'], 'name'=>$row['name']];
}
echo json_encode($json);
Issue resolved. Turns out I had to disable "more"; See https://groups.google.com/forum/#!msg/select2/4mDifie32t0/jdJl8KIFN0EJ
Regarding the final code that actually pastes the results into the dropdown properly, see:
$('.select2lead').select2({
minimumInputLength: 3,
ajax: {
type: 'GET',
url: '/modules/support/ajax.php',
dataType: 'json',
delay: 250,
data: function (params) {
return {
term: params.term
};
},
processResults: function (data) {
return {
results: data,
more: false
};
}
}
});
I'm using the materialize autocomplete plugin to create multiple tags input with autocomplete. Plugin works fine, yet only with data passed as an array defined in advance. If data is passed from ajax call, plugin does not show dropdown with options as if there were no results. There are results in fact, they are cached (using cache option) and are shown as dropdown only after re-typing search phrase.
To sum up, autocomplete plugin does not wait for the ajax to complete its request and deliver data and that is why dropdown is not shown at first try.
Is there any way to get this plugin to show suggestions in dropdown once these are retrieved trough ajax call?
Plugin initialization:
autocomplete = $('#multipleInput').materialize_autocomplete({
cacheable: true,
throttling: true,
multiple: {
enable: true,
maxSize : 5
},
appender: {
el: '.ac-users'
},
dropdown: {
el: '#multipleDropdown'
},
getData: function (value, callback) {
callback(value,getAjaxDropdowValuesAutocomplete(value));
}
});
Function to get values from DB:
function getAjaxDropdowValuesAutocomplete(value){
var returnArray = [],
dataArray,
innerObject = {},
postParamsObj = {"search" : value};
$.ajax({
type: "POST",
url: '/search-elements',
data: postParamsObj,
success: function( msg ) {
dataArray = msg['data'];
for(var i = 0;i < dataArray.length; i++){
innerObject = {};
innerObject["id"] = dataArray[i][0];
innerObject["text"] = dataArray[i][1] + " " + dataArray[i][2];
returnArray.push(innerObject);
}
// returnArray format [{ 'id': '1', 'text': 'Johnny Bravo' }]
},
error : function(msg){
}
});
return returnArray;
}
You could try initializing the autocomplete during the success callback of the ajax request instead of the other way around. That way you're sure to have the data before it tries to start binding the autocomplete events. e.g.
function getAjaxDropdowValuesAutocomplete(value) {
var returnArray = [],
dataArray,
innerObject = {},
postParamsObj = {"search": value};
$.ajax({
type: "POST",
url: '/search-elements',
data: postParamsObj,
success: function (msg) {
dataArray = msg['data'];
for (var i = 0; i < dataArray.length; i++) {
innerObject = {};
innerObject["id"] = dataArray[i][0];
innerObject["text"] = dataArray[i][1] + " " + dataArray[i][2];
returnArray.push(innerObject);
}
// returnArray format [{ 'id': '1', 'text': 'Johnny Bravo' }]
autocomplete = $('#multipleInput').materialize_autocomplete({
cacheable: true,
throttling: true,
multiple: {
enable: true,
maxSize: 5
},
appender: {
el: '.ac-users'
},
dropdown: {
el: '#multipleDropdown'
},
getData: returnArray
});
},
error: function (msg) {
}
});
return returnArray;
}
I have a select2 list which having huge data. So, basically on scrolling we're populating data through pagination( adding 10 records on each scroll). In Select2, version 3.4.8, its working fine and able to load data through asp.net web method. Below is the code
$("#ddlEntity").select2({
width: 200,
dropdownAutoWidth: true,
loadMorePadding: 200
initSelection: function (element, callback) {
var data = { id: ID, text: Value };
callback(data);
},
query: timedelayfunction(function (query) {
var res = AjaxRequest( URL , 'GetOnDemandWebMethod', { searchFilter : query.term, pageCounter: query.page, uid:$('#uid').val() });
var data = { more: (res.d[0] != undefined ? res.d[0].MoreStatus : false), results: [] }, i;
for (i = 0; i < res.d.length; i++) {
data.results.push({ id: res.d[i].ID, text: res.d[i].Value });
}
query.callback(data);
}, 200)
});
After moving Select2, version 4.0.3, same functionality is breaking. Can anyone help on this.
Thanks in Advance.
Finally, I've resolved it at my end and after tweaking web method response as JSON serialised array string and select2 v4 with data portion as json string worked for me.
for others it would be simple as like below code
$('#ddlEntity').select2({
width: 200,
allowClear: true,
placeholder: {
id: -1,
text: "Select any."
},
ajax: {
type:"POST",
url: '',
contentType: "application/json; charset=utf-8",
async: false,
dataType: 'json',
data: function (params) {
return "{'searchFilter':'" + (params.term || "") + "','searchPage':'" + (params.page || 1) + "'}";
},
processResults: function (res, params) {
var jsonData = JSON.parse(res.d);
params.page = params.page || 1;
var data = { more: (jsonData[0] != undefined ? jsonData[0].MoreStatus : false), results: [] }, i;
for (i = 0; i < jsonData.length; i++) {
data.results.push({ id: jsonData[i].ID, text: jsonData[i].Value });
}
return {
results: data.results,
pagination: {
more: data.more
}
};
}
}
});