I have a like button on multiple posts, in EJS. Problem is, when I am clicking the first like button, the form sends and updates the View accordingly.
When I click the other buttons they all seem to send and update the first form, and they also update the first button adding the 'active' class to it.
I tried deleting the IDs and adding classes, still same result.
My guess is there is a fault in my AJAX or HTML structure because form is updating the database with no problem.
HTML:
<form id='like' action="/postLike/<%=blogposts[i]._id%>?_method=PATCH" method="POST">
<% if (blogposts[i].liked == false) {%>
<div id='likeBtn' onclick="Like()" class="wrapperHearts">
<svg xmlns="http://www.w3.org/2000/svg" id="Love"><path d="M28.124,15.5615,16.7549,28.6558a1,1,0,0,1-1.51,0L3.876,15.5615A7.6866,7.6866,0,0,1,2.57,7.61a7.1712,7.1712,0,0,1,6.085-4.5752C8.915,3.0122,9.1768,3,9.4424,3A8.6981,8.6981,0,0,1,16,6.0083,8.6981,8.6981,0,0,1,22.5576,3c.2656,0,.5274.0122.7862.0352A7.1713,7.1713,0,0,1,29.43,7.61,7.6866,7.6866,0,0,1,28.124,15.5615Z" style="fill:#212123"/></svg>
</div><%}%>
<% if (blogposts[i].liked == true) {%>
<div id='likeBtn' onclick="Like()" class="wrapperHearts active">
<svg xmlns="http://www.w3.org/2000/svg" id="Love"><path d="M28.124,15.5615,16.7549,28.6558a1,1,0,0,1-1.51,0L3.876,15.5615A7.6866,7.6866,0,0,1,2.57,7.61a7.1712,7.1712,0,0,1,6.085-4.5752C8.915,3.0122,9.1768,3,9.4424,3A8.6981,8.6981,0,0,1,16,6.0083,8.6981,8.6981,0,0,1,22.5576,3c.2656,0,.5274.0122.7862.0352A7.1713,7.1713,0,0,1,29.43,7.61,7.6866,7.6866,0,0,1,28.124,15.5615Z" style="fill:#212123"/></svg>
</div><%}%>
</form>
AJAX:
let likeButton = document.querySelector('.wrapperHearts');
let frm = $('#like');
function Like(){ frm.submit()}
frm.submit(function (e) {
e.preventDefault(e);
var formData = new FormData(this);
$.ajax({
async: true,
type: frm.attr('method'),
url: frm.attr('action'),
data: formData,
processData: false,
contentType: false,
success: function (data) {
console.log("success");
console.log(data)
if (data.liked == false){
likeButton.classList.add('active')
$("#likesNumber").text(data.likes +1 + ' ' + 'Likes')
}
else{
likeButton.classList.remove('active')
$("#likesNumber").text(data.likes -1 + ' ' + 'Likes')
}
},
error: function(request, status, error) {
console.log("error")
}
});
});
In the form I am using method-override.
I have assigned the EJS dynamic ID to the rendered forms, and then I have created a function which triggered on event, gets the ID of the specific form and assigns it into the AJAX call.
HTML
<form class="likeForm" id="like<%=[i]%>" action="/postLike/<%=blogposts[i]._id%>?_method=PATCH" method="POST" onsubmit="postData(event, this.id)">
More details
var elem = $('#'+id)[0]; // I took the HTML form element in order to assign it to the new form data as seen below
var formData = new FormData(elem)
var fullDiv = $('#'+id)
var likeButton = fullDiv.find('.wrapperHearts')
var likesNumber = fullDiv.find('.likesNumber')
//Used the find() method in order to find the specific element that I want to be updated in real time.
AJAX
function postData(event, id) {
event.preventDefault(event)
var elem = $('#'+id)[0];
var fullDiv = $('#'+id)
var likeButton = fullDiv.find('.wrapperHearts')
var likesNumber = fullDiv.find('.likesNumber')
var currentUserId = <%-JSON.stringify(currentUser._id)%>
console.log(currentUserId)
var formData = new FormData(elem)
console.log(likeButton)
console.log(likesNumber)
$.ajax({
async: true,
type: elem.getAttribute("method"),
url: elem.getAttribute("action"),
data: formData,
processData: false,
contentType: false,
success: function (data) {
console.log(data);
if(!data.userLikes.includes(currentUserId)){
likeButton.addClass('active')
likesNumber[0].innerHTML = data.likes + 1 + ' ' + 'Likes'
}
else{
likeButton.removeClass('active')
likesNumber[0].innerHTML = data.likes - 1 + ' ' + 'Likes'
}
}
})
}
I am trying to send the parameter in a function but its in a loop so when i select the same function next time it first send me the previous value then send me the value that i want which causes the function to be empty and not take any value let me show you my code.
$(window).load(function(e) {
loadmore();
select_likes();
select_share();
// get_recieve_friend_requests();
// get_sent_friend_requests();
});
function loadmore() {
var lastID = $('.load-more').attr('lastID');
// alert(lastID);
jQuery.ajax({
type: 'POST',
url: '<?php echo base_url("user/get_all_post"); ?>',
data: {
id: lastID
},
dataType: 'json',
beforeSend: function(data) {
$('.load-more').show();
},
success: function(data) {
var ParsedObject = JSON.stringify(data);
var json = $.parseJSON(ParsedObject);
if (json == "") {
$("#bottom").append('<div class="btn btn-default col-md-6" >' + 'No More Results' + '</div>');
$("#Load_more_data").hide();
} else {
$postID = json[json.length - 1].id;
$('.load-more').attr('lastID', $postID);
$.each(json, function(key, data) {
var post_id = data.id;
var post_status = data.status;
var status_image = data.status_image;
var multimage = data.multimage;
if (!post_status == "" && !status_image == "") {
alert(post_id);
$("#status_data").append('<div class="media-body"><div class="input-group"><form action="" id="form_content_multimage"><textarea name="textdata" id="content_comment_multimage" cols="25" rows="1" class="form-control message" placeholder="Whats on your mind ?"></textarea><button type="submit" id="comment_button_multimage" onclick="comment_here_multimage(' + post_id + ');" >Comment</button><?php echo form_close();?></div></div></li></ul></div></div>');
}
});
}
}
});
}
function comment_here_multimage(post_id) {
$(document).on('click', '#comment_button_multimage', function(e) {
// this will prevent form and reload page on submit.
e.preventDefault();
var post_id_multimage = $('#post_id_multimage').val();
// here you will get Post ID
alert(post_id_multimage);
var Post_id = post_id;
alert(post_id);
if (post_id == post_id_multimage) {
var User_id = $('.id_data').attr('value');
var textdata = $('#content_comment_multimage').val();
alert(textdata);
alert(Post_id);
$.ajax({
type: 'POST',
url: '<?php echo base_url("user/post_comment"); ?>',
data: {
Post_id: Post_id,
User_id: User_id,
textdata: textdata
},
dataType: 'json',
success: function(data) {
console.log(data);
alert('you have like this');
jQuery('#form_content_multimage')[0].reset();
Post_id = "";
}
});
} else {
return false;
}
});
}
The post_id is being passed onclick event of the comment_here_multimage but whenver i click on it after first time same id is being passed again first then the next id passes. what can i fo to empty the post_id value once it completes.
look at these images and tell me if there is something you dont understand.
[![first time comment][1]][1]
[![second time comment][2]][2]
[![second time comment][3]][3]
[1]: https://i.stack.imgur.com/b36o4.png
[2]: https://i.stack.imgur.com/ahg3W.png
[3]: https://i.stack.imgur.com/taHAS.png
Your problem is not isolated in code. However according to my understanding.
You are binding "comment_here_multimage" function on click event of button when creating dynamic html.
Once context is loaded and user clicks that button you again binds another function on same button, which is ultimately added to the event stack.
If user clicks the button first time nothing will happen, there is no action on it. On first time it will register a handler with it.
If user click second time it will fire the handler attached on first click resulting in old postid supplied to it.
I think your problem is with passing parameter. You can set it in a custom parameter and get it later in click handler. Or you can change your handler like below.
You can change your code like this
onclick="comment_here_multimage(this,' + post_id + ');"
function comment_here_multimage(e,post_id) {
// this will prevent form and reload page on submit.
e.preventDefault();
var post_id_multimage = $('#post_id_multimage').val();
// here you will get Post ID
alert(post_id_multimage);
var Post_id = post_id;
alert(post_id);
if (post_id == post_id_multimage) {
var User_id = $('.id_data').attr('value');
var textdata = $('#content_comment_multimage').val();
alert(textdata);
alert(Post_id);
$.ajax({
type: 'POST',
url: '<?php echo base_url("user/post_comment"); ?>',
data: {
Post_id: Post_id,
User_id: User_id,
textdata: textdata
},
dataType: 'json',
success: function(data) {
console.log(data);
alert('you have like this');
jQuery('#form_content_multimage')[0].reset();
Post_id = "";
}
});
} else {
return false;
}
;
}
My onclick event only works on double click. I searched the previous similar questions also but none of them worked. Please if anyone can help me with this.
function getDetails(tablename,field)
{
goToFind("0"+tablename);
var prntid=sessionStorage.getItem('prnt_id');
$.ajax({
url: 'addresses/getAddressDetails',
type: "post",
data: {'tablename':tablename,'fld':field,'prntid':prntid},
success: function(data){
var obj = JSON.parse(data);
res=res.split("|");
var str="<center><input type='button' value='Exit' onclick=javascript:window.close();opener.window.focus();></center><br/><table border=1>";
str+="<tr>";
for(var i=0;i<res.length;i++)
{
str+="<th>"+res[i]+"</th>";
}
str+="</tr>";
for(j=0;j<obj.length;j++)
{
str+="<tr>";
for(i=0;i<res.length;i++)
{
str+="<td>"+obj[j][res[i]]+"</td>";
}
str+="</tr>";
}
str+="</table>";
z = window.open('', 'popUp','height=' + screen.height + ',width=' + screen.width + ',resizable=yes,scrollbars=yes,toolbar=yes,menubar=yes,location=yes');
z.focus();
z.document.open();
z.document.write(str);
}
});
}
Here I am calling my method from index page
<button class="w3-btn w3-brown" value='skip' onclick="getDetails('addresses','party_id')">Current Party Address</button>
I have a textbox in my view page. when i click on imageIcon,it will take data from db and return in alert successfully. But, when i try to bind this response data to textbox, it is not binded correctly. My code in view page is as following :
#foreach (var dateitem in list)
{
<td id="HoursTxt">
#Html.TextAreaFor(modelitem => dateitem.Hours, new { id = string.Format("txtHours"), style = "width:50%;height:70%;" })
#Html.Hidden("CuDate", dateitem.Date)
<img src="~/Images/comment.png" class="prevtest" />
<div style="border:solid;display:none;">
<input type="text" id="TxtNotess" />
<input type="button" id="BtnComment" value="Save" />
</div>
</td>
}
In my onclick event of imageIcon jquery is following:
$('.prevtest').on('click', function () {
var Cudate = $(this).prev('#CuDate').val();
var ProjId = parseInt($(this).parents('tr').find('input[type="hidden"]').val());
var TskId =parseInt($(this).parents('tr').find('td').find('#testTaskId').val());
$.ajax({
type: "POST",
url: "/Timesheet/GetComments?ProjectId=" + ProjId + "&TaskId= " + TskId + "&date= " + Cudate,
success : function(data)
{
alert(data);
$('#TxtNotess').val(data);
alert('success');
},
error:function()
{
alert('Error');
}
});
$(this).next().toggle();
});
the text box with id TxtNotess not bind with response value
Can anyone help me to do this..
Thanks in advance..
First: ID of an element must be unique so use class for the textfield TxtNotess.
<input type="text" class="TxtNotess" />
Then, in the success handler find the textfild with class TxtNotess inside the next sibling of the clicked element
$('.prevtest').on('click', function () {
var Cudate = $(this).prev('#CuDate').val();
var ProjId = parseInt($(this).parents('tr').find('input[type="hidden"]').val());
var TskId = parseInt($(this).parents('tr').find('td').find('#testTaskId').val());
$.ajax({
type: "POST",
url: "/Timesheet/GetComments?ProjectId=" + ProjId + "&TaskId= " + TskId + "&date= " + Cudate,
context: this,//pass a custom context to the ajax handlers - here the clicked element reference
success: function (data) {
alert(data);
$(this).next().find('.TxtNotess').val(data);//find the target textfield
alert('success');
},
error: function () {
alert('Error');
}
});
$(this).next().toggle();
});
$('.prevtest').on('click', function () {
var Cudate = $(this).prev('#CuDate').val();
var ProjId = parseInt($(this).parents('tr').find('input[type="hidden"]').val());
var TskId = parseInt($(this).parents('tr').find('td').find('#testTaskId').val());
$.ajax({
type: "POST",
url: "/Timesheet/GetComments?ProjectId=" + ProjId + "&TaskId= " + TskId + "&date= " + Cudate,
context: this,//pass a custom context to the ajax handlers - here the clicked element reference
success: function (data) {
alert(data);
$('.TxtNotess').val(data);//find the target textfield
alert('success');
},
error: function () {
alert('Error');
}
});
$(this).next().toggle();
});
I gets resolved by using class name for textbox..
Here's my button that calls the try again function
function tryagain(context) {
//alert(context.parent());
var somedata = context.parent().parent().find('td')[0].innerHTML;
//alert(somedata);
$.ajax({
type: "POST",
url: "checkagain.php",
data: {
somedata: somedata
},
success: function (data) {
var grandparent = context.parent().parent();
var parent = context.parent();
context.remove();
parent.remove(); * * grandparent.append("<td>" + data + "</td>");
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick='tryagain($(this))' class='btn btn-danger'></button>
When I append the td with grandparent, sometimes it appends it fine and most times it just adds another empty td at the end as attached in picture provided data is not empty.