BACKBONE and Jquery
I have a piece of code:
var ChatMessage = Backbone.View.extend({
el : '#friend-list',
events : {},
initialize : function() {},
loadMessage : function(parent_id) {
//ukrycie komunikatów etc.
$("#chat_body").html('');
$("#end-record-info").hide();
$("#end-record-load").hide();
page = 1;
this.ajax(parent_id,page); //initial data load
},
ajax : function(parent_id,page) {
$.getJSON( "/**/**/"+parent_id+"/"+page, function( json ) {
$("#end-record-load").hide();
this.build(json.message, page);
page ++; //page increment
loading = false; //set loading flag off
end_record = false;
if(json.max < page){ //no more records
end_record = true; //set end record flag on
return; //exit
}
});
},
build : function(arr, page) {
alert('dgd');
html = '';
var height = 0;
arr.reverse();
$.each(arr, function(i, data){
html += '<div class="answer '+data.side+'">';
html += '<div class="avatar">';
html += '<a href="**" target="_blank">';
html += ''+data.id+'';
html += '</a>';
html += '<div class="status offline"></div>';
html += '</div>';
html += '<div class="name">';
html += '<a href="**" target="_blank">';
html += data.username;
html += '</a>';
html += '</div>';
html += '<div class="text">';
html += data.content;
html += '</div>';
html += '<div class="time">';
if (data.side != 'left') {
html += data.dateSendMessage
}
else {
if (data.read == 0) {
html += 'xxx';
}
else {
html += 'xxx';
}
}
html += '</div>';
html += '</div>';
});
var nh = $('#chat_body').html();
$('#chat_body').html(html+nh);
if (page == 1) {
$('#chat_body .answer').each(function(i, value){
height += parseInt($(this).height());
});
height += '';
$('.chat2').scrollTop(height);
}
}
});
In AJAX method I want to build method
this.build(json.message, page);
But something does not work and I get an error.
pm2.js:67TypeError: this.build is not a function. (In 'this.build(json.message, page)', 'this.build' is undefined)
Can anyone help? What changes in this piece of code can be by the way?
Piotr
You should probably save current context before calling getJSON:
ajax : function(parent_id,page) {
var self = this;
$.getJSON( "/**/**/"+parent_id+"/"+page, function( json ) {
...
self.build(json.message, page);
Related
I'm coding a wordpress theme and I want to increment a load more button.
I'm not using wordpress always and this is the first time I've this problem with a javascript variable. The variable pull_page in fact will not increment and every time the script will run it will fetch only two pages. Is there any error in the code, and how I can fix it?
$('#load-more').on('click', function(e){
e.preventDefault();
var pull_page = 1;
var jsonFlag = true;
if(jsonFlag){
pull_page++;
$.getJSON("/beta/wp-json/portfolio/all-posts?page=" + pull_page, function(data){
if(data.length){
$.each(data, function(i, item){
var html = '<div class="card">';
html += '<a href="'+ item.permalink +'">';
html += '<img class="card-img-top w-100" src="'+ item.featured_img_src +'" id="case-studies" />';
html += '<div class="overlay"><h4 class="text-center" id="client-name">'+ item.title +'</h4></div>';
html += '</a>';
html += '</div>';
$('body').find('.card-columns')
.append(html);
});
}
else{
jsonFlag = false;
}
}).done(function(data){
if(data.length >= 4){
jsonFlag = true;
}
else{
jsonFlag = false;
}
});
}
}); // end load more
You're resetting pull_page to 1 each and every time the load more button is clicked.
Move it outside.
var pull_page = 1;
$('#load-more').on('click', function(e) {
...
<script>
var index = 0;
$.getJSON("./data/data.json", function(json) {
$.each(json, function(data) {
var html = "";
if(index == 0)
{
console.log(index + " first item");
html = "<div class='item active'>";
} else {
console.log(index + " its not 0");
html = "<div class='item'>"
}
console.log(json.length); // this will show the info it in firebug console
html += "<blockquote><div class='row'><div class='col-sm-3 text-center'><img class='img-circle' src='images/obama.jpg' style='width: 100px;height:100px;'></div><div class='col-sm-9'><p>Change will not come if we wait for some other person or some other time. We are the ones we've been waiting for. We are the change that we seek.</p><small>President Barack Obama</small></div></div></blockquote></div>";
$('body').append(html);
index++;
});
});
</script>
I need to generate 5 of these but the first one needs to be have 'item active'
If there is a better way, please let me know
Thank you for pointing out that my html was being overwritten. I updated my code but jQuery isn't actually placing my HTML into the body. so thats another question
You can add an index into the $.each method; this will span from 0 to data.length - 1
$.getJSON("./data/data.json", function(json) {
$.each(json, function(index, data) {
var html = "";
html += '<div class="item' + (index == 0 ? ' active' : '') + '">';
html += '<blockquote>...</blockquote>';
html += '</div>';
$('body').append(html);
});
});
<script>
var index = 0;
$.getJSON("./data/data.json", function(json) {
$.each(json, function(data) {
var html = "";
if(index == 0)
html = "<div class='item active'>";
else
html = "<div class='item'>";
html += "<blockquote><div class='row'><div class='col-sm-3 text-center'><img class='img-circle' src='images/obama.jpg' style='width: 100px;height:100px;'></div><div class='col-sm-9'><p>Change will not come if we wait for some other person or some other time. We are the ones we've been waiting for. We are the change that we seek.</p><small>President Barack Obama</small></div></div></blockquote></div>";
$('body').append(html);
index++;
});
});
</script>
New on here and a beginner at code. I have this code I am using as a Karaoke search. However, the JSON contains about 40 000 lines of info, and the search is set up to tigger on keyup, so it is very laggy sometimes. I'm hoping someone can help me alter this code so that it only searches when a submit button is pressed... Any ideas? Greatly Appreciated
$(window).load(function(){
$('#search').keyup(function(){
var searchField = $('#search').val();
var regex = new RegExp(searchField, "i");
var output = '<div class="row">';
var count = 1;
$.getJSON('data.json', function(data) {
$.each(data, function(key, val){
if ((val.name.search(regex) != -1) || (val.location.search(regex) != -1)) {
//output += '<div class="col-md-6 well">';
//output += '<div class="col-md-7">';
output += '' + val.name + ' - ';
output += '' + val.location + '';
output += '</div>';
output += '</div>';
output += '<div class="col-md-7"><img class="img-responsive" src="send.png" /></div>';
if(count%2 == 0){
output += '</div><div class="row">'
}
count++;
}
});
output += '</div>';
$('#results').html(output);
});
});
});
Assuming you placed your submit button within a form, give your form an ID.
<form id="search-form">
Change line
$('#search').keyup(function(){
to
$('#search-form').on('submit', function (e) {
e.preventDefault();
The search logic should not be implemented on the client side. It would be painful for the browser to do that kind of iteration. Transfer your search logic in the backend. : )
if you're going to fixed that on front end, please add timeout/debounce during keyup
var delay = null;
$( el ).keyup( function () {
if ( delay ) clearTimeout( delay );
var delay = setTimeout( function () {
// your search logic
} );
} );
I'm using jquery to append rows in a table.
I'm appending rows in an angular.forEach function in each loop but rows are rendered in my html page ine one shot : I mean the 1340 rows are displayed simultaneously insted of row by row.
I can not understand.
Here is an example of my code
angular.forEach(scope.contents, function(pack, indexPack) {
var bodyTag = '<tbody>';
if (pack.products.length > 0) {
angular.forEach(pack.products, function(product, indexProduct) {
bodyTag += '<tr>';
angular.forEach(scope.headers, function(header, indexHeader) {
var cellTag = '<td>';
var cellClass= '';
var cellContent = 'content 1';
cellTag += cellContent+'</td>';
bodyTag += cellTag;
});
bodyTag += '</tr>';
});
} else {
bodyTag += '<tr>';
angular.forEach(scope.headers, function(header, indexHeader) {
var cellTag = '<td>';
var cellClass= '';
var cellContent = 'content 2';
cellTag += cellContent+'</td>';
bodyTag += cellTag;
});
bodyTag += '</tr>';
}
bodyTag += '</tbody>';
$('#myTable').append(bodyTag);
});
Thanks for your help.
For my site I want to have a little chat / support field. At the moment I can write and also save it right to the database.
But I want to have it, that if I open the site again the old text come from the database. But how is the best way to do that? I also think my Array is false, because I only get one and not all data back from the database.
My javascript testcode:
initChat: function () {
var cont = $('#chats');
var list = $('.chats', cont);
var form = $('.chat-form', cont);
var input = $('input', form);
var btn = $('.btn', form);
var handleClick = function (e) {
e.preventDefault();
var text = input.val();
if (text.length == 0) {
return;
}
var time = new Date();
var time_str = time.toString('dd.MM.yyyy - H:mm')+ " Uhr";
var tpl = '';
tpl += '<li class="out">';
tpl += '<img class="avatar" alt="" src="assets/img/avatar.png"/>';
tpl += '<div class="message">';
tpl += '<span class="arrow"></span>';
tpl += 'Meine Frage ';
tpl += '<span class="datetime">vom ' + time_str + '</span>';
tpl += '<span class="body">';
tpl += text;
tpl += '</span>';
tpl += '</div>';
tpl += '</li>';
var msg = list.append(tpl);
var time_str_new = time.toString('yyyy-MM-dd H:mm:ss');
$.ajax({
type: "POST",
url: '../support.php',
data: {datum: time_str_new, text: text},
dataType: 'json',
success: function(data)
{
input.val("");
}
});
$('.scroller', cont).slimScroll({
scrollTo: list.height()
});
}
My php testscript:
$kundenid = KUNDENID;
$query = "INSERT INTO support set datum = '$datum', kunde = '$kundenid', text = '$text', typ = 'kunde'";
$result = mysql_query($query,$db);
$querysup = "SELECT id, datum, kunde, text, typ FROM support WHERE kunde = '$kundenid'";
$resultsup = mysql_query($querysup,$db);
while($rowsup = mysql_fetch_array($resultsup)) {
$datum = $rowsup['datum'];
$text = $rowsup['text'];
$typ = $rowsup['typ'];
$data = array("datum"=>$rowsup['datum'], "text"=>$rowsup['text'], "typ"=>$rowsup['typ']);
}
echo json_encode($data);
Ok now I have this code. If I post a new text it show me all posts from database. But I need it that the data from mysql still there before my first post.
initChat: function () {
var cont = $('#chats');
var list = $('.chats', cont);
var form = $('.chat-form', cont);
var input = $('input', form);
var btn = $('.btn', form);
var handleClick = function (e) {
e.preventDefault();
var text = input.val();
if (text.length == 0) {
return;
}
var time = new Date();
var time_str = time.toString('dd.MM.yyyy - H:mm')+ " Uhr";
var tpl = '';
tpl += '<li class="out">';
tpl += '<img class="avatar" alt="" src="assets/img/avatar.png"/>';
tpl += '<div class="message">';
tpl += '<span class="arrow"></span>';
tpl += 'Meine Frage ';
tpl += '<span class="datetime">vom ' + time_str + '</span>';
tpl += '<span class="body">';
tpl += text;
tpl += '</span>';
tpl += '</div>';
tpl += '</li>';
var msg = list.append(tpl);
var time_str_new = time.toString('yyyy-MM-dd H:mm:ss');
$.ajax({
type: "POST",
url: 'support.php',
data: {datum: time_str_new, text: text},
dataType: 'json',
success: function(data)
{
var myArray = data;
for (var i = 0; i < myArray.length; i++) {
var datum = new Date(myArray[i].datum);
var tpl = '';
tpl += '<li class="out">';
tpl += '<img class="avatar" alt="" src="assets/img/avatar.png"/>';
tpl += '<div class="message">';
tpl += '<span class="arrow"></span>';
tpl += 'Meine Frage ';
tpl += '<span class="datetime">vom ' + datum.toString('dd.MM.yyyy - H:mm:ss')+ ' Uhr' + '</span>';
tpl += '<span class="body">';
tpl += myArray[i].text;
tpl += '</span>';
tpl += '</div>';
tpl += '</li>';
var msg = list.append(tpl);
}
}
});
But how to load it from the array to my javascript... so if I refresh the page the values from array are in my "Chatbox"
The missing part could be a simple "assign" operation like
var chatArr=<?PHP echo json_encode($data) ?>;
in a <script type="language/JavaScript"> section, which you can insert after you have dealt with all the PHP stuff in the document. You should make sure of course that nothing "unwanted" gets into $data. After that you can do whatever you want to do with the JavaScript Array/Object in a $(function(){...}) section anywhere else in the document.
There are of course also dedicated JSON parsers which will also take care of Date objects. The simple assign will only generate Stings or numeric contents in the JavaScript object, see here.