So, I have this HTML5 chatting script which requires users to input their name and email to start chatting. The script grabs the users display picture from gavatar. I'm trying to change that to make it take a webcam snapshot from the users computer and set that as a display picture.
I've seen a few examples of the usage of HTML5 to access the users webcam but I can't seem to figure out how to automatically take the snapshot and set it as the users display picture.
Here's my current code.
$(document).ready(function(){
// Run the init method on document ready:
chat.init();
});
var chat = {
// data holds variables for use in the class:
data : {
lastID : 0,
noActivity : 0
},
// Init binds event listeners and sets up timers:
init : function(){
// Using the defaultText jQuery plugin, included at the bottom:
$('#name').defaultText('Nickname');
$('#email').defaultText('Email');
// Converting the #chatLineHolder div into a jScrollPane,
// and saving the plugin's API in chat.data:
chat.data.jspAPI = $('#chatLineHolder').jScrollPane({
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12
}).data('jsp');
// We use the working variable to prevent
// multiple form submissions:
var working = false;
// Logging a person in the chat:
$('#loginForm').submit(function(){
if(working) return false;
working = true;
// Using our tzPOST wrapper function
// (defined in the bottom):
$.tzPOST('login',$(this).serialize(),function(r){
working = false;
if(r.error){
chat.displayError(r.error);
}
else chat.login(r.name,r.gravatar);
});
return false;
});
// Submitting a new chat entry:
$('#submitForm').submit(function(){
var text = $('#chatText').val();
if(text.length == 0){
return false;
}
if(working) return false;
working = true;
// Assigning a temporary ID to the chat:
var tempID = 't'+Math.round(Math.random()*1000000),
params = {
id : tempID,
author : chat.data.name,
gravatar : chat.data.gravatar,
text : text.replace(/</g,'<').replace(/>/g,'>')
};
// Using our addChatLine method to add the chat
// to the screen immediately, without waiting for
// the AJAX request to complete:
chat.addChatLine($.extend({},params));
// Using our tzPOST wrapper method to send the chat
// via a POST AJAX request:
$.tzPOST('submitChat',$(this).serialize(),function(r){
working = false;
$('#chatText').val('');
$('div.chat-'+tempID).remove();
params['id'] = r.insertID;
chat.addChatLine($.extend({},params));
});
return false;
});
// Logging the user out:
$('a.logoutButton').live('click',function(){
$('#chatTopBar > span').fadeOut(function(){
$(this).remove();
});
$('#submitForm').fadeOut(function(){
$('#loginForm').fadeIn();
});
$.tzPOST('logout');
return false;
});
// Checking whether the user is already logged (browser refresh)
$.tzGET('checkLogged',function(r){
if(r.logged){
chat.login(r.loggedAs.name,r.loggedAs.gravatar);
}
});
// Self executing timeout functions
(function getChatsTimeoutFunction(){
chat.getChats(getChatsTimeoutFunction);
})();
(function getUsersTimeoutFunction(){
chat.getUsers(getUsersTimeoutFunction);
})();
},
// The login method hides displays the
// user's login data and shows the submit form
login : function(name,gravatar){
chat.data.name = name;
chat.data.gravatar = gravatar;
$('#chatTopBar').html(chat.render('loginTopBar',chat.data));
$('#loginForm').fadeOut(function(){
$('#submitForm').fadeIn();
$('#chatText').focus();
});
},
// The render method generates the HTML markup
// that is needed by the other methods:
render : function(template,params){
var arr = [];
switch(template){
case 'loginTopBar':
arr = [
'<span><img src="',params.gravatar,'" width="23" height="23" />',
'<span class="name">',params.name,
'</span>Logout</span>'];
break;
case 'chatLine':
arr = [
'<div class="chat chat-',params.id,' rounded"><span class="gravatar"><img src="',params.gravatar,
'" width="23" height="23" onload="this.style.visibility=\'visible\'" />','</span><span class="author">',params.author,
':</span><span class="text">',params.text,'</span><span class="time">',params.time,'</span></div>'];
break;
case 'user':
arr = [
'<div class="user" title="',params.name,'"><img src="',
params.gravatar,'" width="30" height="30" onload="this.style.visibility=\'visible\'" /></div>'
];
break;
}
// A single array join is faster than
// multiple concatenations
return arr.join('');
},
// The addChatLine method ads a chat entry to the page
addChatLine : function(params){
// All times are displayed in the user's timezone
var d = new Date();
if(params.time) {
// PHP returns the time in UTC (GMT). We use it to feed the date
// object and later output it in the user's timezone. JavaScript
// internally converts it for us.
d.setUTCHours(params.time.hours,params.time.minutes);
}
params.time = (d.getHours() < 10 ? '0' : '' ) + d.getHours()+':'+
(d.getMinutes() < 10 ? '0':'') + d.getMinutes();
var markup = chat.render('chatLine',params),
exists = $('#chatLineHolder .chat-'+params.id);
if(exists.length){
exists.remove();
}
if(!chat.data.lastID){
// If this is the first chat, remove the
// paragraph saying there aren't any:
$('#chatLineHolder p').remove();
}
// If this isn't a temporary chat:
if(params.id.toString().charAt(0) != 't'){
var previous = $('#chatLineHolder .chat-'+(+params.id - 1));
if(previous.length){
previous.after(markup);
}
else chat.data.jspAPI.getContentPane().append(markup);
}
else chat.data.jspAPI.getContentPane().append(markup);
// As we added new content, we need to
// reinitialise the jScrollPane plugin:
chat.data.jspAPI.reinitialise();
chat.data.jspAPI.scrollToBottom(true);
},
// This method requests the latest chats
// (since lastID), and adds them to the page.
getChats : function(callback){
$.tzGET('getChats',{lastID: chat.data.lastID},function(r){
for(var i=0;i<r.chats.length;i++){
chat.addChatLine(r.chats[i]);
}
if(r.chats.length){
chat.data.noActivity = 0;
chat.data.lastID = r.chats[i-1].id;
}
else{
// If no chats were received, increment
// the noActivity counter.
chat.data.noActivity++;
}
if(!chat.data.lastID){
chat.data.jspAPI.getContentPane().html('<p class="noChats">No chats yet</p>');
}
// Setting a timeout for the next request,
// depending on the chat activity:
var nextRequest = 1000;
// 2 seconds
if(chat.data.noActivity > 3){
nextRequest = 2000;
}
if(chat.data.noActivity > 10){
nextRequest = 5000;
}
// 15 seconds
if(chat.data.noActivity > 20){
nextRequest = 15000;
}
setTimeout(callback,nextRequest);
});
},
// Requesting a list with all the users.
getUsers : function(callback){
$.tzGET('getUsers',function(r){
var users = [];
for(var i=0; i< r.users.length;i++){
if(r.users[i]){
users.push(chat.render('user',r.users[i]));
}
}
var message = '';
if(r.total<1){
message = 'No one is online';
}
else {
message = r.total+' '+(r.total == 1 ? 'person':'people')+' online';
}
users.push('<p class="count">'+message+'</p>');
$('#chatUsers').html(users.join(''));
setTimeout(callback,15000);
});
},
// This method displays an error message on the top of the page:
displayError : function(msg){
var elem = $('<div>',{
id : 'chatErrorMessage',
html : msg
});
elem.click(function(){
$(this).fadeOut(function(){
$(this).remove();
});
});
setTimeout(function(){
elem.click();
},5000);
elem.hide().appendTo('body').slideDown();
}
};
// Custom GET & POST wrappers:
$.tzPOST = function(action,data,callback){
$.post('php/ajax.php?action='+action,data,callback,'json');
}
$.tzGET = function(action,data,callback){
$.get('php/ajax.php?action='+action,data,callback,'json');
}
// A custom jQuery method for placeholder text:
$.fn.defaultText = function(value){
var element = this.eq(0);
element.data('defaultText',value);
element.focus(function(){
if(element.val() == value){
element.val('').removeClass('defaultText');
}
}).blur(function(){
if(element.val() == '' || element.val() == value){
element.addClass('defaultText').val(value);
}
});
return element.blur();
}
And this is the PHP file for grabbing the users DP from gravatar.
<?php
class ChatUser extends ChatBase{
protected $name = '', $gravatar = '';
public function save(){
DB::query("
INSERT INTO webchat_users (name, gravatar)
VALUES (
'".DB::esc($this->name)."',
'".DB::esc($this->gravatar)."'
)");
return DB::getMySQLiObject();
}
public function update(){
DB::query("
INSERT INTO webchat_users (name, gravatar)
VALUES (
'".DB::esc($this->name)."',
'".DB::esc($this->gravatar)."'
) ON DUPLICATE KEY UPDATE last_activity = NOW()");
}
}
?>
Also another bit of code.
<?php
/* The Chat class exploses public static methods, used by ajax.php */
class Chat{
public static function login($name,$email){
if(!$name || !$email){
throw new Exception('Fill in all the required fields.');
}
if(!filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)){
throw new Exception('Your email is invalid.');
}
// Preparing the gravatar hash:
$gravatar = md5(strtolower(trim($email)));
$user = new ChatUser(array(
'name' => $name,
'gravatar' => $gravatar
));
// The save method returns a MySQLi object
if($user->save()->affected_rows != 1){
throw new Exception('This nick is in use.');
}
$_SESSION['user'] = array(
'name' => $name,
'gravatar' => $gravatar
);
return array(
'status' => 1,
'name' => $name,
'gravatar' => Chat::gravatarFromHash($gravatar)
);
}
public static function checkLogged(){
$response = array('logged' => false);
if($_SESSION['user']['name']){
$response['logged'] = true;
$response['loggedAs'] = array(
'name' => $_SESSION['user']['name'],
'gravatar' => Chat::gravatarFromHash($_SESSION['user']['gravatar'])
);
}
return $response;
}
public static function logout(){
DB::query("DELETE FROM webchat_users WHERE name = '".DB::esc($_SESSION['user']['name'])."'");
$_SESSION = array();
unset($_SESSION);
return array('status' => 1);
}
public static function submitChat($chatText){
if(!$_SESSION['user']){
throw new Exception('You are not logged in');
}
if(!$chatText){
throw new Exception('You haven\' entered a chat message.');
}
$chat = new ChatLine(array(
'author' => $_SESSION['user']['name'],
'gravatar' => $_SESSION['user']['gravatar'],
'text' => $chatText
));
// The save method returns a MySQLi object
$insertID = $chat->save()->insert_id;
return array(
'status' => 1,
'insertID' => $insertID
);
}
public static function getUsers(){
if($_SESSION['user']['name']){
$user = new ChatUser(array('name' => $_SESSION['user']['name']));
$user->update();
}
// Deleting chats older than 5 minutes and users inactive for 30 seconds
DB::query("DELETE FROM webchat_lines WHERE ts < SUBTIME(NOW(),'0:5:0')");
DB::query("DELETE FROM webchat_users WHERE last_activity < SUBTIME(NOW(),'0:0:30')");
$result = DB::query('SELECT * FROM webchat_users ORDER BY name ASC LIMIT 18');
$users = array();
while($user = $result->fetch_object()){
$user->gravatar = Chat::gravatarFromHash($user->gravatar,30);
$users[] = $user;
}
return array(
'users' => $users,
'total' => DB::query('SELECT COUNT(*) as cnt FROM webchat_users')->fetch_object()->cnt
);
}
public static function getChats($lastID){
$lastID = (int)$lastID;
$result = DB::query('SELECT * FROM webchat_lines WHERE id > '.$lastID.' ORDER BY id ASC');
$chats = array();
while($chat = $result->fetch_object()){
// Returning the GMT (UTC) time of the chat creation:
$chat->time = array(
'hours' => gmdate('H',strtotime($chat->ts)),
'minutes' => gmdate('i',strtotime($chat->ts))
);
$chat->gravatar = Chat::gravatarFromHash($chat->gravatar);
$chats[] = $chat;
}
return array('chats' => $chats);
}
public static function gravatarFromHash($hash, $size=23){
return 'http://www.gravatar.com/avatar/'.$hash.'?size='.$size.'&default='.
urlencode('http://www.gravatar.com/avatar/ad516503a11cd5ca435acc9bb6523536?size='.$size);
}
}
?>
You can copy the media stream into a canvas and later manipulate as you wish. Then you can assign an event listener to canvas and on mouse click to create an image. You can do that with canvas toDataUrl method.
So the workflow would be something like this:
accessing the camera with getUserMedia
create a copy of the life media stream and move into the canvas
attach an event listener to canvas and on click...
export the canvas to an image with toDataUrl method
I hope you got the idea.
EDIT:
I just found the same explanation done by me with real code example: https://developer.mozilla.org/en-US/docs/WebRTC/Taking_webcam_photos
Related
I have the following cloud code on parse to update a user image but I can't seem to get it saving. help!
in php
ParseCloud::run("updateUserImage", array("file" => $_FILES['image'], "objectId" => $objectId, "name" => $_FILES['image']['name'], "type"=> $_FILES['image']['type'] ));
in cloud code
Parse.Cloud.define("updateUserImage", async (request) => {
const { file, objectId, name, type} = request.params;
var fileData = request.params.file;
var fileSave = new Parse.File(name, fileData);
fileSave.save();
var User = Parse.Object.extend(Parse.User);
var query = new Parse.Query(User);
let result = await query.get(objectId, { useMasterKey: true });
if (!result) new Error("No user found!");
result.set("profilePicture", fileSave);
try {
result.save(null, { useMasterKey: true });
return "User updated successfully!";
} catch (e) {
return e.message;
}
});
I created a controller and called the function for one time.But it call two times and inserted the value two times.I call the service upload_album in controller.Now value got inserted for two times.one with original value and another with dummy value
Controller
$scope.savealbum = function() {
$scope.album_pids = $routeParams.id;
$timeout(function () {
//console.log($scope.justapp);
for (tt in $scope.justapp) {
if ($scope.justapp[tt].id == $scope.album_pids) {
for (var i = 0; i < $rootScope.media_lib.length; i++) {
}
}
}
$scope.promise=AlbumServices.upload_album($scope.album_pids,$scope.images,$scope.videos);
$scope.promise.then(function(data) {
console.log(data);
alert('Photos Added to Album Successfully');
// $location.path('album_details/' + $routeParams.id);
}, function(reason) {
console.log(reason);
});
}, 1500, false);
};
Service
upload_album: function (alb,img,vid) {
var deferred = $q.defer();
var data = {};
data.pagename = "upload_album";
data.album = alb;
data.photo = img;
data.video = vid;
$http.post('js/data/album.php', data)
.success(function (data, status, headers, config)
{
console.log(status + ' - ' + data);
deferred.resolve(data);
})
.error(function (data, status, headers, config)
{
deferred.reject(data);
console.log('error');
});
return deferred.promise;
}
php
function upload_album ($prefix) {
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$sub_id=$request->album;
$val=$request->photo;
$photo = json_encode($val);
$video = json_encode($request->video);
$now = date('Y-m-d H:i:s');
$count_pho = sizeof($photo);
$count_vid = sizeof($video);
$test = '';
if($count_pho != '0' ) {
$test .= "('".$sub_id."','".$content_type."','".$photo."','".$website_id."','".$now."'),";
$demo = substr($test, 0, -1);
$sql="INSERT INTO `album_details` (SUB_ID,CONTENT_TYPE,CONTENT_VALUE,WEBSITE_ID,CreatedTime)VALUES".$demo;
$query = mysql_query($sql) or sqlerrorhandler("(".mysql_errno().") ".mysql_error(), $sql, __LINE__);
}
if ($query) {
echo $msg = true;
} else {
echo $msg = false;
}
}
Because we cannot se the whole code (including the HTML) my suggestions are these:
check your html and/or run method inside angular to be sure that your controller was not instanciated twice
create a unique key pair in your database (it could help not have double records)
create a debouncer when using timeout so that if the timeout is always launched once. something like this:
var t = null;
var mySaveFunction = function () {
if (t) {
clearTimeout(t);
}
t = setTimeout(function () {
/* do saving here */
}, 2000);
};
I'm using this function to try and send my objects coordinates and id to my php script. I'm not sure how to setup how to get the card_id and it's top and left coordinates into the post so I can retrieve them in my php script as one array. I have the all the values alerting properly but how do I pass them make sure I'm getting the proper ones on the other end and that the coordinates go with the card_id?
document.getElementById('rasterize-scoutlog2').onclick = function() {
if (!fabric.Canvas.supports('toDataURL')) {
alert('This browser doesn\'t provide means to serialize canvas to an image');
}
else {
canvas.deactivateAllWithDispatch().renderAll();
//window.open(canvas.toDataURL('png'));
//var strDataURI = (canvas.toDataURL('png'));
//strDataURI = strDataURI.substr(22, strDataURI.length);
var objsInCanvas = canvas.getObjects();
objsInCanvas.forEach(function(object) {
var stickycard_ids = [object.card_id];
var stickycard_top = [object.top];
var stickycard_left = [object.left];
if(object.card_id != null){
stickycard_ids.forEach(function(stickycard_idarr) {
alert(stickycard_idarr+stickycard_top+stickycard_left);
});
}
});
var scoutlogname = $('#scoutmapselectcard').val();
$.post("maps/savescout_log.php",
{
//str: strDataURI,
// queryStr: queryStr,
scoutlogname: scoutlogname,
//**** stickycard_idarr: stickycard_idarr
},
function(data){
if(data == "OK"){
$("#msg").html("Scout Log saved to account!").css({'color':"green",'font-weight':"bold"});
}
if(data=="EMPTY"){
$("#msg").html("Please Enter a name for your Scout Log!").css({color:"red"});
}
if(data=="WRONGCH"){
$("#msg").html("Only A_Z,a-z,0-9-_ allowed in Scout Log name!").css({color:"red"});
}
if(data=="EXIST"){
$("#msg").html("Scout Log name all ready exists!<br> Delete the existing one before saving.").css({color:"red"});
}
if(data=="ERROR"){
$("#msg").html("Scout Log not saved!").css({color:"red"});
}
window.setTimeout(function() {
$('#msg').empty();
}, 5000);
});
}
};
I got the objects and their details all going to arrays. I used the .push method to populate the arrays with the objects values in the foreach loop. Now on to the php end to insert them into the mysql database table.
document.getElementById('rasterize-scoutlog').onclick = function() {
if (!fabric.Canvas.supports('toDataURL')) {
alert('This browser doesn\'t provide means to serialize canvas to an image');
}else {
canvas.deactivateAllWithDispatch().renderAll();
//window.open(canvas.toDataURL('png'));
//var strDataURI = (canvas.toDataURL('png'));
//strDataURI = strDataURI.substr(22, strDataURI.length);
var objsInCanvas = canvas.getObjects();
var stickycard_ids = [];
var stickycard_top = [];
var stickycard_left = [];
var stickycard_type = [];
objsInCanvas.forEach(function(object) {
if(object.card_id != null){
stickycard_ids.push(object.card_id);
stickycard_top.push(object.top);
stickycard_left.push(object.left);
stickycard_type.push(object.cardtype);
}
});
var scoutmapname = $('#scoutmapselectcard').val()
var scoutlogname = $('#scoutlogname').val();
$.post("maps/savescout_log.php",
{
//str: strDataURI,
//queryStr: queryStr,
scoutlogname: scoutlogname,
scoutmapname: scoutmapname,
stickycard_ids: stickycard_ids,
stickycard_top: stickycard_top,
stickycard_left: stickycard_left,
stickycard_type:stickycard_type
},
function(data){
if(data == "OK"){
$("#msg").html("Scout Log saved to account!").css({'color':"green",'font-weight':"bold"});
}
if(data=="EMPTY"){
$("#msg").html("Please Enter a name for your Scout Log!").css({color:"red"});
}
if(data=="WRONGCH"){
$("#msg").html("Only A_Z,a-z,0-9-_ allowed in Scout Log name!").css({color:"red"});
}
if(data=="EXIST"){
$("#msg").html("Scout Log name all ready exists!<br> Delete the existing one before saving or enter a new name.").css({color:"red"});
}
if(data=="ERROR"){
$("#msg").html("Scout Log not saved!").css({color:"red"});
}
window.setTimeout(function() {
$('#msg').empty();}, 5000);
});
}
};
Here's the php that will insert those mutiple arrays into into mysql using PDO. I'm using the stickycard_ids as the indexing value then posting that and the other assiociated array values to a new row every time the stickycard_ids value changes.
for ($i=0; $i < count($_POST['stickycard_ids']); $i++ ) {
$card_id = $_POST['stickycard_ids'][$i];
$cardtype = $_POST['stickycard_type'][$i];
$top_y = $_POST['stickycard_top'][$i];
$left_x = $_POST['stickycard_left'][$i];
$sql ="INSERT INTO tablename (scoutmapname,scoutlogname,card_id,left_x,top_y,cardtype)
VALUES (:scoutlogname,:card_id,:left_x,:top_y,:cardtype)";
$q = $pdo->prepare($sql);
$q->execute(array(':scoutmapname'=>$scoutmapname,':scoutlogname'=>$scoutlogname,':card_id'=>$card_id,':left_x'=>$left_x,':top_y'=>$top_y,':cardtype'=>$cardtype));
}
We are making a website using PHP and Knockoutjs. We are able to sent the JSON data using $.ajax method in Knockoutjs.
But it is not loading the data requested initially.
PHP code
$students = $db->query("SELECT * FROM students WHERE status = 1");
$students_r = array();
while($row = $students->fetch_array()){
//default student data
$id = $row['id'];
$name = $row['name'];
$age = $row['age'];
//update status
//its false by default since
//this is only true if the user clicks
//on the span
//$name_update = false;
// $age_update = false;
//build the array that will store all the student records
$students_r[] = array(
'id' => $id, 'name' => $name, 'age' => $age,
);
}
echo json_encode($students_r); //convert the array to JSON string
and this is actually generating proper json data
[
{"id":"1","name":"monkey d. luffy","age":"15"},
{"id":"4","name":"son goku","age":"30"},
{"id":"5","name":"naruto uzumaki","age":"16"},
{"id":"6","name":"draco","age":"15"},
{"id":"10","name":"NIklaus MikaelSon","age":"1500"},
{"id":"16","name":"Elijah","age":"1000"},
{"id":"19","name":"Chitrank","age":"23"},
{"id":"20","name":"Rahul","age":"24"}
]
Now Knockout comes into play to show this data on the page, So here is the HTML page
function RefreshUser(data) {
this.name = ko.observable(data.name);
this.age = ko.observable(data.age);
};
var personModel = function(id, name, age){
var self = this; //caching so that it can be accessed later in a different context
this.id = ko.observable(id); //unique id for the student (auto increment primary key from the database)
this.name = ko.observable(name); //name of the student
this.age = ko.observable(age);
this.nameUpdate = ko.observable(false); //if the name is currently updated
this.ageUpdate = ko.observable(false); //if the age is currently updated
//executed if the user clicks on the span for the student name
this.nameUpdating = function(){
self.nameUpdate(true); //make nameUpdate equal to true
};
//executed if the user clicks on the span for the student age
this.ageUpdating = function(){
self.ageUpdate(true); //make ageUpdate equal to true
};
};
var model = function(){
var self = this; //cache the current context
this.person_name = ko.observable(""); //default value for the student name
this.person_age = ko.observable("");
this.person_name_focus = ko.observable(true); //if the student name text field has focus
this.people = ko.observableArray([]); //this will store all the students
this.createPerson = function(){
if(self.validatePerson()){ //if the validation succeeded
//build the data to be submitted to the server
var person = {'name' : this.person_name(), 'age' : this.person_age()};
//submit the data to the server
$.ajax(
{
url: 'refresher_save.php',
type: 'POST',
data: {'student' : person, 'action' : 'insert'},
success: function(id){//id is returned from the server
//push a new record to the student array
self.people.push(new personModel(id, self.person_name(), self.person_age()));
self.person_name(""); //empty the text field for the student name
self.person_age("");
}
}
);
}else{ //if the validation fails
alert("Name and age are required and age should be a number!");
}
};
this.validatePerson = function(){
if(self.person_name() !== "" && self.person_age() != "" && Number(self.person_age()) + 0 == self.person_age()){
return true;
}
return false;
};
$.getJSON("refresher_save.php", function(userModels) {
var t = $.map(userModels.people, function(item) {
console.log("Something");
return new RefreshUser(item);
});
self.people(t);
});
this.removePerson = function(person){
$.post(
'refresher_save.php',
{'action' : 'delete', 'student_id' : person.id()},
function(response){
//remove the currently selected student from the array
self.people.remove(person);
}
);
};
this.updatePerson = function(person){
//get the student details
var id = person.id();
var name = person.name();
var age = person.age();
//build the data
var student = {'id' : id, 'name' : name, 'age' : age};
//submit to server via POST
$.post(
'refresher_save.php',
{'action' : 'update', 'student' : student}
);
};
};
ko.applyBindings(new model());
Now here we are using $.getJSON to fetch all the JSON records, but it is not displaying the data on the page.
i can see little mistakes for example
this.people = ko.observableArray([]);
and others you should recheck your code i think they should be self.people..... self.person_age, later in your code you refer to them with self for example here
self.people.push(new personModel(id,
self.person_name(),self.person_age()));
you refer with self thats why the data is not loading you are not refering to the same object people
I see you have tried to create something based on a code from two sources (you have them scrambled), which are looking similar but simple are not the same (are not providing correct data).
First you are creating logic duplicity with RefreshUser() and personModel(). You should to left only personModel() as
var personModel = function(data){
var self = this;
this.id = ko.observable(data.id);
this.name = ko.observable(data.name);
this.age = ko.observable(data.age);
/* all the rest stays the same */
Then in createPerson() you should to update that line
self.people.push(new personModel(person));
Then finaly $.getJSON part should to looks like
$.getJSON("refresher_save.php", function(allData) {
var data = $.map(allData, function(item) { return new personModel(item) });
self.people(data);
});
and should be located at the bottom of model() view.
Thank you for your time, but my problem has been been solved, actually in my php script I was passing unused parameters, that cause the problem, when I removed those parameters, it worked and database values loaded when page refreshes. Thank you for your replies. :)
I need your help guys, I'm building my own web chat for my online radio site. I already have a AJAX PHP Web chat from Tutorialzine. I want to modify it. But i don't know where to start. I want it to integrate with Facebook. I want it instead of asking for username and email, there will be a button that says 'Connect to Facebook'. and the Profile Picture and Name of the user will automatically saved to the database. I really need it. And i want it to be moderated. Thank You! and God bless everyone! :)
ajax.php
<?php
/* Database Configuration. Add your details below */
$dbOptions = array(
'db_host' => 'localhost',
'db_user' => 'root',
'db_pass' => '',
'db_name' => 'chat'
);
/* Database Config End */
error_reporting(E_ALL ^ E_NOTICE);
require "classes/DB.class.php";
require "classes/Chat.class.php";
require "classes/ChatBase.class.php";
require "classes/ChatLine.class.php";
require "classes/ChatUser.class.php";
session_name('webchat');
session_start();
if(get_magic_quotes_gpc()){
// If magic quotes is enabled, strip the extra slashes
array_walk_recursive($_GET,create_function('&$v,$k','$v = stripslashes($v);'));
array_walk_recursive($_POST,create_function('&$v,$k','$v = stripslashes($v);'));
}
try{
// Connecting to the database
DB::init($dbOptions);
$response = array();
// Handling the supported actions:
switch($_GET['action']){
case 'login':
$response = Chat::login($_POST['name'],$_POST['email']);
break;
case 'checkLogged':
$response = Chat::checkLogged();
break;
case 'logout':
$response = Chat::logout();
break;
case 'submitChat':
$response = Chat::submitChat($_POST['chatText']);
break;
case 'getUsers':
$response = Chat::getUsers();
break;
case 'getChats':
$response = Chat::getChats($_GET['lastID']);
break;
default:
throw new Exception('Wrong action');
}
echo json_encode($response);
}
catch(Exception $e){
die(json_encode(array('error' => $e->getMessage())));
}
?>
script.js
$(document).ready(function(){
// Run the init method on document ready:
chat.init();
});
var chat = {
// data holds variables for use in the class:
data : {
lastID : 0,
noActivity : 0
},
// Init binds event listeners and sets up timers:
init : function(){
// Using the defaultText jQuery plugin, included at the bottom:
$('#name').defaultText('Nickname');
$('#email').defaultText('Email (Gravatars are Enabled)');
// Converting the #chatLineHolder div into a jScrollPane,
// and saving the plugin's API in chat.data:
chat.data.jspAPI = $('#chatLineHolder').jScrollPane({
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12
}).data('jsp');
// We use the working variable to prevent
// multiple form submissions:
var working = false;
// Logging a person in the chat:
$('#loginForm').submit(function(){
if(working) return false;
working = true;
// Using our tzPOST wrapper function
// (defined in the bottom):
$.tzPOST('login',$(this).serialize(),function(r){
working = false;
if(r.error){
chat.displayError(r.error);
}
else chat.login(r.name,r.gravatar);
});
return false;
});
// Submitting a new chat entry:
$('#submitForm').submit(function(){
var text = $('#chatText').val();
if(text.length == 0){
return false;
}
if(working) return false;
working = true;
// Assigning a temporary ID to the chat:
var tempID = 't'+Math.round(Math.random()*1000000),
params = {
id : tempID,
author : chat.data.name,
gravatar : chat.data.gravatar,
text : text.replace(/</g,'<').replace(/>/g,'>')
};
// Using our addChatLine method to add the chat
// to the screen immediately, without waiting for
// the AJAX request to complete:
chat.addChatLine($.extend({},params));
// Using our tzPOST wrapper method to send the chat
// via a POST AJAX request:
$.tzPOST('submitChat',$(this).serialize(),function(r){
working = false;
$('#chatText').val('');
$('div.chat-'+tempID).remove();
params['id'] = r.insertID;
chat.addChatLine($.extend({},params));
});
return false;
});
// Logging the user out:
$('a.logoutButton').live('click',function(){
$('#chatTopBar > span').fadeOut(function(){
$(this).remove();
});
$('#submitForm').fadeOut(function(){
$('#loginForm').fadeIn();
});
$.tzPOST('logout');
return false;
});
// Checking whether the user is already logged (browser refresh)
$.tzGET('checkLogged',function(r){
if(r.logged){
chat.login(r.loggedAs.name,r.loggedAs.gravatar);
}
});
// Self executing timeout functions
(function getChatsTimeoutFunction(){
chat.getChats(getChatsTimeoutFunction);
})();
(function getUsersTimeoutFunction(){
chat.getUsers(getUsersTimeoutFunction);
})();
},
// The login method hides displays the
// user's login data and shows the submit form
login : function(name,gravatar){
chat.data.name = name;
chat.data.gravatar = gravatar;
$('#chatTopBar').html(chat.render('loginTopBar',chat.data));
$('#loginForm').fadeOut(function(){
$('#submitForm').fadeIn();
$('#chatText').focus();
});
},
// The render method generates the HTML markup
// that is needed by the other methods:
render : function(template,params){
var arr = [];
switch(template){
case 'loginTopBar':
arr = [
'<span><img src="',params.gravatar,'" width="23" height="23" />',
'<span class="name">',params.name,
'</span>Logout</span>'];
break;
case 'chatLine':
arr = [
'<div class="chat chat-',params.id,' rounded"><span class="gravatar"><img src="',params.gravatar,
'" width="23" height="23" onload="this.style.visibility=\'visible\'" />','</span><span class="author">',params.author,
':</span><span class="text">',params.text,'</span><span class="time">',params.time,'</span></div>'];
break;
case 'user':
arr = [
'<div class="user" title="',params.name,'"><img src="',
params.gravatar,'" width="30" height="30" onload="this.style.visibility=\'visible\'" /></div>'
];
break;
}
// A single array join is faster than
// multiple concatenations
return arr.join('');
},
// The addChatLine method ads a chat entry to the page
addChatLine : function(params){
// All times are displayed in the user's timezone
var d = new Date();
if(params.time) {
// PHP returns the time in UTC (GMT). We use it to feed the date
// object and later output it in the user's timezone. JavaScript
// internally converts it for us.
d.setUTCHours(params.time.hours,params.time.minutes);
}
params.time = (d.getHours() < 10 ? '0' : '' ) + d.getHours()+':'+
(d.getMinutes() < 10 ? '0':'') + d.getMinutes();
var markup = chat.render('chatLine',params),
exists = $('#chatLineHolder .chat-'+params.id);
if(exists.length){
exists.remove();
}
if(!chat.data.lastID){
// If this is the first chat, remove the
// paragraph saying there aren't any:
$('#chatLineHolder p').remove();
}
// If this isn't a temporary chat:
if(params.id.toString().charAt(0) != 't'){
var previous = $('#chatLineHolder .chat-'+(+params.id - 1));
if(previous.length){
previous.after(markup);
}
else chat.data.jspAPI.getContentPane().append(markup);
}
else chat.data.jspAPI.getContentPane().append(markup);
// As we added new content, we need to
// reinitialise the jScrollPane plugin:
chat.data.jspAPI.reinitialise();
chat.data.jspAPI.scrollToBottom(true);
},
// This method requests the latest chats
// (since lastID), and adds them to the page.
getChats : function(callback){
$.tzGET('getChats',{lastID: chat.data.lastID},function(r){
for(var i=0;i<r.chats.length;i++){
chat.addChatLine(r.chats[i]);
}
if(r.chats.length){
chat.data.noActivity = 0;
chat.data.lastID = r.chats[i-1].id;
}
else{
// If no chats were received, increment
// the noActivity counter.
chat.data.noActivity++;
}
if(!chat.data.lastID){
chat.data.jspAPI.getContentPane().html('<p class="noChats">No chats yet</p>');
}
// Setting a timeout for the next request,
// depending on the chat activity:
var nextRequest = 1000;
// 2 seconds
if(chat.data.noActivity > 3){
nextRequest = 2000;
}
if(chat.data.noActivity > 10){
nextRequest = 5000;
}
// 15 seconds
if(chat.data.noActivity > 20){
nextRequest = 15000;
}
setTimeout(callback,nextRequest);
});
},
// Requesting a list with all the users.
getUsers : function(callback){
$.tzGET('getUsers',function(r){
var users = [];
for(var i=0; i< r.users.length;i++){
if(r.users[i]){
users.push(chat.render('user',r.users[i]));
}
}
var message = '';
if(r.total<1){
message = 'No one is online';
}
else {
message = r.total+' '+(r.total == 1 ? 'person':'people')+' online';
}
users.push('<p class="count">'+message+'</p>');
$('#chatUsers').html(users.join(''));
setTimeout(callback,15000);
});
},
// This method displays an error message on the top of the page:
displayError : function(msg){
var elem = $('<div>',{
id : 'chatErrorMessage',
html : msg
});
elem.click(function(){
$(this).fadeOut(function(){
$(this).remove();
});
});
setTimeout(function(){
elem.click();
},5000);
elem.hide().appendTo('body').slideDown();
}
};
// Custom GET & POST wrappers:
$.tzPOST = function(action,data,callback){
$.post('php/ajax.php?action='+action,data,callback,'json');
}
$.tzGET = function(action,data,callback){
$.get('php/ajax.php?action='+action,data,callback,'json');
}
// A custom jQuery method for placeholder text:
$.fn.defaultText = function(value){
var element = this.eq(0);
element.data('defaultText',value);
element.focus(function(){
if(element.val() == value){
element.val('').removeClass('defaultText');
}
}).blur(function(){
if(element.val() == '' || element.val() == value){
element.addClass('defaultText').val(value);
}
});
return element.blur();
}
If you only want to connect with facebook for the user name and picture then all you need to do is include the Facebook Javascript SDK, and then either use the Login Button plugin or use the Client-Side authentication.
If you want to connect with the Facebook internal chat, then you can use the Chat API which has two authentication methods: Facebook Platform and Username/Password.
If you want the first method (sounds like what you want) then you'll need to authenticate the user, either with the client side flow or the server side flow and ask for the "xmpp_login" permission.
There are php examples in the chat API documentation.