how to only append new data in ajax request django? - javascript

hello guys so i have this ajax script that get the data from my backend view it works but it only empty the data and replace it with the new one but what i want to do is that i want this ajax request to only get the new data that is not in my div task if the data is in my div task i want to tell it to don't append it i try to do it here:
def task_admin_manager(request):
if request.is_ajax():
data_task = task_admin_form.objects.all()
list_id_task = []
for data in data_task:
data = data.id
if data is not in list_id_task and task_admin_form.objects.filter(id__exact=data).exists():
id_fix = data_task.objects.filter(id__exact=data)
list_id_task.append(id_fix)
for id_task in id_fix:
dict_id_task = {}
dict_id_task['username'] = id_task.username.username
return Httpresponse(json.dumps(dict_id_task))
here it will returm the response
function update_task_manager(){
var append_increment = 0;
var add_data = " "
$.ajax({
method:"GET",
url:"taskadmin",
data:{'append_increment': append_increment},
success:function(response){
add_data = add_data +'<li class="admin-task">'+'
<div class="admin-image">'+'
<img src="{%static "image/dedek.jpg" %}" alt="image-admin">'+'
</div>'+'
<div class="task-admin">'+'
<div class="admin-name-due">'+'
<label>'+response.username+'</label>'+'
<small>Due: {{form_tasks.task_tenggat}}</small>'+'
</div>'+'
<div class="task-subject-task">'+'
<label>{{form_tasks.subject}}</label>'+'
<div class="button-task">'+'
<div clas="detail-task">'+'
<button id="tampilkan-detail-task" value="{{form_tasks.id}}">Detail Task<i class="fa fa-file" style="margin-left:5px"aria-hidden="true"></i></button>'+'
</div>'+'
<div class="button-status">'+'
<button><i class="fa fa-check" aria-hidden="true"></i></button>'+'
<button><i class="fa fa-trash" aria-hidden="true"></i></button>'+'
</div>'+'
</div>'+'
</div>'+'
</div>'+'
</li>'
$('task-manager').append(add_data)
}
})
}
var interval = setInterval(function(){
update_task_manager();
},5000)
because i used return it will only get one data because it will break the loop if i put the return outside the loop it will still print one data because the dict will keep appending the data with same key but different value, can someone give me a tips? or how they do it if the cases like this? thanks here is my code.
def task_admin_manager(request):
if request.is_ajax():
data_task = task_admin_form.objects.all()
return render(request,"task_mager.html",{"form_task":dict_id_task})
main.html
<div class="content-task">
<ul id="task-manager">
</ul>
</div>
task_mager.html
{% load static %}
{% for form_tasks in form_task%}
<li class="admin-task">
<div class="admin-image">
<img src="{%static 'image/dedek.jpg' %}" alt="image-admin">
</div>
<div class="task-admin">
<div class="admin-name-due">
<label>{{form_tasks.username}}</label>
<small>Due: {{form_tasks.task_tenggat}}</small>
</div>
<div class="task-subject-task">
<label>{{form_tasks.subject}}</label>
<div class="button-task">
<div clas="detail-task">
<button id="tampilkan-detail-task" value="{{form_tasks.id}}">Detail Task<i class="fa fa-file" style='margin-left:5px'aria-hidden="true"></i></button>
</div>
<div class="button-status">
<button><i class="fa fa-check" aria-hidden="true"></i></button>
<button><i class="fa fa-trash" aria-hidden="true"></i></button>
</div>
</div>
</div>
</div>
</li>
{% endfor %}
ajax script
$(document).ready(function(){
function update_task_manager(){
var append_increment = 0;
$.ajax({
method:"GET",
url:"taskadmin",
data:{'append_increment': append_increment},
success:function(response){
console.log("this is sucess function");
console.log(response);
$("#task-manager").empty()
$("#task-manager").append(response);
}
})
}
var interval = setInterval(function(){
update_task_manager();
},5000)

Related

Issue on getting id from Selected HTML elements from Ajax GET response with jQuery

I am using ajax to display product data and then delete on click a specific on using the product id but am not able to get the product id as it is showing undefine can you guys suggest something.
In this code first I am getting the product details for the cart dropdown menu and then displaying it in list format with delete button through the first ajax and then on clicking delete should delete the element in the second ajax using the elements product id which I have saved inside data-r but on console, it showing undefined can anyone tell me what is the issue. As I know that the elements are created dynamically but I am not getting a solution
function TopCartVal() {
// Used Route inside the ajax
var url = "{{ route('pdt.details', ':id') }}";
var yui = "{{ route('delete_fr.cart', ':id') }}";
// Ajax Structure
$.getJSON( "{{ route('my.cart','json') }}", function( data ) {
console.log(data);
var Cart = $('#cart_dp_sec_pdt_desc');
// Loop for data
$.each(data, function(key , value) {
console.log(value);
url = url.replace(':id', value.product_id);
yui = yui.replace(':id', value.product_id);
Cart.append(`
<div class="row">
<div class="col-xs-4">
<div class="image">
<a href="`+url+`">
<img src="{{ asset('')}}`+value.image+`" alt=""/>
</a>
</div>
</div>
<div class="col-xs-7">
<h3 class="name">
`+value.product_name+`
</h3>
<div class="price">`+value.currency+value.product_price+`</div>
</div>
<div class="col-xs-1 action">
<a href="#"
data-r"`+value.id+`"
class="cart_dp_btn_ctn_delete">
<i class="fa fa-trash"></i>
</a>
</div>
</div>
`);
});
});
}
// delete part
$(document).on('click', '.cart_dp_btn_ctn_delete', function(e){
e.preventDefault();
var id = $(this).attr('data-r'); // id of to be deleted element
var yui = "{{ route('delete_fr.cart', ':id') }}";
yui = yui.replace(':id', id);
console.log(yui);
console.log(id); // it is showing undefined`enter code here`
// $.getJSON( yui, function(data){
// TopCartVal();
// });
});
You are missing an = here:
data-r"`+value.product_id+`"
But using template literals correctly will make it easier to see
`<div class="row">
<div class="col-xs-4">
<div class="image">
<a href="${url">
<img src="{{ asset('')}}${value.image}" alt=""/>
</a>
</div>
</div>
<div class="col-xs-7">
<h3 class="name">
${value.product_name}
</h3>
<div class="price">${value.currency+value.product_price}</div>
</div>
<div class="col-xs-1 action">
<a href="#" data-r="${value.product_id}" class="cart_dp_btn_ctn_delete">
<i class="fa fa-trash"></i>
</a>
</div>
</div>`

can't refresh the data in a DIV python Django nor the page after a jquery

Let me start by saying I have 2 variables in an HTML template(messages and users) and I have multiple buttons that when one of them is clicked it calls a jquery code that sends a post request to a Django server and it returns an update to a variable(messages)
however, it's not updating the loop, I also tried to return a new HTML page that contains the new variable updated but the jquery is not updating the whole page with the new HTML
if I can update the variable alone it would be better and if I can't do that how can I make jquery use the new HTML page
the python code i used to return the update to the varialbe messages:
if request.method == 'POST':
send=Message.objects.filter(from_id=request.POST.get('userId'),to_id=2)
rec=Message.objects.filter(from_id=2,to_id=request.POST.get('userId'))
messages=sorted(chain(rec, send),key=lambda instance: instance.id,reverse=True)
print(messages)
return HttpResponse(list(messages))
and the code i used to return new HTML template:
m = Message.objects.filter(to_id=2).order_by('-id')
users = {}
for i in m:
if users.get(i.from_id.username) == None:
users[i.from_id.username] = User.objects.get(id=i.from_id.id)
users = list(users.values())
send=Message.objects.filter(from_id=users[0].id,to_id=2)
rec=Message.objects.filter(from_id=2,to_id=users[0].id)
messages=sorted(chain(rec, send),key=lambda instance: instance.id,reverse=True)
if request.method == 'POST':
send=Message.objects.filter(from_id=request.POST.get('userId'),to_id=2)
rec=Message.objects.filter(from_id=2,to_id=request.POST.get('userId'))
messages=sorted(chain(rec, send),key=lambda instance: instance.id,reverse=True)
print(messages)
return render(request,'psych.html',{"users":users, "messages":list(messages)})
return render(request,'psych.html',{"users":users, "messages":list(messages)})
the HTML code and jquery code that uses the variable and try to update it
function newUser(id){
$.ajax({
type: 'POST',
url:'/psych.html/',
data:{
userId:id,
},
success: function(data){
console.log(data);// the data returnd are correct and as needed
//but i cant make it update the messages
$('#messageDiv').load(document.URL + ' #messageDiv');
}
})
}
{% for i in users %}
<li class="">
<button type="button" class="btn" onClick="newUser({{i.id}})">
<div class="d-flex bd-highlight">
<div class="img_cont">
<!-- here was an image ----------------------------------------------->
</div>
<div class="user_info">
<span>{{i.id}}</span>
</div>
</div>
</button>
</li>
{% endfor %}
<!-- The varialbe that i'm trying to update is called messages bottom -->
{% for o in messages %}
{% if o.to_id.id != 2 %}
<div class="d-flex justify-content-start mb-4">
<div class="img_cont_msg">
<!-- here was an image-->
</div>
<div class="msg_cotainer">
{{o.message}}
<!-- <span class="msg_time">{{o.time}}</span> -->
</div>
</div>
{% else %}
<div class="d-flex justify-content-end mb-4">
<div class="msg_cotainer_send">
{{o.message}}
<!-- <span class="msg_time_send">{{o.time}}</span> -->
</div>
<div class="img_cont_msg">
<!-- here was an image-->
</div>
</div>
{% endif %}
{% endfor %}
if it helps i did it before and updated the messages from jquery but i used form and there was only 1 variable i will add the code to that too
$(document).on('submit','#submitMessage', function (e){
e.preventDefault();
$.ajax({
type: 'POST',
url:'/psych.html/',
data:{
message:$('#messageHolder').val(),
csrfmiddlewaretoken: $('input[message=csrfmiddlewaretoken]').val(),
},
success: function(data){
// it work like charm here
$('#messageDiv').load(document.URL + ' #messageDiv');
}
})
})
{% for o in messages %}
{% if o.to_id.id == 2 %}
<div class="d-flex justify-content-start mb-4">
<div class="img_cont_msg">
<!-- here was an image-->
</div>
<div class="msg_cotainer">
{{o.message}}
<!-- <span class="msg_time">{{o.time}}</span> -->
</div>
</div>
{% else %}
<div class="d-flex justify-content-end mb-4">
<div class="msg_cotainer_send">
{{o.message}}
<!-- <span class="msg_time_send">{{o.time}}</span> -->
</div>
<div class="img_cont_msg">
<!-- here was an image-->
</div>
</div>
{% endif %}
{% endfor %}
<form id="submitMessage" >
{% csrf_token %}
<div class="card-footer">
<div class="input-group">
<div class="input-group-append"></div>
<input name="message" class="form-control type_msg" placeholder="Type your message..." id="messageHolder">
<div class="input-group-append">
<button type="submit" class="btn">
<span class="input-group-text send_btn" ><i class="fas fa-location-arrow"></i></span>
</button>
</div>
</div>
</div>
</form>
Try this
$("#messageDiv").load(location.href+" #messageDiv>*");
i figured the problem and it was because i didn't know that
$("#messageDiv").load(location.href+" #messageDiv>*");
would make a GET request so all I did was adding the necessary data to the URL and then change the URL too(so if the client refreshed the page it would stay in the same spot) without refreshing the page and then do the command app there
if it could help anyone please look at the code below:
function newUser(id){
var url = document.URL;
url = url.split('/');
url[url.length-2] = id;
url = url.join('/');
window.history.pushState("object or string", "my website name", url);
$('#messageDiv').load(url + ' #messageDiv');
}
sadly i don't know how to do post requst then load the page please if you know comment down bellow so someone else might get help from it

How to data submit and page redirect same position after the button click using javascript python Django?

index.html
<div class="row">
<div class="col-md-12">
<div class="card shadow-lg">
<div class="card-body" id="div1">
<div class="row">
<div class="col-md-6">
<h5 class="card-title"><i class="fa fa-user-circle" aria-hidden="true"></i>
{{datas.user_id|capfirst}}</h5>
</div>
<div class=" col-md-6 text-right" >
{% if request.user.id == datas.user_id_id %}
<button class="btn btn-sm btn-outline-primary" onclick="load_post(this, '{{datas.id}}')" id="edit">
Edit</button>
{% endif %}
</div>
</div>
<div id="msg">
<hr>
{{datas.post}}
<hr>
</div>
<div id="one">
</div>
<div class="row">
<div class="col-md-4">
<i class="fa fa-thumbs-up" value="0" onclick="count(this, '{{datas.id}}')" id="odd"></i><span id="add"></span>
</div>
<div class="col-md-4"></div>
<div class="col-md-4 text-right">{{datas.post_date}}</div>
</div>
</div>
</div>
</div>
inbox.js
function load_post(id, data)
{
const one = id.closest(".card-body");
one.querySelector('#msg').style.display = 'none';
fetch(`/network/${data}`)
.then(res => res.json())
.then(out => {
const element = document.createElement("textarea");
element.classList.add("form-control");
element.rows = 2;
element.id = "body";
element.innerHTML = out["post"];
one.querySelector('#one').appendChild(element);
const li = document.createElement("br");
one.querySelector('#one').appendChild(li);
const button = document.createElement("button");
button.className = "btn btn-sm btn-success"
//button.classList.add("btn"," btn-primary");
button.id="sucees";
button.innerHTML = "SUBMIT";
button.addEventListener('click',() => edited(id, out["id"]));
one.querySelector('#one').appendChild(button);
})
}
function edited(id, data)
{
var two = document.querySelector('#body').value;
fetch(`/network/${data}`,{
method : 'POST',
body : JSON.stringify({
post : two
})
})
.then(res=>res.json())
.then(out=>console.log(out))
}
views.py
#csrf_exempt
def edit_post(request, post_id):
try:
post = posts.objects.get(user_id=request.user, pk=post_id)
except posts.DoesNotExist:
return JsonResponse({"Out":"Data not found"}, status=404)
if request.method == 'GET':
return JsonResponse(post.serialize())
if request.method == 'POST':
data = json.loads(request.body)
upt = data.get("post","")
post.post = data["post"]
post.save()
print(post)
return redirect(request.META['HTTP_REFERER'])
here i am sharing my index.html, inbox.js and views.py files. The user will post the data and after that they will edit thier correspoding post and after that the entire page will not reload it. when I click the submit button, the div element cannot be modified but data posted in the database. after that, I refresh the page the original posted that will appear in the div element. I need help in this regard.

How can I reach specific div in JavaScript?

I have a plp page which are listed items. And user can favorite any item.
My problem is when the user favorite one item, I want to change star icon it should be show favorited.
Here my item structure:
<div class="product-tile-top">
<div class="product-tile-top-inner tile-wishlist">
<span role="button" class="wish-list-icon" id="grc398342">
<div class="btn btn-default btn-sm pdp-wishlist-btn">
<span>
<img class="favorite" src="/_ui/responsive/common/images/favorite.svg" height="17px;">
</span>
</div>
</span>
</div>
</div>
Every item has unique id like this:
<span role="button" class="wish-list-icon" id="grc398342">
So, I want to reach and change only this section when user favorite:
<span>
<img class="favorite" src="/_ui/responsive/common/images/favorite.svg" height="17px;">
</span>
I changed my code like this but its not running?
var newURL = "/_ui/responsive/common/images/favorite-red.svg";
function fav(elemId){
$("#elemId").find(".favorite").attr("src", newURL)
}
$('#addBtn').click(function() {
var listName = $('#listName').val();
var productCode = $('#productCode').val();
$('#notificationP').text('');
if (listName.trim() == '') {
$('#notificationP').text($('#nameValidate').val());
return;
}
$('.loading-overlay').show();
$.ajax({
type : "POST",
url : ACC.config.encodedContextPath + "/wishlist/add",
data : 'productCode=' + productCode + '&listName=' + listName,
success : function(loginPopup) {
$('.loading-overlay').hide();
if (loginPopup.code == '0' || loginPopup.code == '2') {
$('#notificationP').text($('#duplicate').val());
} else if (loginPopup.code == '1') {
$('#notificationP').text($('#add').val());
fav(productCode);
}
else if(loginPopup.code == '3'){
$('#notificationP').text($('#maxProductsError').val()+' '+loginPopup.errorCodeMeg+')');
}
else {
$('#notificationP').text($('#globleError').val());
}
},
error : function(error) {
$('.loading-overlay').hide();
$('#notificationP').text($('#globleError').val());
}
});
});
How can I access this image?
Onclick of the div invoke a function and push the id of the div. Using children get the span child and make changes
function a(id) {
var ele = document.getElementById(id).children[0].children[0];
ele.style.color = "red";
ele.children[0].setAttribute('url',"www.xyz.com")
console.log(ele.children[0].getAttribute('url'))
}
<div class="product-tile-top">
<div class="product-tile-top-inner tile-wishlist">
<span role="button" class="wish-list-icon" id="grc398342" onclick=a(this.id)>
<div class="btn btn-default btn-sm pdp-wishlist-btn">
<span>dd
<img class="favorite" src="/_ui/responsive/common/images/favorite.svg" height="17px;">
</span>
</div>
</span>
</div>
</div>
You can use .find() method on the passed element in jquery like this. We give .find() the class name of the image and then change src attribute of the image. In this example if you click on the icon it will change to a star.
var newURL = "https://img.freepik.com/free-vector/start_53876-25533.jpg?size=338&ext=jpg";
function fav(elem){
$(elem).find(".favorite").attr("src", newURL)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product-tile-top">
<div class="product-tile-top-inner tile-wishlist">
<span role="button" class="wish-list-icon" id="grc398342" onclick="fav(this)">
<div class="btn btn-default btn-sm pdp-wishlist-btn">
<span>
<img class="favorite" src="https://img.freepik.com/free-vector/yellow-star-trail-set_23-2147739091.jpg?size=338&ext=jpg" height="17px;">
</span>
</div>
</span>
</div>
</div>
As for your comment how to do this in ajax. You can return the item id in your ajax call and then access it like this
var newURL = "https://img.freepik.com/free-vector/start_53876-25533.jpg?size=338&ext=jpg";
function fav(elemId){
$("#elemId").find(".favorite").attr("src", newURL)
}
// your ajax call
$.ajax({
url: "",
data: { /*Your parameters*/},
success: function(returnedData){
fav(returnedData);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product-tile-top">
<div class="product-tile-top-inner tile-wishlist">
<span role="button" class="wish-list-icon" id="grc398342">
<div class="btn btn-default btn-sm pdp-wishlist-btn">
<span>
<img class="favorite" src="https://img.freepik.com/free-vector/yellow-star-trail-set_23-2147739091.jpg?size=338&ext=jpg" height="17px;">
</span>
</div>
</span>
</div>
</div>

Ajax success function with data-id

I have a feed page that loads an individual feedLikes.php for each post on the feed. Currently, I can like each post and it updates the likes using Ajax. However, every time a like is updated, it returns to the top of the feed. Below is feedLikes.php:
if (isset($_POST['feedID'])) {
$feedID = ($_POST['feedID']);
$findHasUserLiked = $pdo->prepare('SELECT username FROM feedLikes WHERE feedID =? and username=?');
//execute query and variables
$findHasUserLiked->execute([$feedID, $username]);
if ($findHasUserLiked->rowCount() > 0) {
$hasUserLiked = $findHasUserLiked->fetchColumn();
echo <<<_END
<form action="feedLikes.php" id="unlikePostForm$feedID" method="post">
<button type="submit" class="unLikeButton"></button>
<input type="hidden" name="feedIDForUnlike" class="feedIDForUnlike$feedID" value="$feedID">
</form>
_END;
?>
<script type="text/javascript">
$(document).ready(function () {
$('#likePostForm<?php echo $feedID ?>').on('submit', function (e) {
e.preventDefault();
var feedIDLike = $(".feedIDForLike<?php echo $feedID ?>").val();
$.ajax({
url: "feedLikesClicked.php",
cache: false,
type: "POST",
data: {
feedIDLike: feedIDLike
},
dataType: "html",
success: function (html) {
location.reload();
}
});
});
});
</script>
<?php
} else {
echo <<<_END
<form action="feedLikes.php" id="likePostForm$feedID" method="post">
<button type="submit" class="likeButton"></button>
<input type="hidden" name="feedIDForLike" class="feedIDForLike$feedID" value="$feedID">
</form>
_END;
?>
<script type="text/javascript">
$(document).ready(function () {
$('#likePostForm<?php echo $feedID ?>').on('submit', function (e) {
e.preventDefault();
var feedIDLike = $(".feedIDForLike<?php echo $feedID ?>").val();
$.ajax({
url: "feedLikesClicked.php",
cache: false,
type: "POST",
data: {
feedIDLike: feedIDLike
},
dataType: "html",
success: function (html) {
location.reload();
}
});
});
});
</script>
<?php
}
$likesNumber = $pdo->prepare('SELECT count(*) FROM feedLikes WHERE feedID =?');
//execute query and variables
$likesNumber->execute([$feedID]);
$numberOfLikes = $likesNumber->fetchColumn();
print '<div class=numberOfLikes data-id="' . $feedID . '">
<p>' . $numberOfLikes . '</p>
</div>';
}
I'm aware this is because location.reload() is actually reloading all the feedLikes.php pages, not just the one post i have liked. However, i can't seem to figure out what success function i need to use to just update the one post and not take me back to the top of the feed.
I have tried placing everything in feedLikes.php in a div like so:
<div class=allLikesPage data-id="'.$feedID .'">
and then in the ajax success using this line:
$('.allLikesPage[data-id='"+ feedID +"']').load(document.URL + ' .allLikesPage[data-id='"+ feedID +"']');
However that just removes everything and doesn't update. I've also tried the same thing without the data-id amongst other things.
there you go you can see the example here I had to show how the ajax response should be encoded so I added the example on my domain
your PHP file will look like the following, I have omitted the SQL part and added only the logic on how to use json_encode with the arrays hope you find it helpful you can use this code on your local machine to look into how things are working
<?php
$response = array('success'=>false,'likes'=>0);
if(isset($_POST['count'])){
$counter = $_POST['count'];
$response['likes']=$counter+1;
$response['success']=true;
}
echo json_encode($response);
?>
your HTML page is below
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<style>
.feed {
width: 95%;
height: auto;
}
i.fa {
cursor: pointer;
}
</style>
<script type="text/javascript">
$(document).ready(function () {
$(".voteup").click(function () {
var curElement = $(this);
console.log(curElement.parent().find('.likes').text());
$.ajax({
url: 'test.php',
dataType: 'json',
data: 'count=' + curElement.parent().find(".likes").text(),
method: 'POST'
}).done(function (data) {
if (data.success) {
curElement.parent().find(".likes").html(data.likes);
} else {
alert('Some Error occoured at the server while liking the feed');
}
});
});
});
</script>
</head>
<body>
<div class="panel panel-default">
<div class="panel-heading">Panel Heading</div>
<div class="panel-body">
<div class="feed">
<p>This is my feed can someone like it</p>
<i class="fa fa-thumbs-up voteup" aria-hidden="true" ></i>
<span class="likes">0</span>
<i class="fa fa-thumbs-down votedown" aria-hidden="true" ></i>
<span class="dlikes">0</span>
</div>
<div class="feed">
<p>Another feed item</p>
<i class="fa fa-thumbs-up voteup" aria-hidden="true" ></i>
<span class="likes">0</span>
<i class="fa fa-thumbs-down votedown" aria-hidden="true" ></i>
<span class="dlikes">0</span>
</div>
<div class="feed">
<p>This is my feed can someone like it</p>
<i class="fa fa-thumbs-up voteup" aria-hidden="true" ></i>
<span class="likes">0</span>
<i class="fa fa-thumbs-down votedown" aria-hidden="true" ></i>
<span class="dlikes">0</span>
</div>
<div class="feed">
<p>This is my feed can someone like it</p>
<i class="fa fa-thumbs-up voteup" aria-hidden="true" ></i>
<span class="likes">0</span>
<i class="fa fa-thumbs-down votedown" aria-hidden="true" ></i>
<span class="dlikes">0</span>
</div>
<div class="feed">
<p>This is my feed can someone like it</p>
<i class="fa fa-thumbs-up voteup" aria-hidden="true" ></i>
<span class="likes">0</span>
<i class="fa fa-thumbs-down votedown" aria-hidden="true" ></i>
<span class="dlikes">0</span>
</div>
<div class="feed">
<p>This is my feed can someone like it</p>
<i class="fa fa-thumbs-up voteup" aria-hidden="true" ></i>
<span class="likes">0</span>
<i class="fa fa-thumbs-down votedown" aria-hidden="true" ></i>
<span class="dlikes">0</span>
</div>
</div>
</div>
</body>
</html>
EDIT:
Basically, I am just incrementing the posted variable count you do not have to do that you just need to update likes in the database once you send the ajax call and then count with an SQL query and show the output in the same format I have used.And about the $.parseJSON() you will notice that the ajax call used here has the dataType set to JSON if you have set the dataType you do not need to parse the response otherwise you should use var myData=$.parseJSON(data); and then use like myData.likes myData.success

Categories

Resources