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
....
});
}
Related
Hello I am using jqgrid and other function call using ajax when I use these two scripts then one script is working and one is not working.
and show this error in the browser console.
Screen shot
I try a lot of to remove this error but still, I am not able to remove to this error. kindly any expert tells me what is the problem and how can I resolved this error.
<script type="text/javascript" src="~/bower_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="~/assets/jqgrid/js/jquery.jqgrid.min.js"></script>
<link href="~/assets/jqgrid/jquery-ui-1.12.1.custom/jquery-ui.min.css" rel="stylesheet" />
<script type="text/javascript" src="~/assets/jqgrid/jquery-ui-1.12.1.custom/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.14.1/css/ui.jqgrid.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.14.1/jquery.jqgrid.min.js"></script>
<script type="text/javascript">
$.noConflict();
var rowsToColor = [];
jQuery(document).ready(function ($) {
var $grid = $("#jqGrid");
$grid.jqGrid({
url: '#Url.Action("Ownsership")',
datatype: 'json',
postData: { Membership_ID: function () { return $("#mID").val(); } },
jsonReader: {},
colModel: [
{ name: 'FileID', index: 'FileID', label: 'FILE ID', width: 3 },
{ name: 'UnitNo', index: 'UnitNo', label: 'UNIT NO', width: 7 },
{ name: 'TransDate', index: 'TransDate', label: 'TRANS DATE', width: 8 },
{ name: 'Category', index: 'Category', label: 'FILE CATEGORY', width: 10 },
{ name: 'Project', index: 'Project', label: 'PROJECT', width: 20 }
],
additionalProperties: [],
loadonce: true,
navOptions: {
reloadGridOptions: { fromServer: true }
},
formEditing: {
closeOnEscape: true,
closeAfterEdit: true,
savekey: [true, 13],
reloadGridOptions: {
fromServer: true
}
},
viewrecords: true,
height: 'auto',
autowidth: true,
rowNum: 100,
rowList: [10, 20, 30, 50, 100, 500],
rownumbers: true,
sortname: "Name",
sortorder: "desc"
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
TotalFilesM();
$("#Projectlist").change(function () {
TotalFilesM();
});
});
function TotalFilesM() {
$.ajax({
type: 'GET',
url: '#Url.Action("mTotalFilesMember")',
dataType: 'json',
data: { PhaseID: $("#Projectlist").val() },
success: function (mTotalMemberFiles) {
$('#TotalFilesMember').html(mTotalMemberFiles);
},
error: function (ex) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
}
});
return false;
}
</script>
You're using $.noConflict(), which removes the definition of $. After that, you need to use jQuery() instead of $().
You can still use $ inside jQuery(document).ready(function($) { ... }). But your second <script> tag doesn't do it this way, it tries to use $(document).ready() at top-level.
In you console it is showing that
~/bower_components/jquery/dist
in the above path you don't have jquery.min.js check the path where you saved your jquery
and if you ever got the error of $ is not a function using jquery
try to add the online link of Jquery if online link of Jquery works then (70%) times it is the issue of your Jquery path
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()});
I have a code that uses to load data passing from the sever side into a jQGrid. I'm using an AngularJS factory method to initiate the call and return received json document. I'm getting Uncaught TypeError: Cannot read property 'loadDataToGrid' of undefined error in chrome console.
JQuery function to load data into jQGrid :-
$(function ($scope,$http,$rootScope,retriveDataFromServer) {
$("#list").jqGrid({
url: retriveDataFromServer.loadDataToGrid($http),
datatype: "json",
mtype: "GET",
colNames: ["Employee First Name", "Employee Last Name", "Contact No"],
colModel: [
{ name: "fname", width: 55 },
{ name: "lname", width: 60 },
{ name: "contactNo", width: 55, align: "right" },
],
pager: "#pager",
rowNum: 10,
autowidth: true,
rowList: [10, 20, 30],
sortname: "fname",
sortorder: "desc",
viewrecords: true,
gridview: true,
autoencode: true,
caption: "Employee Data Grid"
});
});
AngulaJS factory method :-
empApp.factory('retriveDataFromServer',function(){
return{
loadDataToGrid: function($http){
return $http({
method : 'GET',
url : 'http://localhost:8080/IdeaOne/viewall'
}).then(function(response){
return response;
})
}
}
});
html :-
<div ng-app="empApp">
<table id="list"><tr><td></td></tr></table>
<div id="pager"></div>
</div>
when I directly load my data by specifying my url inside jQuery method it works fine.
Someone please point out where did I go wrong.
I have a jqGrid that is filled by a JSON request, the thing is that the request back to the server in base64 encoded data and I need to decode the data before assign it to the grid.
Basically I need something like this:
$( "#grid" ).jqGrid( {
datatype: "json",
colNames: ["id", "Num", "Name", "Code"],
colModel: [
{ name: "id", index: "id", width: 30, sortable: true, resizable: false },
{ name: "num", index: "num", width: 150, sortable: true, resizable: false },
{ name: "name", index: "name", width: 250, sortable: true, resizable: false },
{ name: "code", index: "code", width: 150, sortable: true, resizable: false },
],
multiselect: true,
width: "760",
height: "100%",
heightMetric: "%",
shrinkToFit: false,
rowNum: 20,
rowList: [20,30,60],
pager: "#pager",
sortname: "id",
viewrecords: true,
sortorder: "asc",
headertitles : true,
caption: "Loading...",
beforeProcessing: function(data){
data = decompress(data); // Like this
}
})
The callback function beforeProcessing is the correct place where you can implement all what you need. The exact implementation depends on the format of the data returned by the server. If one uses datatype: "json" then the data returned from the server are typically an object which is serializes as JSON string. jqGrid uses internally jQuery.ajax which automatically decode the JSON string and convert it back to object. So the input data parameter of beforeProcessing callback is the object returned from the server. If you don't use any additional jsonReader option of jqGrid then jqGrid wait the input data in the standard format described here. So you need just fill the expected properties of data object (rows, page, total and records) based on the input data returned from the server. You don't posted any example of the data returned from the server, so I could give you no more detailed examples.
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());
});