webRTC socket.io error transport unknown - socket.io

I get following error from the socket.io server.
"Transport unknown"
Can you please tell me why it's giving this error?
I using this Signalling server Connection.socketURL = 'https://rtcmulticonnection.herokuapp.com:443/';
My code used to work before but suddenly it stopped working.
Using this library to implement webRTC
http://www.rtcmulticonnection.org/docs/
Can anyone help me with this?
Following is my code
<script src="https://cdn.webrtc-experiment.com:443/rmc3.min.js"></script>
<script type="text/javascript">
var Connection = new RTCMultiConnection();
// or a free signaling server
Connection.socketURL = 'https://rtcmulticonnection.herokuapp.com:443/';
Connection.session = {
data: true,
audio: true,
};
Connection.sdpConstraints.mandatory = {
OfferToReceiveAudio: true,
OfferToReceiveVideo: true
};
localvideoContainer = document.getElementById('meeting-preview');
remotevideoContainer = document.getElementById('attendee-xylon');
Connection.onstream = function(event){
var video = event.mediaElement;
console.log(event);
if (event.type === 'local') {
var userinfoDIV = document.createElement('div');
userinfoDIV.className = 'user-video';
userinfoDIV.innerHTML = '<video id="' + event.userid + '" src="' + URL.createObjectURL(event.stream) + '" autoplay muted=true volume=0></vide>' || '<img src="/frontend/images/meeting-preview.png" class="img-responsive" />';
localvideoContainer.appendChild(userinfoDIV);
};
if (event.type === 'remote') {
var userinfoDIV = document.createElement('div');
userinfoDIV.id = event.userid;
userinfoDIV.className = 'user-video meeting-attendees-content timer-icon';
userinfoDIV.innerHTML = '<div id="remote"><video id="' + event.userid + '" src="' + URL.createObjectURL(event.stream) + '" autoplay muted=true volume=0></vide></div><button class="btn btn-custom" type="button" data-toggle="collapse" data-target="#collapse-one" aria-expanded="false" aria-controls="collapse-one">Show Goals / Progress</button><div class="collapse" id="collapse-one"><div class="well attendees-moreinfo"><div class="row"><div class="col-lg-12"><div class="personality-label week-goal"><span>1.</span> Here comes my defined goal for the week</div><div class="personality-bar"><div class="goal-bar-wrap"><div class="meter goal-progress nostripes"><span style="width: 66px; height: 4px;"></span></div></div></div><div class="personality-percentage text-right"><p>66%</p><p></p></div></div></div><div class="row"><div class="col-lg-12"><div class="personality-label week-goal"><span>2.</span> Here comes my defined goal for the week</div><div class="personality-bar"><div class="goal-bar-wrap"><div class="meter goal-progress nostripes"><span style="width: 50px; height: 4px;"></span></div></div></div><div class="personality-percentage text-right"><p>50%</p><p></p></div></div></div><div class="row"><div class="col-lg-12"><div class="personality-label week-goal"><span>3.</span> Here comes my defined goal for the week</div><div class="personality-bar"><div class="goal-bar-wrap"><div class="meter goal-progress nostripes"><span style="width: 80px; height: 4px;"></span></div></div></div><div class="personality-percentage text-right"><p>80%</p><p></p></div></div></div></div></div>' || '<img src="/frontend/images/meeting-preview.png" class="img-responsive" />';
remotevideoContainer.appendChild(userinfoDIV);
};
}
Connection.onclose = Connection.onleave = function(event) {
console.log(event);
$('#'+event.userid).hide();
};
</script>
<script type="text/javascript">
$(document).ready(function(){
var url = window.location.pathname;
Connection.openOrJoin(url.replace('/meetings/joinMeeting/',"") || 'predefined-roomid');
});
</script>

Please check this:
https://github.com/muaz-khan/RTCMultiConnection/releases/tag/3.4.2
Recent release is using latest socket.io.js, so you're asked to use following files instead:
<script src="https://rtcmulticonnection.herokuapp.com/dist/RTCMultiConnection.min.js"></script>
<script src="https://rtcmulticonnection.herokuapp.com/socket.io/socket.io.js"></script>
Please do NOT use rmc3.min.js.

Related

Different datas for each element inside vue-for cycle

I'm new to Vue and since my start some week ago I find myself really happy about it and the way it can be combined with pure javascript.
I'm running this code inside a laravel blade template:
<template v-for = "background in backgrounds" >
<template v-if="currentBackground.path === background.path">
<div class="m-1 background inline-block rounded-circle" style="width: 100px; height: 100px; overflow: hidden">
<img class="img-fluid " :src="background.path" v-on:click="changeBack(background)" :style="circledPositionStyle" v-on:load="inquadraThumb(background)">
</div>
</template>
</template>
And in the script section:
data() { return {
[...]
frontObjects : '',
circledPositionStyle : '' }},
methods: {
[...],
inquadraThumb(back) {
var thumbHeight = 100;
var calculatedThumbPositionY = (back.Ypos * thumbHeight) / 500;
var calculatedThumbPositionX = (back.Xpos * calculatedThumbPositionY) / back.Ypos;
this.circledPositionStyle = "transform: scale(4); height: " + thumbHeight + "px;transform-origin:" + calculatedThumbPositionX + "px " + calculatedThumbPositionY + "px;";
},
Now, the code works just fine, but all the images generated in the loop have the same circledPositionStylestyle applied... How can I manage to have different values for each cycle?
You are referencing circlePositionStyle as the data property, so if that value changes, it will change for every item that refers to it.
Instead, change your function to return the value of curclePositionStyle instead of mutating the data property.
inquadraThumb(back) {
var thumbHeight = 100;
var calculatedThumbPositionY = (back.Ypos * thumbHeight) / 500;
var calculatedThumbPositionX = (back.Xpos * calculatedThumbPositionY) / back.Ypos;
return "transform: scale(4); height: " + thumbHeight + "px;transform-origin:" + calculatedThumbPositionX + "px " + calculatedThumbPositionY + "px;";
}
You will also need to slightly adjust the tag:
<img class="img-fluid " :src="background.path" v-on:click="changeBack(background)" :style="inquadraThumb(background)">

capture image from webcam and store

I want to capture image from webcam and store it to database and file path.but it will not stored in database also in file path.
My view:
<script type="text/javascript" src="<?php echo base_url() ?>assets/dist/js/webcam.min.js"></script>
<div class="form-group">
<div class="col-sm-3 col-md-offset-3 no-print">
<!--<img src="<?php echo base_url(); ?>assets/images/blank.png" >-->
<div class="clearfix" id="my_camera"></div><br>
<button type="button" class="btn btn-info" onClick="take_snapshot()"><i class="fa fa-camera fa-fw"></i>Capture</button>
</div>
<div class="col-md-3 col-md-offset-1 imager" id="results">
<!--<img src="<?php echo base_url(); ?>assets/images/user.png" class="thumbnail" >-->
<h3>Visitors Photo</h3>
</div>
</div>
<script language="JavaScript">
function take_snapshot() {
Webcam.snap(function (data_uri) {
document.getElementById('results').innerHTML =
'<h2>Here is your image:</h2>' +
'<img src="' + data_uri + '"/>';
});
}
</script>
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach('#my_camera');
</script>
if you use https://github.com/jhuckaby/webcamjs/blob/master/DOCS.md you can
Webcam.snap(function (data_uri) {
document.getElementById('results').innerHTML =
'<h2>Here is your image:</h2>' +
'<img src="' + data_uri + '"/>';
});
must be like
Webcam.snap(function (data_uri) {
document.getElementById('results').innerHTML =
'<h2>Here is your image:</h2>' +
'<img src="' + data_uri + '"/>';
Webcam.upload( data_uri, '<?php echo site_url('controlerfunctiontoupload'); ?>', function(code, text) {
if (code == '200') {
alert ('ok');
} else {
alert('error');
}
} );
});
see in documentation
upload_name "webcam"
in controler / function to upload
$filename='test.jpg';
$filepath=FCPATH.'folderWithRights0777/'.$filename;
$result=move_uploaded_file($_FILES['webcam']['tmp_name'], $filepath));
also for insert in database
$this->db->from('files');
$this->db->set('image', $filename);
$this->db->insert();

Node.js long polling event loop breaks the whole code

I am completely new to programming and at this stage of developing my website I need to set up a simple long polling request to get the newest messages from the db and then show them to the client.
I created a messaging system last day and now it saves the messages with all needed relations between messages and users...
Here is what I did :
var express = require('express');
var router = express.Router();
var Conversation = require('../models/conversation');
var Promise = require('promise');
// Get Homepage
router.get('/', function(req, res){
res.render('index');
});
var messages = [];
router.get('/inbox', function(req, res){
var promise = new Promise(function (resolve, reject) {
req.user.conversations.forEach(function(id){
Conversation.getConversationById(id, function(err, conv){
if (conv){
messages.push(conv);
if(messages.length == req.user.conversations.length){
resolve(messages);
messages = [];
}
} else {
console.log(err);
}
});
});
}).then(function(object){
res.render('inbox', {convers: object});
}).catch(function(err){
console.log(err);
});
});
// Add new messages to messagesArray -> mesgArray to display them
var mesgArray = [];
var userIdFor = "";
router.post('/messages', function(req, res){
var convId = req.body.conversationId;
userIdFor = req.user.id;
var promise = new Promise(function(resolve, reject){
Conversation.getConversationById(convId, function(err, conver){
if (err){
console.log(err);
} else {
conver.messages.forEach(function(messa){
mesgArray.push({msg: messa.msg, owner: messa.msgOwner, ownerName: messa.msgOwnerName});
if(mesgArray.length == conver.messages.length){
resolve(mesgArray);
}
});
}
});
}).then(function(object){
res.send({allMessages: object, userId: userIdFor});
mesgArray = [];
userIdFor = "";
}).catch(function(err){
console.log(err);
});
});
// Save posted message to existent conversation
router.post('/saveMsg', function(req, res){
var conversationId = req.body.conversationId;
var messageToSave = req.body.message;
console.log(messageToSave);
console.log(conversationId);
Conversation.getConversationById(conversationId, function(err, conversation){
if (err){
console.log(err);
} else {
Conversation.getConversationById(conversationId, function(err, conversation){
if(err){
console.log(err)
} else {
conversation.messages.push({
msg: messageToSave,
msgOwner: req.user.id,
msgOwnerName: req.user.firstName
});
conversation.save(function(err){
if(err){
console.log(err);
}
})
}
});
}
});
});
module.exports = router;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<!-- REPLAY MESSAGE BOX -->
<div class="contact-form-container hidden-mode">
<div class="row hide-contact text-right">
<img src="/images/close.png">
</div>
<form>
<div class="inbox-all-messages-container">
<div class="row inbox-all-messages">
<!-- Here will be all the messages -->
</div>
<div class="row text-center inbox-send-input">
<div class="col-lg-11 col-md-11 col-sm-11">
<textarea class="inbox-message-response-txt" placeholder="Type your message here"></textarea>
</div>
<div class="col-lg-1 col-md-1 col-sm-1 text-center inbox-message-send-btn">
<p class="inbox-message-send-msg-btn">Send</p>
</div>
</div>
</div>
</form>
</div>
<script>
$(document).ready(function(){
var convId = "";
$('.inbox-messager').on('click', function(){
$('.inbox-all-messages').empty();
var conversationId = this.getAttribute("data-conv-id");
convId = conversationId;
$.ajax({
url: '/messages',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({conversationId: conversationId}),
success: function(response){
response.allMessages.forEach(function(message){
if(message.owner == response.userId){
$('.inbox-all-messages').append(
'<div class="row inbox-message-structure-meNot">'+
'<div class="row inbox-message-header">'+
'<div class="inbox-message-ava col-lg-1 col-md-1 col-sm-1">'+
'<img src="/images/avatar.jpg" class="inbox-message-header-ava-img">'+
'</div>'+
'<div class="inbox-message-header-senderName col-lg-3 col-md-3 col-sm-3">'+
'<p>' + message.ownerName + '</p>'+
'</div>'+
'<div class="col-lg-3 col-lg-offset-5 col-md-3 col-md-offset-5 col-sm-3 col-sm-offset-5 inbox-message-header-sentTime text-right">'+
'<p>24/05/2016</p>'+
'</div>'+
'</div>'+
'<div class="row inbox-message-body">'+
'<div class="col-lg-9 col-lg-offset-1 col-md-9 col-md-offset-1 col-sm-9 col-sm-offset-1 text-left">'+
'<p>' + message.msg + '</p>'+
'</div>'+
'</div>'+
'</div>'
);
} else {
$('.inbox-all-messages').append(
'<div class="row inbox-message-structure-me">'+
'<div class="row inbox-message-header">'+
'<div class="inbox-message-ava col-lg-1 col-md-1 col-sm-1">'+
'<img src="/images/client.jpg" class="inbox-message-header-ava-img">'+
'</div>'+
'<div class="inbox-message-header-senderName col-lg-3 col-md-3 col-sm-3">'+
'<p>' + message.ownerName + '</p>'+
'</div>'+
'<div class="col-lg-3 col-lg-offset-5 col-md-3 col-md-offset-5 col-sm-3 col-sm-offset-5 inbox-message-header-sentTime text-right">'+
'<p>24/05/2016</p>'+
'</div>'+
'</div>'+
'<div class="row inbox-message-body">'+
'<div class="col-lg-9 col-lg-offset-1 col-md-9 col-md-offset-1 col-sm-9 col-sm-offset-1 text-left tester">'+
'<p>' + message.msg + '</p>'+
'</div>'+
'</div>'+
'</div>'
);
}
});
$('.inbox-all-messages').append('<div id="bottom"></div>');
$('.inbox-all-messages').scrollTo('#bottom', 100, "max");
}
});
$('.contact-form-container').removeClass('hidden-mode');
$('.messenger-contaner').addClass('stop-scroll');
});
$('.hide-contact').on('click', function(){
$('.contact-form-container').addClass('hidden-mode');
$('.messenger-contaner').removeClass('stop-scroll');
});
$('.inbox-message-send-msg-btn').on('click', function(){
var messageToSend = $('.inbox-message-response-txt').val();
$.ajax({
url: '/saveMsg',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({message: messageToSend, conversationId: convId}),
success: function(response){
alert('le message a bien ete enregistree');
}
});
});
})
</script>
Now I can send messages and store them in my mongoDB but I need to refresh the page to get the new messages... So I am trying to set up a long polling request but can't find a solution because each time I set a loop in my jQuery code it breaks the whole page and it can't open a conversation no more... If someone can help me to improve my code and set up a simple no technology to get the message without refreshing the page it would be so wonderful!
Sorry for my bad English! And thank you a lot for geing there for us!
If you are completely new to programming as you said, then instead of trying to create the functionality from scratch that you have trouble with, maybe using a working solution would be a better idea.
You can use Socket.io for that sort of thing. It uses long polling and tries to upgrade to WebSocket if it's supported. It's very simple to use. Here is an entire working example of a server that sends requests to the client:
var path = require('path');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'si.html'));
});
io.on('connection', s => {
for (var t = 0; t < 3; t++)
setTimeout(() => s.emit('message', 'message from server'), 1000*t);
});
http.listen(3002, () => console.error('listening on http://localhost:3002/'));
And here is the entire JavaScript code on the client:
var l = document.getElementById('l');
var log = function (m) {
var i = document.createElement('li');
i.innerText = new Date().toISOString()+' '+m;
l.appendChild(i);
}
log('opening socket.io connection');
var s = io();
s.on('connect_error', function (m) { log("error"); });
s.on('connect', function (m) { log("socket.io connection open"); });
s.on('message', function (m) { log(m); });
For more examples and better explanation see the project on GitHub which I created to demonstrate the usage of sending messages to the client.
See also other related questions for more details:
Differences between socket.io and websockets
socket.io no communication between server and client
why web socket behave differently on nodejs ?
getting an error when trying to use socket.io
How to use Socket.io combined with Express.JS

How can I use JSONP to bypass an error with XMLHttpRequest?

Can someone help me to use JSONP so I can bypass this error:
XMLHttpRequest cannot load https://na.api.pvp.net/api/lol/na/v1.3/stats/by-summoner/24332988/ranked?season=SEASON4&?api_key=***********. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 401.
I am having trouble understanding on how to use it.
Here is the code I have right now which gives me the error above. How can I fix this?
//ap.js
var summonerLookUp = function () {
// DECLARE URIs
var nameUri = 'https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/';
var statUri = 'https://na.api.pvp.net/api/lol/na/v1.3/stats/by-summoner/';
var statEnd = '/ranked?season=SEASON4&';
// Expose API Key for demo purposes
var apiKey = '?api_key=******************************';
// Grab summoner names;
var summOne = $('#summOne').val();
var summTwo = $('#summTwo').val();
// declare divIds that need to be modified later;
var divIds = {
summoner : '',
sLevel : 'Summoner Level : ',
sId : 'Summoner ID: ',
champKills : 'Champion Kills: ',
death : 'Death Total: ',
assist : 'Assist Total: ',
kda : 'Avg KDA: ',
win : 'Wins: ',
loss : 'Losses: ',
minions : 'Minion Kills: ',
turrets : 'Turret Kills: '
};
// Declare general errorhandler
var errorHandler = function () {
alert('Sorry, please try again.');
};
// Must fetch summoner info first to get basic summoner data
var fetchSummonerStats = function (summoner) {
$.ajax({
url: nameUri + summoner + apiKey,
type: 'GET',
dataType: 'json',
data: {},
success: function (summData) {
summData = summData[summoner];
// attach .summoner property to summData for divIds later
summData.summoner = summoner;
console.log('SUMM DATA >>', summData);
fetchDetail(summData);
},
error: errorHandler
});
};
// Declare secondary ajax call to fetch stats
// provide summonername an data to attach
var fetchDetail = function (summoner) {
$.ajax({
url: statUri + summoner.id + statEnd + apiKey,
type: 'GET',
dataType: 'json',
data: {},
success: function (summStats) {
// include previous data to attach for divIds
summStats.id = summoner.id;
summStats.summoner = summoner.summoner;
summStats.level = summoner.summonerLevel;
attachStats(summStats);
},
error: errorHandler
});
};
var attachStats = function(summStats) {
var summNumber;
/*
attach a 1 or 2 based on summonername;
if summStats.summoner === xkouki,
summNumber = 1 else it must be summTwo
*/
if (summStats.summoner === summOne) {
summNumber = 1;
} else if (summStats.summoner === summTwo) {
summNumber = 2;
} else {
return errorHandler();
}
// change summoner to summoner as saved in riot api
summStats.summoner = summStats.name;
for (var divId in divIds) {
/*
if divId === summoner
val = 'xkouki';
*/
var val = summStats[divId];
/*
add summonerNumber to the current key in divIds
if divId === summoner
and summNumber === 1
id = summoner1;
etc ...
*/
var id = divId + summNumber;
/*
attach prefix to actual value
if divid === summoner
divIds.summoner = ''
innerHtml = '' + xkouki
*/
document.getElementById(id).innerHtml = divIds[divId] + val;
}
};
// make sure both values exist
if (!summOne || !summTwo) {
alert('Please make sure you have an entry for summoner one & two');
} else {
// loop through this array using forEach and fetchSummoner
[summOne, summTwo].forEach(function (summoner) {
fetchSummonerStats(summoner);
});
}
};
$(document).ready(function() {
$('#list').click(function() {
$('.list').fadeToggle("fast");
});
});
<!DOCTYPE html>
<html>
<head>
<title>League Stats</title>
<link rel="stylesheet" type="css/text" href="styles.css"/>
<link rel="stylesheet" type="css/text" href="font.css"/>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<link href='http://fonts.googleapis.com/css?family=Trade+Winds' rel='stylesheet' type='text/css'>
<script src="app.js"></script>
</head>
<body>
<div class="container">
<header class="title">
<h1>League of Legends Face Off</h1>
<input id="summOne" placeholder="summoner name"/>
<input id="vs" type="button" value="VS" onclick="summonerLookUp();" />
<input id="summTwo" placeholder="summoner name"/>
</header>
<div class="one">
<div id="summoner1"></div>
<div id="sLevel1"></div>
<div id="sID1"></div>
<div id="champKills1"></div>
<div id="death1"></div>
<div id="assist1"></div>
<div id="kda1"></div>
<div id="win1"></div>
<div id="loss1"></div>
<div id="minions1"></div>
<div id="turrets1"></div>
</div>
<div class="logo"><img class="vs" src="vs.png"></div>
<div class="two">
<div id="summoner2"></div>
<div id="sLevel2"></div>
<div id="sID2"></div>
<div id="champKills2"></div>
<div id="death2"></div>
<div id="assist2"></div>
<div id="kda2"></div>
<div id="win2"></div>
<div id="loss2"></div>
<div id="minions2"></div>
<div id="turrets2"></div>
</div>
<button id="list">summoner names</button>
<div class="list" style="display: none;">
xkouki | theoddone | le groot | renesisbuddy | azoh | gripex | bestriven na
<br/>
dyrus | kingtrick | voyboy | robertxlee | iamgosu | balls | fabbbyyy | azingy | megazero
</div>
</div>
</body>
</html>

Jquery Datatable sorting

I'm noob with Jquery DataTables.
I have a very basic question on how to use the sorting plugins:
Have googled a lot on this, but I fail to get proper answers, on how to incorporate them in my code, do we have to just add the script to a ".js" file and add it? or Do we also have to call the function of the plugins?
Can someone point me to a working example with sorting of numeric columns formatted with commas/percentage signs.
The columns with signs or commas are sorted as string. I have seen a lot of references which say to use plugins and then specify sType or sSortableDataType but that doesn't work.
Here's my code: (Please correct me where I'm wrong)
<%# Page Language="C#" AutoEventWireup="true" CodeFile="scorecard_dynamic.aspx.cs" Inherits="Dashboard_scorecard_dynamic" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>new score card</title>
<%--<script src="../js/jquery-1.10.2.min.js"></script>--%>
<style type="text/css" title="currentStyle">
#import "../js/datatable/css/demo_page.css";
#import "../js/datatable/css/demo_table.css";
</style>
<script type="text/javascript" src="../js/datatable/js/jquery.js"></script>
<script type="text/javascript" src="../js/datatable/js/jquery.dataTables.js"></script>
<script src="../js/datatable/Plugins-master/sorting/custom-data-source/percent.js"></script>
<link href="../StyleSheet/LoadingPanel.css" rel="stylesheet" />
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
gettopchannelsplot();
//transpose();
var otable = $('#example').dataTable({
"iDisplayLength": 5,
"aLengthMenu": [[1, 2, 3, 4, 5], [1, 2, 3, 4, "All"]],
"oLanguage": {
"oPaginate": {
"sPrevious": "Previous", //can change text for pagination
"sNext": "Next"
},
//"fnDrawCallback": function (oSettings) {
// alert('DataTables has redrawn the table');
//},
"aoColumns": [
null,
{ "sType": "pct" },
null,
null,
null,
null,
null,
null
],
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [ 0,5,6,7 ] }
]
}
//"sPaginationType": "full_numbers"
});
oTable.fnSort([[3, 'asc']]);
});
var StartDate = '16-oct-2013';
var EndDate = '22-oct-2013';
function transpose() {
var t = $('#example tbody').eq(0);
var r = t.find('tr');
var cols = r.length;
var rows = r.eq(0).find('td').length;
var cell, next, tem, i = 0;
var tb = $('<tbody></tbody>');
while (i < rows) {
cell = 0;
tem = $('<tr></tr>');
while (cell < cols) {
next = r.eq(cell++).find('td').eq(0);
tem.append(next);
}
tb.append(tem);
++i;
}
$('#example').append(tb);
$('#example').show();
}
function gettopchannelsplot() {
//$("#bubbling").show();
//alert('gettopchannelsplot');
var arrListMain = new Array();
var arrList = new Array();
var linkName = 'View Chatter';
var result = ExecuteSynchronously('../SocialMedia.asmx', 'GetTopchannels', { startDate: StartDate, endDate: EndDate });
//tbl_example.empty();
$('#example thead').append("<tr>"
+"<td class='normalBold' align='left'>info</td>"
+ "<td class='normalBold' align='left'>share of voice</td>"
+ "<td class='normalBold' align='left'>total chatter</td>"
+ "<td class='normalBold' align='left'>sentiments</td>"
+ "<td class='normalBold' align='left'>exposure</td>"
+ "<td class='normalBold' align='left'>most popular with</td>"
+ "<td class='normalBold' align='left'>most popular on</td>"
+ "<td class='normalBold' align='left'>link</td>"
+ "</tr>");
var value = new Array();
if (result.d != "" && result.d != null) {
arrListMain = result.d.split('#');
for (var i = 0; i < arrListMain.length; i++) {
var tmp = "<tr>"
+ "<td class='border' width='12%'><a href='../Scorecard.aspx?1'><image src='" + "../" + arrListMain[i].split('^')[7] + "'/></a></td>"
+ " <td class='border' width='12%' align='center'>" + arrListMain[i].split('^')[2] + "%</td>"
+ " <td class='border' width='12%' align='center'> " + arrListMain[i].split('^')[3] + "</td>"
//// + " <td class='border' width='12%' align='center'><label id=label" + i + " >" + Number(arrListMain[i].split('^')[3]).toLocaleString() + "</label></td>"
+ " <td class='border' width='12%' align='center'><image src='" + "../" + arrListMain[i].split('^')[10] + "'/></td>"
+ " <td class='border' width='13%' align='center'>" + arrListMain[i].split('^')[5] + "</td>"
+ " <td class='border' width='13%' align='center'><image src='" + "../" + arrListMain[i].split('^')[8] + "'/></td>"
+ " <td class='border' width='13%' align='center'><image src='" + "../" + arrListMain[i].split('^')[9] + "'/></td>"
+ " <td class='border' width='13%' align='center'><a href='../ChatterAdvanced2.aspx?filter=channel&value=" + arrListMain[i].split('^')[0] + "'>chatter</a></td>"
+ "</tr>";
//alert(tmp);
$('#example tbody').append(tmp);
}
}
$("#bubbling").hide();
}
</script>
<script type="text/javascript">
function ExecuteSynchronously(url, method, args) {
var executor = new Sys.Net.XMLHttpSyncExecutor(); // Instantiate a WebRequest.
var request = new Sys.Net.WebRequest(); // Set the request URL.
request.set_url(url + '/' + method); // Set the request verb.
request.set_httpVerb('POST'); // Set request header.
request.get_headers()['Content-Type'] = 'application/json; charset=utf-8'; // Set the executor.
request.set_executor(executor); // Serialize argumente into a JSON string.
request.set_body(Sys.Serialization.JavaScriptSerializer.serialize(args)); // Execute the request.
request.invoke();
if (executor.get_responseAvailable()) {
return (executor.get_object());
}
return (false);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<AjaxToolkit:ToolkitScriptManager runat="server" ID="ASD">
<Scripts>
<asp:ScriptReference Path="~/js/XMLHttpSyncExecutor.js" ScriptMode="Release" />
<asp:ScriptReference Path="~/App_Code/SocialMedia.cs" />
</Scripts>
</AjaxToolkit:ToolkitScriptManager>
<div>
<div class="bubblingG" id="bubbling">
<span id="bubblingG_1"></span>
<span id="bubblingG_2"></span>
<span id="bubblingG_3"></span>
</div>
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example">
<thead>
</thead>
<tbody>
</tbody>
</table>
</div>
</form>
</body>
</html>
Please excuse my HTML markup formatting.
You need both the "plugin" and set the proper sType according to that plugin. The plugins are really just some very simple functions, that you easily can produce yourself for your own needs and place into your code. Consider this "plugin" that sort percents with commas :
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"normalize": function(n) {
return parseFloat(n.toString().replace(',','.'));
},
"percent-asc": function(a, b) {
a=this.normalize(a);
b=this.normalize(b);
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},
"percent-desc": function(a, b) {
a=this.normalize(a);
b=this.normalize(b);
return ((a < b) ? 1 : ((a > b) ? -1 : 0));
}
});
The above is pretty failsafe. To initialize :
var dataTable = $('#example').dataTable({
aoColumns: [
null,
null,
null,
{ sType: "percent" },
null
],
//...
});
see this working fiddle demonstrating the code above -> http://jsfiddle.net/xK7Ud/

Resources