hi guys i am trying to create a like system where when users like a post it gets saved in the database that this user has liked this post now i need to count the no of times 'like' has been done.now i used a column type to save the like whenever someone click but when i am retrieving how many likes are on a post how can i count how many likes has been done on this post.here is my code
script
function select_likes(post_id)
{
var Post_id=post_id;
var User_id = $('.id_data').attr('value');
jQuery.ajax({
type:'POST',
url:'<?php echo base_url("user/select_likes"); ?>',
data: {Post_id:Post_id,User_id:User_id},
dataType: 'json',
success:function(data)
{
var ParsedObject = JSON.stringify(data);
var json = $.parseJSON(ParsedObject);
$.each(json, function (key, data) {
var likes=data.type;
// alert(likes);
var count=likes.length;
alert(count);
// var post_id=data.post_id;
// $post_id=post_id;
// // alert(comment);
// // // alert(post_id);
// // var div_list=document.getElementById('#comment_div').innerHTML='post_id;
// // $("#comment_post_id").attr('value',$post_id);
var mediaID ='.likes'+post_id;
$(mediaID).append(likes);
});
}
});
}
controller
public function select_likes()
{
$Post_id=$this->input->post('Post_id');
$User_id=$this->input->post('User_id');
$this->load->model('Pmodel');
$select_likes=$this->Pmodel->select_likes_post_id($Post_id,$User_id);
// print_r($select_likes);
echo json_encode($select_likes);
}
model
public function select_likes_post_id($Post_id,$User_id)
{
$this->db->select('*');
$this->db->from('userpost_likes_share');
$this->db->where('post_id',$Post_id);
$this->db->where('type','like');
$query=$this->db->get();
$likes=$query->result_array();
return $likes;
}
but how can i count it ? is it possible to count no of times a variable calls in javscript
simply use count() function on $select_likes in controller count($select_likes) ... it will be the number of like on the post and pass it as json as json_encode(array('like_count'=>$like_count))
So in controller code can be like:
public function select_likes()
{
$Post_id=$this->input->post('Post_id');
$User_id=$this->input->post('User_id');
$this->load->model('Pmodel');
$select_likes=$this->Pmodel->select_likes_post_id($Post_id,$User_id);
$like_count = count($select_likes);
echo json_encode(array('like_count'=>$like_count));
}
Use in js script you can use the data.like_count as total number of like on the post.
If you only need like count from table then i would suggest only select one column from your 'userpost_likes_share' table.. you can select only id(primary key) of the table for make the code work faster.
Let me know if you think i get wrong and answer in wrong direction...
I am trying to receive data from the controller to the view using json_encode and ajax functions. But I am sending to separate values through json, and I am tring to access it. So how can I separate those two objects, and get only a single value?
Let me show you my code:
function check_relation_status()
{
var id=$('.id_data').attr('value');
jQuery.ajax({
type:'POST',
url:'<?php echo base_url("user/check_relation_status"); ?>',
data:{id:id},
dataType:'json',
success:function(data)
{
console.log(data);
var ParsedObject = JSON.stringify(data);
var sender_Data = $.parseJSON(ParsedObject);
var senders_id=sender_Data.senders_id;
jQuery.ajax({
type:'POST',
url:'<?php echo base_url("user/get_senders_data"); ?>',
data:{id:senders_id},
dataType:'json',
success:function(data)
{
console.log(data);
var ParsedObject = JSON.stringify(data);
var sender_values = $.parseJSON(ParsedObject);
var senders_name=sender_values.sender_data;
// alert(senders_name);
$.each(sender_values, function(key,data)
{
var uname = data.uname;
// alert(uname);
$('#friendship_request').append('<div>'+uname +'has sent you a request</div>');
});
}
});
}
});
}
now the controller code
public function get_senders_data()
{
$sender_id=$this->input->post('id');
$this->load->model('Pmodel');
$userdata=$this->Pmodel->getUserdata($sender_id);
$senders['senders_data']=$userdata;
$senders['senders_post'] = $this->Pmodel->get_all_count($sender_id);
// print_r($senders);
echo json_encode($senders);
}
the json value '$senders' holds both the values but when i try to access it usng 'each' function it shows the values two time when there is only a single column for uname . let me add some images to explain.
Where I am wrong?
Try to change like below:-
if(uname){
$('#friendship_request').html('<div>'+uname +'has sent you a request</div>');
}
Note:-
1.You are appending all usernames (which is not correct).
2.You are not checking that username is either undefined or null or empty etc
I have a canvas that lives on top of a video. When a user pauses the video they are able to add fabricjs objects to the canvas. When an object is added to the canvas it is saved to a table in a mysql database as JSON.
When the user clicks a button it will query the mysql database for records and return via ajax the objects for each record in an array.
As it loops through this array I want fabricjs to render each object one at a time until all objects have been rendered.
I have tried using :
canvas.loadFromJSON(rData, canvas.renderAll.bind(canvas), function(o, object) {
fabric.log(o, object);
});
It will load all objects but clears the canvas before each load and will only display the last object.
I have tried the example here:
http://codepen.io/Kienz/pen/otyEz but cannot seem to get it to work for me. I have also tried http://jsfiddle.net/Kienz/bvmkQ/ but cannot see what is wrong.
So I have come to the experts! I appreciate all and any help. Thank you.
Here is my table in mysql wth 2 records:
CREATE TABLE IF NOT EXISTS `telestrations` (
`id_telestration` int(11) NOT NULL AUTO_INCREMENT,
`object` longtext NOT NULL,
PRIMARY KEY (`id_telestration`),
UNIQUE KEY `id_telestration` (`id_telestration`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=65 ;
--
-- Dumping data for table `telestrations`
--
INSERT INTO `telestrations` (`id_telestration`, `object`) VALUES
(63, '{"objects":[{"type":"i-text","originX":"left","originY":"top","left":161.05,"top":359.29,"width":69.3,"height":20.97,"fill":"#e6977e","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","text":"AAAAAA","fontSize":16,"fontWeight":"bold","fontFamily":"arial","fontStyle":"","lineHeight":1.16,"textDecoration":"","textAlign":"left","textBackgroundColor":"","styles":{"0":{"1":{},"2":{},"3":{},"4":{},"5":{}}}}],"background":""}'),
(64, '{"objects":[{"type":"i-text","originX":"left","originY":"top","left":463.68,"top":353.84,"width":69.3,"height":20.97,"fill":"#20f20e","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","text":"BBBBBB","fontSize":16,"fontWeight":"bold","fontFamily":"arial","fontStyle":"","lineHeight":1.16,"textDecoration":"","textAlign":"left","textBackgroundColor":"","styles":{"0":{"1":{},"2":{},"3":{},"4":{},"5":{}}}}],"background":""}');
Here is my php file:
$teles = Telestration::getTeleByVideo();
$objArray = array();
foreach($teles as $tele){
$obj = $tele->getValueEncoded('object');
$objArray[] = $obj;
}
echo json_encode($objArray);
Here is my JavaScript:
document.getElementById("get_json").onclick = function(ev) {
$.ajax({
url: 'getTelestrations.php',
data: dataString,
type: 'POST',
dataType:"json",
success: function(data){
for (var i = 0; i < data.length; i++) {
rData = data[i].replace(/"/g, '\"');
//Do something
canvas.loadFromJSON(rData, canvas.renderAll.bind(canvas), function(o, object) {
fabric.log(o, object);
});
}
}
});
}
Hello inside your success function use instead of canvas.loadFromJSON , the fabric.util.enlivenObjects() funtion, like this:
//inside the success function, you get the results data from the server and loop inside the items, allright if you have only one object but use loop for more.
results.data.forEach(function (object) {
var tmpObject = JSON.parse(object.table_data);
fabric.util.enlivenObjects([tmpObject], function (objects) {
var origRenderOnAddRemove = canvas.renderOnAddRemove;
canvas.renderOnAddRemove = false;
console.log(objects);
objects.forEach(function (o) {
canvas.add(o);
console.log(o);
});
canvas.renderOnAddRemove = origRenderOnAddRemove;
canvas.renderAll();
});//end enlivenObjects
});//end data.forEach
Hope this helps, good luck
I was able to figure out how to load each object. It turns that the json returned from my mysql was not "workable" for fabricjs. I had to clean my json and then the objects would load.
I only made changes to my javascript:
$.ajax({
url: 'getTelestrations.php',
data: dataString,
type: 'POST',
dataType:"json",
success: function(data){
for (var i = 0; i < data.length; i++) {
//clean results for json
json_result = data[i].replace(/"/g, '\"'); //remove quotes from entire result
json_clean = json_result.replace(/"objects"/, 'objects'); //remove quotes around first object
jsonObj = JSON.parse(JSON.stringify(json_clean)); // parse the entire result
jsonobj2 = eval('(' + jsonObj + ')');
// Add object to canvas
var obj = new fabric[fabric.util.string.camelize(fabric.util.string.capitalize(jsonobj2.objects[0].type))].fromObject(jsonobj2.objects[0]);
canvas.add(obj);
canvas.renderAll();
}
}
});
I am trying to send data from form to PHP file using JavaScript. PHP file pushes this data to database. For now, almost all works well but I have a problem with array from getElementsByClassName. After sending to database I can see only "Array" but no values of this array.
Here's a JS:
function przekaz_form($wejscie) {
var datas = document.formularz.datas.value;
var klient = document.formularz.firma.value;
var comment = document.formularz.comment.value;
var collect = document.getElementsByClassName($wejscie);
var datan = document.formularz.datan.value;
var items = new Array();
for(var i = 0; i < collect.length; i++) {
items.push(collect.item(i).value);
}
jQuery.ajax({
url: 'addtobase.php',
type: 'post',
data:{
devices: items,
datas: datas,
klient: klient,
comment: comment,
datan: datan
},
success: function(output) {
alert('Success');
}
});
}
One way to do this is:
$inputData = json_decode(file_get_contents('php://input'));
Once you have the $inputData variable you can access the data in the JSON by:
$devices = (!is_null($inputData) && property_exists($inputData, "devices")) ? strip_tags($inputData->{"devices"}) : 0;
You should also try to better format the JSON : http://json.org/example
I have PHP associative array and I use JQuery AJAX to get the result array but my problem is when that result is pass to jquery and use looping to extract each Sequence,Percent and Date then that extracted data will store to new Jquery Array for data manipulation purposes. Please see my sample code so far.
sample code PHP ARRAY:
$Sequence=array(
array("Seq1","20%"),
array("Seq2","40%"),
array("Seq3","60%"),
array("Seq4","80%"),
array("Seq5","100%")
);
****For loop here****
$ResultArray[$arrayIndex]=array(
'Sequence' => $Sequence[$arrayIndex][0],
'Percent' => $Sequence[$arrayIndex][1],
'Date' => $row['exactDate']
);
echo json_encode($ResultArray); // then pass result array to jquery
JQUERY :
$(document).ready(function(){
var ListOfSequence = []
var ListOfPercentage = [];
var ListOfDates = [];
$("#button").click(function(){
var _WOID = $('#txtWOID').val();
$.ajax({
url:'getStatus.php',
type:'POST',
data:{id:_WOID},
dataType:'json',
success:function(output){
//here is where the problem begin
for (var key in output) {
if (output.hasOwnProperty(key)) {
//here where extracted data will store to designated array
ListOfSequence.push(key);//<---store extracted Sequence
ListOfPercentage.push(key);//<---store percentage
ListOfDates.push(output[key]);//<---store dates
}
}
ListOfPercentage.reverse();
console.log(ListOfPercentage);
console.log(ListOfDates);
console.log(ListofSequence);
}
});
});
});
and here's the console.log:
Thank you in advance
Since you are already using jQuery you could use $.each() :
$(document).ready(function(){
var ListOfSequence = []
var ListOfPercentage = [];
var ListOfDates = [];
$("#button").click(function(){
var _WOID = $('#txtWOID').val();
$.ajax({
url:'getStatus.php',
type:'POST',
data:{id:_WOID},
dataType:'json',
success:function(json){
$.each(json, function(index, object){
ListOfSequence.push(object.Sequence);
ListOfPercentage.push(object.Percent);
ListOfDates.push(object.Date);
});
}
});
});
});
You should set the json response header before sending the content to the browser like so:
header('Content-type: application/json');
die(json_encode($ResultArray);)