Ajax success function with data-id - javascript

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

Related

How do i make div refreshing to work properly

FIXED
I have options for user to select if he is Online, Away...etc
When i select Away for example, in mysql database i get away status. So, selecting status is working perfect. The problem is that i want when user select status, function submit_status gets called and $('#statusRefresh').load(' #statusRefresh'); should refresh the div where his current status is displayed, but when i select for example Away, the status stays Online, and when i select Busy, the status changes to Away, but when i refresh the page, status goes to Busy. It's like late by one step, showing me only previous status. Sometimes happens like when i select, nothing happens, remains the old status, and when i select another, i get previous. The problem should be something about refreshing that div in correct time (when i select status).
This is the list of all statuses:
public function getStatusText($value){
if($value == '1'){
echo '<i class="fas fa-check-circle text-success"></i> Online';
}else if($value == '2'){
echo '<i class="fas fa-clock text-warning"></i> Away';
}else if($value == '3'){
echo '<i class="fas fa-minus-circle text-danger"></i> Busy';
}else if($value == '4'){
echo '<i class="fas fa-times-circle text-info"></i> Invisible';
}
}
This needs to be refreshed when i change status:
<li class="list-group-item" data-bs-toggle="modal" data-bs-target="#statusModal"><div id="statusRefresh"><?php echo $user->getStatusText(escape($user->data()->status)); ?></div>
This is how i select status:
<div class="modal fade" id="statusModal" tabindex="-1" aria-labelledby="statusModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm modal-dialog-centered">
<div class="modal-content">
<div class="modal-header bg-darkblue">
<h5 class="modal-title" id="statusModalLabel">Status</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="d-grid gap-2">
<button type="button" onclick="submit_status(1)" class="btn btn-light border text-start"><i class="fas fa-check-circle text-success"></i> Online</button>
<button type="button" onclick="submit_status(2)" class="btn btn-light border text-start"><i class="fas fa-clock text-warning"></i> Away</button>
<button type="button" onclick="submit_status(3)" class="btn btn-light border text-start"><i class="fas fa-minus-circle text-danger"></i> Busy</button>
<button type="button" onclick="submit_status(4)" class="btn btn-light border text-start"><i class="fas fa-times-circle text-info"></i> Invisible</button>
</div>
</div>
</div>
</div>
</div>
This is how i call for refresh:
function submit_status(value){
$.ajax({
type: "POST",
url: "index.php",
data: {
value : value,
success: function (data) {
$('#output').html(data);
$('#statusModal').modal('hide');
$('#statusRefresh').load(' #statusRefresh');
}
}
});
}
FIXED:
function submit_status(value){
$.ajax({
type: "POST",
url: "index.php",
data: { value: value },
dataType: "html",
success: function (data) {
$('#output').html(data);
$('#statusModal').modal('hide');
$('#statusRefresh').load(' #statusRefresh');
}
});
}
I didn't notice that i put success inside data...

how to only append new data in ajax request django?

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)

How to create onclick ajax function in prestashop (1.7) and build right url link

I created an ajax reference in javasctript and I expect the link to be realized, it has appealed to the ajax_[modulename].php file in the background, but the url address is ignored and the main address is inserted into the module. I do not know what is causing this. Please help.
I created the javascript code in the file .... tpl as below. Then I added the ajax_[modulename].php file which I placed in the main module directory
The expected effect is to display messages that confirm this part is working correctly.
Unfortunately, this is not done in the background and the reference that is returned is the main link of the module.
The site is reloaded and the link "index.php? Controller = AdminModules & token = 3213789e146f56adaa445b96bb79956f & configure = dpeasye & module_name = dpeasy & List" is executed.
File - display_list.tpl
<td class="text-right">
<div class="btn-group-action pull-right">
<a class="btn btn-outline-info" href=".../index.php?controller=AdminModules&token=3213789e146f56adaa445b96bb79956f&configure=dpeasye&module_name=dpeasye&id_field=47&ListDic=mg">
<i class="icon-layer"></i>
Display Sub
</a>
<a class="btn btn-outline-info" href=".../index.php?controller=AdminModules&token=3213789e146f56adaa445b96bb79956f&configure=dpeasye&module_name=dpeasye&id_field=47&UpdateDic=mg">
<i class="icon-edit"></i>
Edytuj
</a>
<a class="btn btn-outline-info" href=".../index.php?controller=AdminModules&token=3213789e146f56adaa445b96bb79956f&configure=dpeasye&module_name=dpeasye&id_field=47&DeleteDic=mg">
<i class="icon-trash"></i>
Delete
</a>
<a id="active-47" class="btn btn-success ajax-status" href=" " title="Enabled">
<i class="icon-check"></i>
Enabled
</a>
</div>
</td>
<td class="text-right">
<div class="btn-group-action pull-right">
<a class="btn btn-outline-info" href=".../index.php?controller=AdminModules&token=3213789e146f56adaa445b96bb79956f&configure=dpeasye&module_name=dpeasye&id_field=65&ListDic=tt">
<i class="icon-layer"></i>
Display Sub
</a>
<a class="btn btn-outline-info" href=".../index.php?controller=AdminModules&token=3213789e146f56adaa445b96bb79956f&configure=dpeasye&module_name=dpeasye&id_field=65&UpdateDic=tt">
<i class="icon-edit"></i>
Edytuj
</a>
<a class="btn btn-outline-info" href=".../index.php?controller=AdminModules&token=3213789e146f56adaa445b96bb79956f&configure=dpeasye&module_name=dpeasye&id_field=65&DeleteDic=tt">
<i class="icon-trash"></i>
Delete
</a>
<a id="active-65" class="btn btn-success ajax-status" href=" " title="Enabled">
<i class="icon-check"></i>
Enabled
</a>
</div>
</td>
File - display_list.tpl
<script type="text/javascript">
$('a.ajax-status').click(function() {
var MainUrl = "";
var abtn = $(this);
var aidall = $(this).attr('id');
var aid = $(this).attr('id').replace('active-', '');
var aclass = $(this).attr('class').split(' ');
var atitle = $(this).attr('title');
var atext = $(this).text();
atext = atext.replace('\n', '');
var iclass = $(this).children().attr('class');
var data = '&id_field=' + aid ;
$.ajax({
url: baseDir + 'modules/dpeasye/ajax_dpeasye.php?action=changeStatus',
type: 'POST',
data: data,
cache: false,
dataType: "JSON",
success: function(aid){
if (aclass.class[2] == 'btn-danger'){
abtn.fadeOut(700);
atext.replace('Enabled','Disabled');
aclass[2].replace('btn-success','btn-danger');
atitle.replace('Enabled','Disabled');
iclass.replace('icon-check','icon-remove');
abtn.fadeIn(700);
}
if (aclass.class[2] == 'btn-danger'){
abtn.fadeOut(700);
atext.replace('Disabled','Enabled');
aclass[2].replace('btn-danger','btn-success');
atitle.replace('Disabled','Enabled');
iclass.replace('icon-remove','icon-check');
abtn.fadeIn(700);
}
showSuccessMessage(update_success_msg);
},
failure:function(aid){
console.log('test ok');
}
});
});
</script>
File - ajax_dpeasye.php
include_once('../../config/config.inc.php');
include_once('../../init.php');
include_once('dpeasye.php');
if (isset($_GET['action'])) {
switch ($_GET['action']) {
case 'changeStatus':
$this->displayConfirmation($this->trans('Test passed'));
break;
case 'sort':
break;
}
} else {
die('no action passed');
}
Why does the main link appear if there is no link in the link: "<a id="active-65" class="btn btn-success ajax-status" href="" title="Enabled"> <i class = "icon -check "> </ i> Enabled </a>"?
What is the reason that the javascript code is not being executed?

Call action on button outside function

I wrote a script where I add items to individual sections on the page. I will show you this by the example of one particular section. The problem appears with the c-grid-box, which is responsible for the fadeOut of the parent div. The anonymous function responsible for this action must be called outside of the diva addition function (otherwise I would have to add a function to each call that misses the target). For this I wrote something like this, although it still does not work - what could be the reason here?
function showModal(type) {
switch(type) {
case "title":
$(".overlay").fadeIn("slow");
$("#modal-inputs").html('<input type="text" placeholder="Title..." class="param-title" name="param-title" /><input type="text" placeholder="Description..." class="param-description" name="param-description" /><input type="submit" class="add-btn" id="insert-title" value="Insert" />');
break;
}
}
$("#add-text").on("click", function() {
showModal("title");
$("#insert-title").on("click", function() {
title = $(".param-title").val();
description = $(".param-description").val();
$('#section-title').append('<div class="grid-1-5"><div class="grid_box">Delete</i><p class="grid-box-title">'+title+'</p><p>'+description+'</p></div></div>');
$(".overlay").fadeOut("slow");
});
});
$(".grid_box").on("click", ".c-grid-box", function() {
alert("foo bar");
});
.overlay {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add-text">
<i class="fa fa-align-justify" aria-hidden="true"></i>
<p>Add <i class="fa fa-angle-right" aria-hidden="true"></i></p>
</button>
<section class="add-box" id="section-title">
</section>
<div class="overlay">
<div class="modal-box">
<p class="modal-title"><i class="fa fa-cogs" aria-hidden="true"></i>Settings
<i class="fa fa-times" aria-hidden="true"></i>
</p>
<div id="modal-inputs">
</div>
</div>
</div>

Remove message from view?

Each time a user clicks un read the div area should remove, below is my HTML and javascript. Whats happening at the moment is that when you click unread it does everything in the back end and not in the front end screen, I think its got to do with my JavaScript line $('#Unreadmessage').closest(".messagearea").remove(); please advise
<div class="alert alert-default alert-dismissible messagearea" role="alert" style="background: rgb(233, 233, 233);">
<button class="close" aria-label="Close" type="button" data-dismiss="alert"><span aria-hidden="true">×</span></button>
<div id="Unreadmessage" class="markmessage" data-messageid="#message.Id">
<p class="small"><i class="fa fa-envelope" aria-hidden="true"></i> Unread</p></div>
<p class="small"><i class="fa fa-calendar" aria-hidden="true"></i> #message.CreatedOn.ToString("dd MMM yyyy")</p>
<p class="small" style="font-weight: bold;"><i class="fa fa-info" aria-hidden="true"></i> Claim ref. #message.CaseNumber</p>
<p>#message.Message More.</p>
</div>
Below is my Javascript
$("#Unreadmessage").click(function () {
var messageId = $(this).data("messageid"); //need to pass this message ID to controller.
var isread = true; //True by default
//I need to pass the messageID to server which is CRM
$.ajax({
url: "#Url.Action("MarkMessage", "Enquiry")", //Need to add my URl here
type: "POST",
data: { messageId: messageId, isread: true }, //Get messageId and isread values
dataType: "json",
success: function (response) {
$('#Unreadmessage').closest(".messagearea").remove();
}
});
If you mean removing the content just like clicking x, then that can also be achieved by just placing data-dismiss="alert" at p(the unread container).
To remove just the unread, it will be best to update the back-end to isread(for example) when More is clicked. You then have to decide whether to display Read or displaying nothing.
<p data-dismiss="alert" class="small"><i class="fa fa-envelope" aria-hidden="true"></i> Unread</p>

Categories

Resources