Trying to integrate this on a site: https://github.com/mangcoding/instagram-feeder
I don't know enough about APIs to get it working for a username instead of a tag. I'm thinking it might have something to do with this line: let instaData = data.edge_hashtag_to_media.edges;
Anyone know how I could accomplish, thanks!
<script charset="utf-8">
(function ($) {
$(window).on('load', function () {
var limit = 20;
$.instagramFeed({
'tag': 'data', // want this to be 'username': 'data',
'get_data': true,
'callback': function (data) {
let instaData = data.edge_hashtag_to_media.edges;
instaData.slice(0, limit).filter(x => x.node.edge_media_to_caption.edges.length > 0)
.forEach(item => {
let node = item.node;
let source = $("#instagram-template").html();
let template = Handlebars.compile(source);
let taken = new Date(node.taken_at_timestamp * 1000)
.toDateString().substr(4);
//change format to month date,year
let created = taken.slice(0, 6) + ',' + taken.slice(6);
let context = {
link: "https://www.instagram.com/p/" + node
.shortcode + "/",
image_url: node.display_url,
countLikes: node.edge_liked_by.count,
caption: node.edge_media_to_caption.edges[0].node
.text,
created: created
};
let html = template(context);
$("#instagramFeed").append(html);
});
$('#instagramFeed').flickity({
cellAlign: 'left',
wrapAround: true,
pageDots: false,
setGallerySize: false,
prevNextButtons: true,
arrowShape: { "x0": 20, "x1": 60, "y1": 40, "x2": 60, "y2": 35, "x3": 25 }
});
}
});
});
})(jQuery);
</script>
Figured it out:
let instaData = data.edge_owner_to_timeline_media.edges;
vs
let instaData = data.edge_hashtag_to_media.edges;
<script charset="utf-8">
(function ($) {
$(window).on('load', function () {
var limit = 20;
$.instagramFeed({
'username': 'myusername',
'get_data': true,
'callback': function (data) {
let instaData = data.edge_owner_to_timeline_media.edges;
instaData.slice(0, limit).filter(x => x.node.edge_media_to_caption.edges.length > 0)
.forEach(item => {
let node = item.node;
let source = $("#instagram-template").html();
let template = Handlebars.compile(source);
let taken = new Date(node.taken_at_timestamp * 1000)
.toDateString().substr(4);
//change format to month date,year
let created = taken.slice(0, 6) + ',' + taken.slice(6);
let context = {
link: "https://www.instagram.com/p/" + node
.shortcode + "/",
image_url: node.display_url,
countLikes: node.edge_liked_by.count,
caption: node.edge_media_to_caption.edges[0].node
.text,
created: created
};
let html = template(context);
$("#instagramFeed").append(html);
});
$('#instagramFeed').flickity({
cellAlign: 'left',
wrapAround: true,
pageDots: false,
setGallerySize: false,
prevNextButtons: true,
arrowShape: { "x0": 20, "x1": 60, "y1": 40, "x2": 60, "y2": 35, "x3": 25 }
});
}
});
});
})(jQuery);
</script>
Related
im having hard time fixing this problem.
i get my data with a get request, after opening developer tools or resizing browser the data is shown.
i have tried some delay or timeout solutions but sadly could not make it work. i need the fastest solution, even if it is a "dirty hack" sort of solution.
im using vue 2.9.1 and chartjs-vue 2.7.1.
thank you!
this is my code:
import {Line} from 'vue-chartjs'
export default {
name: 'Events',
extends: Line,
created: function () {
this.getEvents();
},
data () {
return {
gradient: null,
gradient2: null,
datesList : [],
avgList: []
}
},
methods:{
graphClickEvent(event, array){
var points = this.getElementAtEvent(event)
},
getEvents () {
this.$http.get('http://localhost:8081/users/getAllEvents'
,{headers: {'Content-Type': 'application/json',
'Authorization': localStorage.getItem('token'),}
}).then((res) => {
// res.body = array of event object
var eventsArr = res.body;
var arrayLength = eventsArr.length;
for (var i = 0; i < arrayLength; i++) {
var date = new Date(parseInt(eventsArr[i].startTime))
var day = date.getDate()
var month = date.getMonth()
var year = date.getFullYear()
var hours = date.getHours()
hours = ("0" + hours).slice(-2);
var minutes = date.getMinutes()
minutes = ("0" + minutes).slice(-2);
var str = day;
var str = day + "." + (month + 1) + "." + year +" - " + hours + ":" + minutes
this.datesList.push(str);
}
for (var i = 0; i < arrayLength; i++) {
var evnt = eventsArr[i];
this.avgList.push({label: evnt.name,y: evnt.pulseAverage ,tag: evnt.tag, id: evnt.id });
}
})
}
},
mounted () {
this.gradient = this.$refs.canvas.getContext('2d').createLinearGradient(0, 0, 0, 450)
this.gradient2 = this.$refs.canvas.getContext('2d').createLinearGradient(0, 0, 0, 450)
this.gradient.addColorStop(0, 'rgba(255, 0,0, 0.5)')
this.gradient.addColorStop(0.5, 'rgba(255, 0, 0, 0.25)');
this.gradient.addColorStop(1, 'rgba(255, 0, 0, 0)');
this.gradient2.addColorStop(0, 'rgba(0, 231, 255, 0.9)')
this.gradient2.addColorStop(0.5, 'rgba(0, 231, 255, 0.35)');
this.gradient2.addColorStop(1, 'rgba(0, 231, 255, 0)');
this.renderChart({
labels: this.datesList,
datasets: [
{
label: 'Events',
borderColor: '#05CBE1',
pointBackgroundColor: 'white',
pointBorderColor: 'white',
borderWidth: 2,
backgroundColor: this.gradient2,
data: this.avgList
},
]
,
options: {
scales: {
xAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
}
//
,{ onClick: function(event){
var activePoints = this.getElementAtEvent(event)
var firstPoint = activePoints[0];
if(firstPoint !== undefined){
var label = this.data.labels[firstPoint._index];
var value = this.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
var location = "eventGraph?id=" + value.id;
window.location.href = location;
}
}
, responsive: true, maintainAspectRatio: false,fontColor: '#66226',
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
title: function(tooltipItems, data) {
var evnt = data.datasets[0].data[tooltipItems[0].index].label;
return evnt
},
label: function(tooltipItems, data) {
var avg = 'Average heart: ' + [tooltipItems.yLabel];
var evnt = 'Type: ' + data.datasets[0].data[tooltipItems.index].tag;
return [avg,evnt];
}
}
}
})
}
}
It sounds like an initialization issue where the chart is initially rendered in an element that is not visible or it can't determine the size of the parent.
I see similar issues doing a Google:
ChartJS won't draw graph inside bootstrap tab until window resize #17
Charts rendered in hidden DIVs will not display until browser resize #29
Chart.js not rendering properly until window resize or toggling line in legend
One suggested doing a chart refresh when everything is visible:
setTimeout(function() { myChart.update(); },1000);
In think in vue this could be done in the mount function.
I'm sure there is a more elegant way to handle this with a watch function or something similar for instance.
Updated:
As mentioned in the comments, I've seen references to people firing a window resize event manually using:
window.dispatchEvent(new Event('resize'));
I think it would probably work in the mounted function of the vue component:
export default {
name: 'graphs-component',
mounted: function(){
window.dispatchEvent(new Event('resize'));
}
}
You might even wrap it in a setTimeout to ensure everything is loaded.
Here I'm working on Highcharts time series chart with live streaming data, based on the sample jsfiddle. In the fiddle there shows 4 lines named as input1, input2, input3, & input 4 and it is updated with live random data but in my actual project the input values are updated via MQTT. In actual project, sometimes, when we push streaming data, there will be increase or decrease in no: of inputs (such as input5, input6 like wise). So how can we add new line or remove line dynamically in time series chart with streaming data.
javascript code :
$(function() {
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
$('#container').highcharts({
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function() {
// set up the updating of the chart each second
var series = this.series;
var length = series.length;
setInterval(function() {
var x = (new Date()).getTime(), // current time
a0 = Math.random();
a1 = Math.random();
a2 = Math.random();
series[0].addPoint([x, Math.random()], true, true);
for (var i = 1; i < length; i++) {
series[i].addPoint([x, Math.random()], false, true);
}
}, 1000);
}
}
},
title: {
text: 'Live random data'
},
legend: {
enabled: true
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 2);
}
},
exporting: {
enabled: false
},
series: [{
name: 'input1',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}, {
name: 'input2',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}, {
name: 'input3',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}, {
name: 'input4',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}]
});
});
});
Using DataTables and Buttons (NOT TableTools, which is retired) extension. Some cells have progressbars and small icons. Is there a way to export these images (or at least their titles) to PDF? Found some possible hacks on this page, but all of them were for retired TableTools.
Checked https://datatables.net/reference/button/pdf and https://datatables.net/reference/api/buttons.exportData%28%29 but couldn't find any method to achieve this goal. Tested by adding this code:
stripHtml: false
but whole HTML code (like img src=...) was included in PDF file instead of images.
If exporting images isn't possible, is there a way to export at least alt or title attribute of each image? That would be enough.
I assume you are using pdfHtml5. dataTables is using pdfmake in order to export pdf files. When pdfmake is used from within a browser it needs images to be defined as base64 encoded dataurls.
Example : You have rendered a <img src="myglyph.png"> in the first column of some of the rows - those glyphs should be included in the PDF. First create an Image reference to the glyph :
var myGlyph = new Image();
myGlyph.src = 'myglyph.png';
In your customize function you must now
1) build a dictionary with all images that should be included in the PDF
2) replace text nodes with image nodes to reference images
buttons : [
{
extend : 'pdfHtml5',
customize: function(doc) {
//ensure doc.images exists
doc.images = doc.images || {};
//build dictionary
doc.images['myGlyph'] = getBase64Image(myGlyph);
//..add more images[xyz]=anotherDataUrl here
//when the content is <img src="myglyph.png">
//remove the text node and insert an image node
for (var i=1;i<doc.content[1].table.body.length;i++) {
if (doc.content[1].table.body[i][0].text == '<img src="myglyph.png">') {
delete doc.content[1].table.body[i][0].text;
doc.content[1].table.body[i][0].image = 'myGlyph';
}
}
},
exportOptions : {
stripHtml: false
}
}
Here is a an example of a getBase64Image function
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
return canvas.toDataURL("image/png");
}
If you just want to show the title of images in the PDF - or in any other way want to manipulate the text content of the PDF - then it is a little bit easier. The content of each column in each row can be formatted through the exportOptions.format.body callback :
buttons : [
{
extend : 'pdfHtml5',
exportOptions : {
stripHtml: false
format: {
body: function(data, col, row) {
var isImg = ~data.toLowerCase().indexOf('img') ? $(data).is('img') : false;
if (isImg) {
return $(data).attr('title');
}
return data;
}
}
}
]
The reason format.body cannot be used along with images is that is only let us pass data back to the text node part of the PDF document.
See also
http://pdfmake.org/#/gettingstarted (look for Images section)
https://github.com/bpampuch/pdfmake/blob/master/examples/images.js
Since no suggestions received, I had to make a hack in order to get PDF file formatted the way I want.
In case someone has the same issue, you can use hidden span to display image alt/title near image itself. I'm sure it's not the best practice, but it will do the trick. So the code will look like:
<img src='image.png' alt='some_title'/><span class='hidden'>some_title</span>
This way datatables will show only the image, while PDF file will contain text you need.
This is my CODE!
HTML
<div class="dt-btn"></div>
<table>
<thead><tr><th>No</th><th>IMAGE</th><th>NOTE</th></tr></thead>
<tbody>
<tr>
<td>{{$NO}}</td>
<td>{{$imgSRC}}</td>
<td>{{$NAME}}<br />
{{$GRADE}}<br />
{{$PROFILE}}<br />
{{$CODE}}<br />
</td>
</tr>
</tbody>
</table>
JAVASCRIPT
$.extend( true, $.fn.dataTable.defaults, {
buttons: [{
text: '<i class="bx bx-download font-medium-1"></i><span class="align-middle ml-25">Download PDF</span>',
className: 'btn btn-light-secondary mb-1 mx-1 dnPDF',
extend: 'pdfHtml5',
pageSize: 'A4',
styles: {
fullWidth: { fontSize: 11, bold: true, alignment: 'left', margin: [0,0,0,0] }
},
action: function ( e, dt, node, config ) {
var that = this;
setTimeout( function () {
$.fn.dataTable.ext.buttons.pdfHtml5.action.call(that, e, dt, node, config);
$( ".donePDF" ).remove();
$( ".dnPDF" ).prop("disabled", false);
}, 50);
},
customize: function(doc) {
doc.defaultStyle.fontSize = 11;
doc.defaultStyle.alignment = 'left';
doc.content[1].table.dontBreakRows = true;
if (doc) {
for (var i = 1; i < doc.content[1].table.body.length; i++) {
// 1st Column - display IMAGE
var imgtext = doc.content[1].table.body[i][0].text;
delete doc.content[1].table.body[i][0].text;
jQuery.ajax({
type: "GET",
dataType: "json",
url: "{{route('base64')}}",
data: { src: imgtext },
async: false,
success: function(resp) {
//console.log(resp.data);
doc.content[1].table.body[i][0] = {
margin: [0, 0, 0, 3],
alignment: 'center',
image: resp.data,
width: 80,
height: 136
};
}
});
// 2nd Column - display NOTE(4 line)
var bodyhtml = doc.content[1].table.body[i][1].text;
var bodytext = bodyhtml.split("\n");
var bodystyle = []
for (var j = 0; j < bodytext.length; j++) {
switch(j) {
case 0:
// NAME
var _text = { margin:[0, 0, 0, 3], color:"#000000", fillColor:'#ffffff', bold:true, fontSize:13, alignment:'center', text:bodytext[j] };
break;
case 1:
// GRADE
var _text = { margin:[0, 0, 0, 3], color:"blue", fillColor:'#ffffff', bold:false, fontSize:11, alignment:'left', text:bodytext[j] };
break;
case 3:
// CODE
var _text = { margin:[0, 0, 0, 3], color:"#000000", fillColor:'#ffffff', bold:true, fontSize:11, alignment:'left', text:bodytext[j] };
break;
default:
// OTHERS
var _text = { margin:[0, 0, 0, 3], color:"#000000", fillColor:'#ffffff', bold:false, fontSize:11, alignment:'left', text:bodytext[j] };
break;
}
bodystyle[j] = _text;
};
doc.content[1].table.body[i][1] = bodystyle;
}
}
},
exportOptions: {
columns: [ 1, 2 ],
stripNewlines: false,
stripHtml: true,
modifier: {
page: 'all' // 'all', 'current'
},
}
}],
columns: [
{ className: 'iNo', orderable: true, visible: true},
{ className: 'iIMG', orderable: false, visible: false },
{ className: 'iPDF', orderable: false, visible: false, responsivePriority: 10001 } ]
});
var table = $('#table').DataTable();
table.buttons().container().appendTo('.dt-btn');
$('.dnPDF').on('click', function(){
$(this).append('<span class="spinner-border spinner-border-sm donePDF" role="status" aria-hidden="true"></span>').closest('button').attr('disabled','disabled');
});
$.fn.dataTable.Buttons.defaults.dom.container.className = '';
$.fn.dataTable.Buttons.defaults.dom.button.className = 'btn';
PHP
public function base64(Request $request)
{
$request->validate([
'src' => 'required|string'
]);
$fTYPE = pathinfo($request->src, PATHINFO_EXTENSION);
$fDATA = #file_get_contents($request->src);
$imgDATA = base64_encode($fDATA);
$imgSRC = 'data:image/' . $fTYPE . ';base64,'.$imgDATA;
$error = ($imgDATA!='') ? 0 : 1;
$msg = ($error) ? 'Error' : 'Success';
return response()->json([ 'msg' => $msg, 'error'=> $error, 'data' => $imgSRC]);
}
[Sample][1]: https://i.stack.imgur.com/35Wlm.jpg
In addition to davidkonrad's answer. I created dynamically all base64 images and used them in Datatables pdfmake like this:
for (var i = 1; i < doc.content[2].table.body.length; i++) {
if (doc.content[2].table.body[i][1].text.indexOf('<img src=') !== -1) {
html = doc.content[2].table.body[i][1].text;
var regex = /<img.*?src=['"](.*?)['"]/;
var src = regex.exec(html)[1];
var tempImage = new Image();
tempImage.src = src;
doc.images[src] = getBase64Image(tempImage)
delete doc.content[2].table.body[i][1].text;
doc.content[2].table.body[i][1].image = src;
doc.content[2].table.body[i][1].fit = [50, 50];
}
//here i am removing the html links so that i can use stripHtml: true,
if (doc.content[2].table.body[i][2].text.indexOf('<a href="details.php?') !== -1) {
html = $.parseHTML(doc.content[2].table.body[i][2].text);
delete doc.content[2].table.body[i][1].text;
doc.content[2].table.body[i][2].text = html[0].innerHTML;
}
}
I'm using this code for create a booking system:
http://jsfiddle.net/9zjwdypc/
This example working fine, but I can't add the internalization and others option.
I tried this sample code:
$('#dpd1').datepicker({
language: 'it'
});
$('#dpd1').datepicker({
format: "dd-mm-yyyy",
weekStart: 1,
language: "fr",
autoclose: true,
todayHighlight: true
});
$('#dpd2').datepicker({
format: "dd-mm-yyyy",
weekStart: 1,
language: "fr",
autoclose: true,
todayHighlight: true
});
$(window).load(function(){
var nowTemp = new Date();
var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
var checkin = $('#dpd1').datepicker({
onRender: function(date) {
return date.valueOf() < now.valueOf() ? 'disabled' : '';
}
}).on('changeDate', function(ev) {
if (ev.date.valueOf() > checkout.date.valueOf()) {
var newDate = new Date(ev.date)
newDate.setDate(newDate.getDate() + 1);
checkout.setValue(newDate);
}
checkin.hide();
$('#dpd2')[0].focus();
}).data('datepicker');
var checkout = $('#dpd2').datepicker({
onRender: function(date) {
return date.valueOf() <= checkin.date.valueOf() ? 'disabled' : '';
}
}).on('changeDate', function(ev) {
checkout.hide();
}).data('datepicker');
});
adding:
<script src="http://eternicode.github.io/bootstrap-datepicker/bootstrap-datepicker/js/locales/bootstrap-datepicker.fr.js"></script>
The same using this:
$(document).ready(function(){
$.fn.datepicker.defaults.language = 'it';
});
This is the error:
TypeError: $.fn.datepicker.dates is undefined
You have include french language file and then try to use italian language...
My .ascx page has two jqGrids
$(document).ready(function () {
var searchText = "";
$("#cclist").jqGrid({
//url: ResolveUrl() + '/CC_DoctorList',
datatype: 'local',
// postData: { "CaseNo": CaseNo },
mtype: 'POST',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (jsondata) { return JSON.stringify(jsondata); },
jsonReader: { repeatitems: false, root: "d.rows", page: "d.page", total: "d.total", records: "d.records" },
colNames: ['Remove', 'DoctorID', 'Last Name', 'First Name', 'Address'],
colModel: [
{ name: 'RemoveAction', width: 80, fixed: true, sortable: false, resize: false, align: "center" },
{ name: 'ID', index: 'ID', width: 50, sortable: false, hidden: false },
{ name: 'LastName', index: 'LastName', width: 100, hidden: false, sortable: false },
{ name: 'FirstName', index: 'FirstName', width: 100, hidden: false, sortable: false },
{ name: 'Address', width: 420, hidden: false, sortable: false,
jsonmap: function (obj) {
var street = obj.Address.Address1
var city = obj.Address.City
var state = obj.Address.StateProvince
var zip = obj.Address.PostalCode
if (street != '') { street = street + ', ' }
if (city != '') { city = city + ', ' }
if (state != '') { state = state + ', ' }
var Address = street + city + state + zip
return Address
}
}
],
gridComplete: function () { addDeleteIcon(); },
pager: '#ccpager',
rowNum: 100,
rowList: [100, 200],
sortname: 'LastName',
sortorder: 'desc',
viewrecords: true,
gridview: true,
height: "100%",
caption: 'Send Copy of Report To:',
multiselect: false,
shrinkToFit: false,
loadui: "disabled"
})//.jqGrid('navGrid', '#ccpager', { edit: false, add: true, del: false, search: true });
$("#list").jqGrid({
url: ResolveUrl() + '/DoctorList',
datatype: 'local',
postData: { "searchText": searchText },
mtype: 'POST',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (jsondata) { return JSON.stringify(jsondata); },
jsonReader: { repeatitems: false, root: "d.rows", page: "d.page", total: "d.total", records: "d.records" },
colNames: ['Add', 'DoctorID', 'Last Name', 'First Name', 'Address'],
colModel: [
{ name: 'AddAction', width: 80, fixed: true, sortable: false, resize: false, align: "center" },
{ name: 'ID', index: 'ID', width: 50, sortable: false, hidden: false },
{ name: 'LastName', index: 'LastName', width: 100, hidden: false, frozen: true, sortable: false },
{ name: 'FirstName', index: 'FirstName', width: 100, hidden: false, frozen: true, sortable: false },
{ name: 'Address', width: 420, hidden: false, sortable: false,
jsonmap: function (obj) {
var street = obj.Address.Address1
var city = obj.Address.City
var state = obj.Address.StateProvince
var zip = obj.Address.PostalCode
if (street != '') { street = street + ', ' }
if (city != '') { city = city + ', ' }
if (state != '') { state = state + ', ' }
var Address = street + city + state + zip
return Address
}
}],
gridComplete: function () {
var ids = jQuery("#list").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var cl = ids[i];
var rd = $("#list").getRowData(cl);
var imageid = 'addImg_' + rd['ID']
be = "<div><image style='height:22px;width:20px;' alt='' src='" + ResolveUrl('//img/icons/add_black.png') + "'></image></div>"//"<input type='button' value='Remove' onclick=\"jQuery('#rowed2').editRow('" + cl + "');\" />";
jQuery("#list").jqGrid('setRowData', ids[i], { AddAction: be });
}
},
pager: '#pager',
rowNum: 5,
rowList: [5, 10, 15, 20],
sortname: 'LastName',
sortorder: 'desc',
viewrecords: true,
gridview: true,
caption: 'Search Result',
multiselect: false,
height: "100%",
shrinkToFit: false
})
jQuery("#list").click(function (e) {
var el = e.target;
if (el.nodeName !== "TD") {
el = $(el, this.rows).closest("td");
}
var iCol = $(el).index();
var row = $(el, this.rows).closest("tr.jqgrow");
var rowId = row[0].id;
var noMatch = 0;
if (iCol == 0) {
var rd = $("#list").getRowData(rowId);
var DoctorID = rd['ID'];
//check if the doc already exists in the cc doc list
var ids = jQuery("#cclist").jqGrid('getDataIDs');
if (ids.length == 0) {
ids.length = ids.length + 1;
}
for (var i = 0; i < ids.length; i++) {
var cl = ids[i];
var ccrd = $("#cclist").getRowData(cl);
var newrowid = ids.length + 1;
var ccDoctorID = ccrd['ID'];
if (DoctorID != ccDoctorID) {
noMatch = noMatch + 1;
if (noMatch == ids.length) {
var deleteImageIcon = "<div><image style='height:22px;width:20px;' alt='' src='" + ResolveUrl('//img/icons/trashbin.png') + "'></image></div>"; // onclick=\"jQuery('#cclist').delRowData('" + rowId + "');\"
jQuery("#cclist").jqGrid('addRowData', newrowid, { RemoveAction: deleteImageIcon, ID: rd['ID'], LastName: rd['LastName'], FirstName: rd['FirstName'], Number: rd['Number'], Address: rd['Address'] });
// alert(ids);
// var hdnids = document.getElementById('hdnDocIDs').value;
// hdnids.value = rd['ID'];
//var hdnids = jQuery("#<%=hdnDocIds.ClientID %>").val();
//alert(hdnids);
//hdnids = rd['ID'];
//alert('hdnvalue :' + hdnids);
//$("#<%=hdnlbldocs.ClientID%>").val(rd['ID'].toString() + ',' + $("#<%=hdnlbldocs.ClientID%>").val())
//$("#<%=hdnlbldocs.ClientID%>").val(rd['ID']);
//alert($("#<%=hdnlbldocs.ClientID%>").val());
//alert($("#<%=hdnlbldocs.ClientID%>").val(rd['ID'] + ','));
//alert($("#<%=hdnlbldocs.ClientID%>").val());
//jQuery("#<%=hdnDocIDs.ClientID %>").val(rd['ID']);
//The below works as expected - working.
jQuery("#<%=hdnDocIDs.ClientID %>").val(jQuery("#<%=hdnDocIDs.ClientID%>").val() + ',' + rd['ID']);
alert('All hdn ids : ' + jQuery("#<%=hdnDocIDs.ClientID%>").val());
//Using hidden fields it concatenates the doc ids - working
//alert('in side the for loop ID 2:' + rd['ID'] + ' DoctorID : ' + DoctorID);
//var furl = ResolveUrl() + '/AddCCDoctor';
//var furl = '';
//var param = '{"CaseNo":"' + CaseNo + '", "DoctorID":"' + DoctorID + '" }';
//var param = '{ "DoctorID":"' + DoctorID + '" }';
//var callback = function (msg) { dataHasChanged(); jQuery("#cclist").trigger("reloadGrid"); };
// ajaxJsonCall(furl, param, callback);
//jQuery("#cclist").jqGrid('setGridParam', {datatype: 'json'}).trigger('reloadGrid');
function (msg) { dataHasChanged(); jQuery("#cclist").trigger("reloadGrid"); };
}
}
}
}
});
The #list grid gets loaded by clicking on the Search button that I have not posted in the above code. Once the #list jqGrid is loaded users can click on the rows they are interested in and those rows are added to the #cclist jqgrid.
Now, to make the .ascx more generic I need to be able to write a public method in the code behind to return all the rows IDs (doctorIDs) that are added to the #cclist jqGrid and save the IDs to the database.
Can someone help me out on how to do this?
Thanks for taking time to read my post and posting your comments.
I put the code in a function as below and it is working as expected.
var hiddenField = $("#<%= hdnDocIDs.ClientID %>");
var selectedValues = "";
function updateSelectedRowsHidden() {
var selectedRows = [];
selectedRows = $('#cclist').jqGrid('getDataIDs');
selectedValues = "";
hiddenField.val("");
for (var i = 0; i < selectedRows.length; i++) {
var myRow = $('#cclist').jqGrid('getRowData', selectedRows[i]);
selectedValues = selectedValues + myRow.ID + ",";
}
hiddenField.val(selectedValues);
}
You see this answer, here I'm getting data out of selected rows and sending that to server method. Have a save button in your page like the one in answer
Now in your case you want data from entire grid. So for you code will be like this.
$('#clickMe').click(function() {
var rowsOnPage=[];
var docId=[];
rowsOnPage=$('#cclist').jqGrid('getDataIDs');
for(var i=0;i<rowsOnPage.length;i++)
{
docId.push(rowsOnPage[i].ID);
}
$.ajax({
type: 'POST',
url: '#Url.Action("editMe")',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({DoctorID:docID })
dataType: "json",
success: function() {
$('#grid').trigger("reloadGrid");
},
error: function() {
alert("error");
}
});
});
and the server method(in ASP.NET MVC) which will be your code behind method in your approach will be like this.
//depends upon dataType of DoctorID(int or string)
public ActionResult editMe(string[] DoctorID)
{
}