Push data to array populate jqGrid - javascript

Im try to populate my JQgrid with data each time I press the button "1" but I dont know what Im doing wrong. Im new to jquery. I have no problem printing the data to a p tag.
Im trying to use push should I use add instead? Or do I need to refresh the grid every press.
Any other suggested solutions are welcome.
$(document).ready(function () {
// Examle data for jqGrid
var currentTime = [
{time:""} ,
];
// Configuration for jqGrid Example 1
$("#table_list_1").jqGrid({
data: currentTime,
datatype: "local",
height: 250,
autowidth: true,
shrinkToFit: true,
rowNum: 14,
rowList: [10, 20, 30],
colNames: ['Time'],
colModel: [
{name: 'time', index: 'time', width: 60, sorttype: "double"},
],
pager: "#pager_list_1",
viewrecords: true,
caption: "Example jqGrid 1",
hidegrid: false
});
// Add responsive to jqGrid
$(window).bind('resize', function () {
var width = $('.jqGrid_wrapper').width();
$('#table_list_1').setGridWidth(width);
});
});
window.addEventListener('keydown', doKeyDown, false);
function doKeyDown(e){
if(e.keyCode == 49 & wavesurfer.isPlaying()){
// KEY = " 1 "
currentTime.push(wavesurfer.getCurrentTime());
});
}
}

My solution:
jQuery("#table_list_1").addRowData("1",{id: id, time: wavesurfer.getCurrentTime()});

Related

JavaScript array push method not displaying all elements after pushing

I am working on a javascript array. I am getting a list from the backend of size 122. But I am pushing all the elements into a javascript array and displaying all of them in UI. But only 30 are visible in display.
I amusing JQGrid javascript frame work for grid display. Need some help to know what I am missing here. :(
Please find the code below:
var list= '<%=list%>';
alert(list.length);
for(i=0;i<list.length;i++){
list.push({'list':list[i] });
}
//alert gives me an expected answer (122) but in display only 30 are available.
//JQGRID CODE
jQuery("#jqGrid1").jqGrid({
datatype: "local",
data: list,
width : 600,
height: 600,
shrinkToFit: false,
forceFit: true,
colModel: [
{ label: 'List', name: 'list', index: 'list', width: 350, align: 'left', classes:'zeroBorderRight' }
],
gridComplete: function(){
jQuery('.ui-jqgrid-bdiv').css({'height':'auto', 'max-height':'100px'});
jQuery('.ui-th-column').css({'background':'#F2F2F2','height':'25px','text-align':'left'});
jQuery('.ui-jqgrid tr.jqgrow td').css({'height':'20px'});
$(this).find(">tbody>tr.jqgrow").removeClass("myAltRowClassEven myAltRowClassOdd");
$(this).find(">tbody>tr.jqgrow:odd").addClass("myAltRowClassEven");
$(this).find(">tbody>tr.jqgrow:even").addClass("myAltRowClassOdd");
$('.ui-corner-all').addClass('ui-zero-corner');
},
onSortCol: function (index, columnIndex, sortOrder) {
$(this).find(">tbody>tr.jqgrow").removeClass("myAltRowClassEven myAltRowClassOdd");
$(this).find(">tbody>tr.jqgrow:odd").addClass("myAltRowClassEven");
$(this).find(">tbody>tr.jqgrow:even").addClass("myAltRowClassOdd");
}
});

jQGrid - "jpg1" instead of proper id number

I'm loading local file (I'm parsing csv file into json and then transfer the array to jqGrid). Table generated through jqGrid should allow user to modify, add and delete the data in the grid. Everything seemed to work perfectly until I wanted to add a row to my grid. One of the columns had a parameter key = true which is my id for the rows. When I try to add new row, the grid changes my id into jpg1. The others columns are fine. Below is the code I'm using:
$("#jqGrid").jqGrid({
datatype: "local",
data: myData,
editurl: "clientArray",
colModel: [
{
label: 'Kod',
name: 'Kod',
width: 60,
editable: true,
key: true,
sorttype: 'number'
},
{
label: 'Firma',
name: 'Firma',
width: 120,
editoptions:
{
size: 40,
sopt:['cn']
},
editable: true,
sorttype: 'string'
},
{
label: 'Adres',
name: 'Adres',
width: 80,
editoptions: {size: 40},
editable: true
},
{
label: 'Miasto',
name: 'Miasto',
width: 80,
editoptions:
{
size: 40,
sopt:['cn']
},
editable: true
}
],
height: 'auto',
autowidth: true,
shrinkToFit: false,
forceFit: false,
autoencode: true,
viewrecords: true,
caption: "Title",
pager: "#jqGridPager",
sortable: true,
ignoreCase: true,
sortname: 'Kod',
sortorder: 'asc',
rowNum: 5,
rowList: [5, 10, 20, "10000:All"],
ondblClickRow: function(rowid) {
$("#jqGrid").jqGrid('editGridRow', rowid,
{
editCaption: "The Edit Dialog",
zIndex:100,
recreateForm: true,
closeAfterEdit: true,
width: 900,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
});
}
});
$('#jqGrid').jqGrid('navGrid',"#jqGridPager",
{ edit: true, add: true, del: true, search: false, refresh: true, view: true, cloneToTop: true},
// options for the Edit Dialog
{
editCaption: "The Edit Dialog",
zIndex:100,
recreateForm: true,
closeAfterEdit: true,
reloadAfterSubmit: true,
width: 900,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Add Dialog
{
width: 900,
zIndex:100,
closeAfterAdd: true,
recreateForm: true,
reloadAfterSubmit: true,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Delete Dialog
delSettings,
// options for the Search Dialog
{
zIndex:100
},
// options for the View Dialog
{
width: '100%'
});
I'm attaching a screenshot that shows a problem:
Photo
The data I use is a file parsed into JSON array via Papaparse.js plugin.
EDIT:
I've added the test data if somebody would like to test the code.
var myData = [];
myData.push(
{
Kod: 1.1,
Firma: 'Hutchinson',
Adres: '5th Avenue',
Miasto: 'Wroclaw'
},
{
Kod: 2.1,
Firma: 'BMW',
Adres: '6th Avenue',
Miasto: 'Warsaw'
});
I will be grateful for any help.
If you need the grid only for local editing, you can consider just remove key: true property to solve the problem. It's the way, which I would recommend you. You can include id property in the input data which will be used as value of rowid (id of <tr> elements).
Alternatively you can change the block "options for the Add Dialog" to the following
// options for the Add Dialog
{
width: 900,
zIndex:100,
closeAfterAdd: true,
recreateForm: true,
reloadAfterSubmit: true,
onclickSubmit: function (options, postdata, frmoper) {
// save Kod in some other parameter
return {myKod: postdata.Kod};
},
afterSubmit: function (jqXHR,postdata, frmoper) {
// restore the correct value
postdata.Kod = postdata.myKod;
// inform jqGrid that it was not an error
return [true];
}
},
You still don't would be able to change the id of the row in the way.
By the way you wrote that you use jqGrid 4.7.1. I want remind you that jqGrid 4.7.0 is the last version which is free. It's the reason why I started free jqGrid project which still free. You can get it here (see readme and wiki).
The demo shows an example of the above code fixes using free jqGrid 4.8.

creating an updating jqgrid table from websocket source

I am struggling a bit with where to start, I am in the process of doing a websocket project, I have the server coded which pushes messages in realtime to a websocket client running jQuery and HTML5. I have set the server up to pass across JSON messages like the below.
{"timestamp":"2015-01-12T17:22:40.4372664+11:00","code":0012345,"parsedname":" (NAME)","priority":"AB","message":"THIS IS A TEST MESSAGE"}
These messages show up fine on the websocket page, but now I want to display them in a more friendly way. Whilst I am fine with vb.net this kind of programming is way out of my area and I am wondering if anyone could point me in the direction of some simple code examples which would allow me to update a table in realtime as a json message is recieved by the websocket client.
I had a quick look on the net, but I can either find only partial examples or overly complex examples. I should clarify I am not looking for someone to do it for me, just to help me get a better understanding on how to best do it and to point me in the direction of some code samples.
From what I can see it looks like jqgrid might be suitable, but I don't know how to bind it to a websocket, and how to go from there.
From the demo's it looks like something like this below should work, but how do I change the source to the websockets json strings, and once done, how do I then update the table. I should clarify each new message is 1 json string.
<script type="text/javascript">
$(function () {
$("#list").jqGrid({
url: "example.php",
datatype: "xml",
mtype: "GET",
colNames: ["timestamp", "code", "name", "message"],
colModel: [
{ name: "timestamp", width: 55 },
{ name: "code", width: 90 },
{ name: "name", width: 80, align: "right" },
{ name: "message", width: 80, align: "right" }
],
pager: "#pager",
rowNum: 10,
rowList: [10, 20, 30],
sortname: "invid",
sortorder: "desc",
viewrecords: true,
gridview: true,
autoencode: true,
caption: "My first grid"
});
});
</script>
Many thanks,
Thanks for the tips, I have tried the samples and combined them but having no real luck so far :(
Travis.
Code:
<html>
<head>
<title>Info Stream (TEST)</title>
<link href="https://www.guriddo.net/demo/css/trirand/ui.jqgrid.css" rel="stylesheet"/>
<link href="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.11.1/themes/start/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.4/jquery-ui.min.js"></script>
<script src="http://www.guriddo.net/demo/js/trirand/jquery.jqGrid.min.js"></script>
<script src="http://www.guriddo.net/demo/js/trirand/i18n/grid.locale-en.js"></script>
<script type="text/javascript">
var noSupportMessage = "Your browser cannot support WebSocket!";
var ws;
function appendMessage(message) {
$('body').append(message);
}
function connectSocketServer() {
var support = "MozWebSocket" in window ? 'MozWebSocket' : ("WebSocket" in window ? 'WebSocket' : null);
if (support === null) {
appendMessage("* " + noSupportMessage + "<br/>");
return;
}
appendMessage("* Connecting to server ..<br/>");
// create a new websocket and connect
ws = new window[support]('ws://address.com:2012/');
// when data is comming from the server, this metod is called
ws.onmessage = function (evt) {
makegrid(evt.data);
};
// when the connection is established, this method is called
ws.onopen = function () {
appendMessage('* Connection open<br/>');
};
// when the connection is closed, this method is called
ws.onclose = function () {
appendMessage('* Connection closed<br/>');
};
}
function disconnectWebSocket() {
if (ws) {
ws.close();
}
}
function connectWebSocket() {
connectSocketServer();
}
window.onload = function () {
connectWebSocket();
};
function makeGrid(data){
var json = [data]; // now this is local data
$("#list").jqGrid({
datastr: data, // so you should use datastr instead of url with localdata
datatype: "jsonstring", // and dataype should be jsonstring with local data
colNames: ["timestamp", "capcode", "parsedname", "message"],
colModel: [
{ name: "timestamp", width: 400 },
{ name: "capcode", width: 200 },
{ name: "parsedname", width: 200, align: "right" },
{ name: "message", width: 200, align: "right" }
],
pager: "#pager",
rowNum: 10,
rowList: [10, 20, 30],
sortname: "invid",
sortorder: "desc",
viewrecords: true,
gridview: true,
autoencode: true,
caption: "Pager Messages"
});
};
</script>
</head>
<body>
<table id='list'></table>
<div id='pager'></div>
</body>
</html>
your data type should be json
datatype: "json"
everything else looks fine.
Try this this is a sample demo with your json and the js object should have to be in []:
var data = [{"timestamp":"2015-01-12T17:22:40.4372664+11:00","code":0012345,"parsedname":" (NAME)","priority":"AB","message":"THIS IS A TEST MESSAGE"}];
$(function () {
$("#list").jqGrid({
datastr: data,
datatype: "jsonstring",
mtype: "GET",
colNames: ["timestamp", "code", "name", "message"],
colModel: [
{ name: "timestamp", width: 400 },
{ name: "code", width: 200 },
{ name: "name", width: 200, align: "right" },
{ name: "message", width: 200, align: "right" }
],
pager: "#pager",
rowNum: 10,
rowList: [10, 20, 30],
sortname: "invid",
sortorder: "desc",
viewrecords: true,
gridview: true,
autoencode: true,
caption: "My first grid"
});
});
<link href="https://www.guriddo.net/demo/css/trirand/ui.jqgrid.css" rel="stylesheet"/>
<link href="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.11.1/themes/start/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.4/jquery-ui.min.js"></script>
<script src="http://www.guriddo.net/demo/js/trirand/jquery.jqGrid.min.js"></script>
<script src="http://www.guriddo.net/demo/js/trirand/i18n/grid.locale-en.js"></script>
<table id='list'></table>
<div id='pager'></div>
Another way is this, you can have a jquery ajax call to get the object you are getting and push that object in array and pass the array to the jqgrid like this:
$.getJSON('example.php', function(data){
makeGrid(data);
});
and your function makeGrid():
function makeGrid(data){
var json = [data]; // now this is local data
$("#list").jqGrid({
datastr: data, // so you should use datastr instead of url with localdata
datatype: "jsonstring", // and dataype should be jsonstring with local data
....
});
}

jquery, jqgrid paging: cannot switch page

Here append similar questions but I cannot find answer to my one:
In html is
table id= grid and div id=pager:
Also I have mine js code:
var myGrid = $("#grid").jqGrid({
url: _options.gridFetch,
datatype: "json",
colModel:[
{name:'id',index:'id', width:55},
{name:'name',index:'name', width:555, editable:true},
{name:'is_promoted',index:'is_promoted', width:165, editable:true, formatter: $.adminCategoryEntries._boolFormatter, edittype: 'select', editoptions:{value:"1:Yes;0:No"}},
{name:'is_in_shop',index:'is_in_shop', width:165, editable:true, formatter: $.adminCategoryEntries._boolFormatter, edittype: 'select', editoptions:{value:"1:Yes;0:No"}},
{name:'actions', formatter:'actions', width: 85, formatoptions:{keys:true}},
],
pager: '#pager',
jsonReader : { repeatitems: false } ,
rowNum: 10,
rowList: [10, 20, 500],
viewrecords: true,
autowidth: true,
sortname: 'id',
sortorder: 'desc'
});
myGrid.jqGrid('navGrid','#pager',{edit:false,add:false,del:false,search:false});
I've use code from other stackoverflow tutorial.
And here is my issue: If I try to change number of showed rows in my navigator I can see all stored data (86 rows) but if I set rows to i.e 10 (value less than rows number)per page I always see in my navigator:
page 1 of 5
and I cannot switch it to another it always stays on first
json info:
>page: 1
>records: "86"
>rows: [{id:3, name:Ulkofilee/Naudanliha, is_promoted:1, is_in_shop:1},…]
>total: 5
thanks in advance
Radek
Are you getting the data from a server method you can control? It's somewhat cryptic, but the data coming from your _options.gridFetch needs to have a property named "total" defined that specifies the current page that should be viewed.

jQuery button click refresh of jqGrid only firing once

I have the following jQuery code which I'm using to populate a jqGrid. It works perfectly posting to my ASP.NET MVC page on the first click of the button. My
problem is, any other clicks past the first it seems to run through the jquery code when clicking the button but it never makes it to the POST page. Any ideas why?
<script type="text/javascript">
$(document).ready(function() {
$('#btnSubmit').click(function() {
/* Refreshes the grid */
$("#list").jqGrid({
/* The controller action to get the grid data from */
url: '/CRA/AddPart',
data: { partNumber: "123"},
datatype: 'json',
mtype: 'GET',
/* Define the headers on the grid */
colNames: ['col1', 'col2', 'col3', 'col4'],
/* Define what fields the row columns come from */
colModel: [
{ name: 'col1', index: 'invid', width: 290 },
{ name: 'col2', index: 'invdate', width: 290 },
{ name: 'col3', index: 'amount', width: 290, align: 'right' },
{ name: 'col4', index: 'tax', width: 290, align: 'right'}],
height: 'auto',
rowNum: 10,
rowList: [10, 20, 30],
sortname: 'id',
sortorder: "desc",
viewrecords: true,
imgpath: '../../Scripts/jgrid/themes/steel/images',
caption: 'Core Return Authorization Contents:',
cellEdit: true
});
});
});
</script>
The reason the grid isn't reloading is that you are calling the wrong method. The jqGrid method does approximately this:
Examine the table to see if it is already a grid; if so, exit.
Turn the table into a grid.
Populate the first page of data.
So the second time you call the method, it does nothing, as per step 1.
Instead, you should be calling $("#list").trigger("reloadGrid") on the second and all subsequent clicks.
Now, because of your mtype in the grid options, the grid is going to do a GET, not a POST. So if the POST is coming from the button itself (in other words, it is an input of type submit), you should return true to indicate that the submit should continue as usual.
Here is the solution :
<script type="text/javascript">
var firstClick = true;
$(document).ready(function() {
$('#btnSubmit').click(function() {
if (!firstClick) {
$("#list").trigger("reloadGrid");
}
firstClick = false;
/* Refreshes the grid */
$("#list").jqGrid({
/* The controller action to get the grid data from */
url: '/CRA/AddPart',
data: { partNumber: "123"},
datatype: 'json',
mtype: 'GET',
/* Define the headers on the grid */
colNames: ['col1', 'col2', 'col3', 'col4'],
/* Define what fields the row columns come from */
colModel: [
{ name: 'col1', index: 'invid', width: 290 },
{ name: 'col2', index: 'invdate', width: 290 },
{ name: 'col3', index: 'amount', width: 290, align: 'right' },
{ name: 'col4', index: 'tax', width: 290, align: 'right'}],
height: 'auto',
rowNum: 10,
rowList: [10, 20, 30],
sortname: 'id',
sortorder: "desc",
viewrecords: true,
imgpath: '../../Scripts/jgrid/themes/steel/images',
caption: 'Core Return Authorization Contents:',
cellEdit: true
});
});
});
</script>
Because I need to POST new values to the the Action for me it does not work "reloadGrid".
I just remove all the content and create the empty table again.
In the if I check if the grid is there to hide the "empty chart" div (it shows just a message). In the else I just clean the div that surrounds the table and then I add inside the table again. When the plugin finds the empty table then it loads the grid completely again.
LoadTableData is the function that has the common functionality to create and load the grid.
Probably this solution is not elegant, but when the time is rushing...
$("#btnDownloadsPerFile").click(function () {
if ($('#chartContainerDownloadsPerFile .ui-jqgrid').length == 0) {
$('#chartContainerDownloadsPerFile .emptyChart').hide();
}
else {
$('#chartContainerDownloadsPerFile').empty();
$('#chartContainerDownloadsPerFile').append('<table id="downloadsPerFileGrid"></table>');
}
LoadTableData("downloadsPerFileGrid", $('#ddlportalOptionsDownloadsPerFile').val(), "downloadsPerFile", $('#ddlTimeOptionsDownloadsPerFile').val(), $('#ddlTimeValuesDownloadsPerFile').val(), $('#ddlCountries').val());
});

Categories

Resources