Javascript - CORRECTLY append new comments without reloading - javascript

I have asked a question, how to append comments already. I got quite great answer. BUt now i want to know how to append new comments correctly, without refreshing! RIght now I add new comments with just creating new element containing comment and comment user, but they dont appear "from database". Is there any way to append new comments without having to reload whole page, but just the div containing comments, and just adding new comment?
I have this code for now:
$(".comments input[name='post']").keydown(function (evt) {
var keyCode = evt.which?evt.which:evt.keyCode;
if (keyCode == 13) {
var form = this.closest("form");
var container = form.closest(".comments");
var olist = $(container).find(".clearfix");
var input = this;
$.ajax({
url: "{% url 'comment' letnik_id=letnik_id classes_id=classes_id subject_id=subject_id %}",
data: $(form).serialize(),
type: 'post',
cache: false,
beforeSend: function () {
$(input).val("");
$(input).blur();
},
success: function (data) {
alert(data.comment);
clearfix = $(container).children(".clearfix");
clearfix.append("<small>"+data.user+"</small>" + "<br>" + data.comment)
}
});
}
});
I have this in the views:
def comment(request, letnik_id, classes_id, subject_id):
if request.method == 'POST':
exam_id = request.POST.get('exam_id')
exam = get_object_or_404(Exam, id=exam_id)
comment = request.POST.get('post')
comment = comment.strip()
if len(comment) > 0:
instance = ExamComment(
exam=exam,
comment=comment,
comment_user=request.user)
instance.save()
user = request.user.username
return JsonResponse({'comment': comment, 'user': user})
else:
return HttpResponseBadRequest()

Related

Getting logic error using JavaScript on creating like/dislike counter

I've fixed the bug. I'm documenting my code for future reference.
I'm creating a like/dislike counter and getting a logic error.
My script works such that on clicking on either button I can like/dislike or undo that action. I've tried creating logic such that when I dislike after liking the post, or vice versa, the dislike decrements and the like counter increments . The problem where I'm stuck at is after successively clicking both buttons, either one of the counter resets to zero.
<script type="text/javascript">
var dislike_b = like_b = false;
var num1 = 0;
var like = parseInt("{{post.like_votes}}");
var num2 = 0;
var dislike = parseInt("{{post.dislike_votes}}");
function likeHandler() {
const xhr = new XMLHttpRequest();
if (dislike_b == true){
dislikeHandler();
//dislike_b = false ;
}
// like iterator
like = like + (-1)**num1 ;
num1 = (num1 + 1)%2;
document.getElementById("like").innerHTML = like;
like_b = !like_b;
console.log( like , num1);
//var catid;
//catid = $(this).attr("data-catid");
$.ajax(
{
type: "POST",
url: "/likepost/",
data: {
//post_id: catid ,
votes : like ,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function (data) {
//$('#like' + catid).remove();
$('#message').text(data);
}
})
}
function dislikeHandler() {
const xhr2 = new XMLHttpRequest();
if (like_b == true){
likeHandler();
}
// like iterator
dislike = dislike + (-1)**num2 ;
num2 = (num2 + 1)%2;
document.getElementById("dislike").innerHTML = dislike;
dislike_b = !dislike_b;
console.log( dislike , num1);
$.ajax(
{
type: "POST",
url: "/dislikepost/",
data: {
votes : dislike ,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function (data) {
$('#message').text(data);
}
})
}
</script>
Have you tried preventDefault()?
You could try simplifying it a little like this by putting the ajax request in its own function. What else needs to happen when clicking the buttons? Just comment and I'll update.
// Variables
let likes = 0
let dislikes = 0
// Like
function like() {
const likeDOMText = document.querySelector('.like span')
likes++
likeDOMText.innerText = likes
// Calling the ajax request
initRequest({
likes: likes,
dislikes: dislikes,
// And whatever else
})
}
// Dislike
function dislike() {
const dislikeDOMText = document.querySelector('.dislike span')
dislikes++
dislikeDOMText.innerText = dislikes
// Calling the ajax request
initRequest({
likes: likes,
dislikes: dislikes,
// And whatever else
})
}
// Ajax request to server
function initRequest(data) {
// $.ajax({
// ...
//data: JSON.parse(data)
//})
}
<button class="like" onclick="like()">Like <span>0</span></button>
<button class="dislike" onclick="dislike()">Dislike <span>0</span></button>

jquery can't select unique elements using classes

I'm trying to use ajax on some auto generated html elements from django. I saw that you do this by selecting the instances via the class, but I can't seem to get it working. What do I have wrong here?
javascript
$(document).ready(function() {
$('.fix-button').on('submit', function(event) {
event.preventDefault();
var $issue_id = $(this);
$.ajax({
url: '{% url "fix_issue" %}',
type: 'POST',
datatype: 'json',
data: {
issueid: $issue_id.val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
action: 'post'
},
success: function (json) {
document.getElementById("fixed_bool").innerHTML = json['result']
console.log(json)
},
error: function (xhr, errmsg, err) {
}
});
});
});
html
<button class = "fix-button" value = "{{ issue.id }}">Fix</button>
views.py
def FixView(request):
if request.POST.get('action') == 'post':
result = ''
id = int(request.POST.get('issueid'))
issue = get_object_or_404(Issue, id=id)
if issue.fixed == False:
issue.fixed = True
result = str(issue.fixed)
issue.save()
else:
issue.fixed = False
result = str(issue.fixed)
issue.save()
return JsonResponse({'result': result, })
You're trying to add an eventlistener to essentially, a list, instead of a single element.
Try using the .each() method after grabbing the element.
https://api.jquery.com/each/
The backend was actually working, but the label that switches between true and false was the thing that wasn't properly updating. To fix this, I added unique id's to the label, <span id = "{{ issue.id }}">{{ issue.fixed }}</span> and got the unique id using
var issue_id = $(this).val()
document.getElementById(issue_id).innerHTML = json['result']

Ajax if more then one #mention

I am trying to make a facebook and twitter style mention system using jquery ajax php but i have a problem if i try to #mention more then one user. For example if i start to type something like the follow:
Hi #stack how are you.
The results showing #stack but if i try to mention another user like this:
Hi #stack how are you. i am #azzo
Then the results are nothing. What i am missing my ajax code anyone can help me please ?
I think there is a regex problem for search user_name. When i write some username after first one like #stack then the ajax request posting this:
f : smen
menFriend : #stack
posti : 102
But if i want to tag my other friend in the same text like this:
Hi #stack how are you. I am #a then ajax request looks like this:
f : smen
menFriend : #stack, #a
posti : 102
So what I'm saying is that apparently, ajax interrogates all the words that begin with #. It needs to do is interrogate the last #mention from database.
var timer = null;
var tagstart = /#/gi;
var tagword = /#(\w+)/gi;
$("body").delegate(".addComment", "keyup", function(e) {
var value = e.target.value;
var ID = e.target.id;
clearTimeout(timer);
timer = setTimeout(function() {
var contents = value;
var goWord = contents.match(tagstart);
var goname = contents.match(tagword);
var type = 'smen';
var data = 'f=' +type+ '&menFriend=' +goname +'&posti='+ID;
if (goWord.length > 0) {
if (goname.length > 0) {
$.ajax({
type: "POST",
url: requestUrl + "searchuser",
data: data,
cache: false,
beforeSend: function() {
// Do Something
},
success: function(response) {
if(response){
$(".menlist"+ID).show().html(response);
}else{
$(".menlist"+ID).hide().empty();
}
}
});
}
}
}, 500);
});
Also here is a php section for searching user from database:
$searchmUser = mysqli_real_escape_string($this->db,$searchmUser);
$searchmUser=str_replace("#","",$searchmUser);
$searchmUser=str_replace(" ","%",$searchmUser);
$sql_res=mysqli_query($this->db,"SELECT
user_name, user_id
FROM users WHERE
(user_name like '%$searchmUser%'
or user_fullname like '%$searchmUser%') ORDER BY user_id LIMIT 5") or die(mysqli_error($this->db));
while($row=mysqli_fetch_array($sql_res,MYSQLI_ASSOC)) {
// Store the result into array
$data[]=$row;
}
if(!empty($data)) {
// Store the result into array
return $data;
}
Looks like you're sending an array which is result of match you in AJAX request.
Though I cannot test it but you can use a lookahead in your regex and use 1st element from resulting array. Negative lookahead (?!.*#\w) is used to make sure we match last element only.
var timer = null;
var tagword = /#(\w+)(?!.*#\w)/;
$("body").delegate(".addComment", "keyup", function(e) {
var value = e.target.value;
var ID = e.target.id;
clearTimeout(timer);
timer = setTimeout(function() {
var contents = value;
var type = 'smen';
var goname = contents.match(tagword);
if (goname != undefined) {
var data = 'f=' +type+ '&menFriend=' +goname[1] +'&posti='+ID;
$.ajax({
type: "POST",
url: requestUrl + "searchuser",
data: data,
cache: false,
beforeSend: function() {
// Do Something
},
success: function(response) {
if(response){
$(".menlist"+ID).show().html(response);
} else {
$(".menlist"+ID).hide().empty();
}
}
});
}
}, 500);
});

ASP.net 3.5 WebMethod Strange Behavior, jQuery AJAX receives strange data

I've ran into this strange JSON behavior.. I just cant figure out what the hell is going on..
I've got a WebMethod in my asp.net page.. It repetitively calls as page loads through jQuery AJAX.. Everything goes pretty smooth but what strange thing happens is that the data I sens to my jQuery ajax is not the SAME I just sent.. :S
here is not code of page method
[WebMethod()]
public static List<Unister.UnisterCore.Core.Domain.Comment> LoadComments(long objID, int sysID)
{
if (objID == 0)
return null;
UnisterWeb.UserControls.Presenter.CommentsPresenter _presneter;
_presneter = new UnisterWeb.UserControls.Presenter.CommentsPresenter();
List<Unister.UnisterCore.Core.Domain.Comment> comments = new List<Unister.UnisterCore.Core.Domain.Comment>();
comments = _presneter.LoadComments(sysID, objID);
if (comments.Count == 0)
return null;
return comments;
}
Here returning list is what I got from my presenter layer but when I receive that in my js method, its either null or previous value.
Here is my jQuery method..
function LoadComments(SysID, ObjID) {
if (parseInt(SysID) == 0 || parseInt(ObjID) == 0)
return;
var args = 'objID:' + ObjID + ',sysID:' + SysID;
$.ajax({
type: "POST",
url: "/dashboard/default.aspx/LoadComments",
cache: false,
data: '{' + args + '}',
contentType: "application/json",
dataType: "json",
success: function(result) {
if (result.d != null) {
comments = new Array();
$.each(result.d, function(key, val) {
data = new Object();
data.CommentID = val.CommentID;
data.Body = val.Body;
codate = new Date(parseInt(val.CreateDate.replace("/Date(", "").replace(")/", ""), 10));
var fdate = dateFormat(codate, "isoUtcDateTime");
ldate = $.timeago(fdate);
data.CreateDate = ldate;
data.CommentByAccountID = val.CommentByAccountID;
comments.push(data);
});
var boxid = "#commentBox_" + ObjID;
$(boxid).setTemplateURL("../Templates/comments.htm");
$(boxid).processTemplate(comments);
}
}
});
}
Please help me..
I found the solution... :)
First thing we could do is make our request async: false (BUT it'll impact our performance).. Instead, Im sending an ID (in my case SysID) and also bind it with my DIV id like the code below..
<div id ="comment_<%= SysID %>"></div>
In my jQuery function I use
var ID = "#comment_" + val.SysteID;
$(ID).setTemplateURL("../Templates/comments.htm");
$(ID).processTemplate(comments);
Hope it helps you guys too ... :)

Jquery Ajax call doesn't work fine in IE8

I'm loading some data lively from the database and each row have some links that do some things over that.
They work flawlessly except for the last one I've implemented which seems not to be working on IE
$('.lockFile').click(function(){
var url = "functions/lock_call.php";
var unlock = 'assets/lock-unlock.png';
var lock = 'assets/lock.png';
var action = 'unlock';
var id = $(this).parent().parent().attr('id');
var image = $(this).children(0);
if (image.attr('src') == unlock)
action = 'lock';
var data = 'id='+id+'&action='+action;
$.ajax({
type: "POST",
url: url,
data: data,
cache: false,
success: function(){
alert (action);
if (action == 'lock')
image.attr('src', lock);
else
image.attr('src', unlock);
}
});
return false;
});
What could be wrong?
The alert is performer on "success" but nothing is made. That is, the script doesn't run.
IE 8 has some amazing variables reserved, try this one
$('.lockFile').click(function(){
var Aurl = "functions/lock_call.php";
var AunAlock = 'assets/lock-unlock.png';
var Alock = 'assets/lock.png';
var Aaction = 'AunAlock';
var Aid = $(this).parent().parent().attr('id');
var Aimage = $(this).children(0);
if (image.attr('src') == AunAlock)
Aaction = 'Alock';
var data = 'id='+Aid+'&action='+Aaction;
$.ajax({
type: "POST",
url: Aurl,
data: data,
cache: false,
success: function(){
alert (Aaction);
if (Aaction == 'lock')
Aimage.attr('src', Alock);
else
Aimage.attr('src', AunAlock);
}
});
return false;
});
try to declare data in JSON format
var data = {'id':id, 'action': action}

Categories

Resources